0

I created a button that allows to create a zip file., the function that zips the file works correctly, but when I call her via the button (in the JS file) it crashes and it gives a blank page (I think I do not manage the output stream) would please an idea

(this is a new modified version (for those who see that it is the same question)

here is the code :

Button

 isc.ToolStripButton.create({
    ID: "BooksApp_GetXmlImage_Button"
    ,autoDraw:false
    ,icon: getUIIcon("icon_xml_16")
    ,prompt: getUIMsg("book_report_get_xml",4)
    ,showHover:true
    ,hoverStyle:"book_hover_style"
    ,click : function () {
        BooksApp_Action_loadFile("objx");
        // isc.say("test");
        }
});

function to call the zipfile() method:

  function BooksApp_Action_loadFile(p_UsedFormat) {
        var tmpBookID = BooksApp_Application.FP_BookID;
        var tmpIDs = BooksApp_Application.FP_fct_getSelectedPOVIDs();
        var tmpUsr_ID = FPIUser.FP_fct_getID();
        var tmpFormat = p_UsedFormat;

        var showInWindow=false;
        books_objects.exportData(
                {
                 r_book_idnum   :   tmpBookID
                ,sBook_ID       :   tmpBookID
                ,sPOV_IDs       :   tmpIDs
                ,sUser_ID       :   tmpUsr_ID
                ,sFormat        :   tmpFormat
                }
                ,{ operationId: "customExport" 
                    ,exportDisplay: (showInWindow ? "window" : "download") }
                ,function (dsResponse, data, dsRequest) {
                    //Never called
                    BooksApp_Action_Log("BooksApp_Action_loadFile:"+data);
                    }
                );
    }

customExport() function

     public static String customExport(RPCManager rpc,
                      HttpServletResponse response) throws Exception {
                String sReturn = _Return_OK;
                try {
                      // setting doCustomResponse() notifies the RPCManager that we'll
                      // bypass RPCManager.send
                      // and instead write directly to the servletResponse output stream
                      rpc.doCustomResponse();
                      RequestContext.setNoCacheHeaders(response);

                      writeServerDebug("customExport : start");
                      DSRequest req = rpc.getDSRequest();

                      List<?> results = req.execute().getDataList();

                      String sReqData = (String) req.getParameter("exportDisplay");
                      String sReqData_sBook_ID = "" + req.getCriteriaValue("sBook_ID");
                      String sReqData_sPOV_IDs = "" + req.getCriteriaValue("sPOV_IDs");
                      String sReqData_sUser_ID = "" + req.getCriteriaValue("sUser_ID");
                      String sReqData_sFormat  = "" + req.getCriteriaValue("sFormat");

                      StringBuilder content = new StringBuilder("get (sReqData:"
                                  + sReqData + ",sBook_ID:" + sReqData_sBook_ID
                                  + ",sPOV_IDs:" + sReqData_sPOV_IDs + ",sUser_ID:"
                                  + sReqData_sUser_ID + ",sFormat:" + sReqData_sFormat + ")"
                                  + results.size() + " line(s):");

                      for (Iterator<?> i = results.iterator(); i.hasNext();) {
                            Map<?, ?> record = (Map<?, ?>) i.next();
                            content.append("\n" + Books.Column_IDNum + ":"
                                       + record.get(Books.Column_IDNum));
                            content.append("\n" + Books.Column_Name + ":"
                                       + record.get(Books.Column_Name));
                      }

                      writeServerDebug("The content is \n" + content.toString());

                      // Create the new Office Engine
                      OfficeEngine myOfficeEngine = new OfficeEngine();

                      boolean bIsConnected = myOfficeEngine.get_RepositoryBridge()
                                  .connectSourceDataBase(false);
                      if (bIsConnected) {
                            //Connected to the repository, so get the files
                            if (sReqData_sFormat.equalsIgnoreCase("pdf") || sReqData_sFormat.equalsIgnoreCase("pptx")) {
                                  //The book end user format 
                                  String sReturnPptx = myOfficeEngine.performGeneratePptx(
                                             req.getHttpServletRequest(), response,
                                             sReqData_sBook_ID, sReqData_sPOV_IDs,
                                             sReqData_sUser_ID, sReqData_sFormat);
                                  writeServerDebug("customExport call performGeneratePptx, return is "+ sReturnPptx);

                            }
                            else if (sReqData_sFormat.equalsIgnoreCase("objx")) {
                                 //String sReturnObjx = myOfficeEngine.performExport(req.getHttpServletRequest(), response,sReqData_sBook_ID,sReqData_sUser_ID,sReqData_sFormat
                                   //       );
                                String sReturnPptx = myOfficeEngine.performExport(req.getHttpServletRequest(), response,sReqData_sBook_ID,sReqData_sUser_ID,sReqData_sFormat
                                         );

                                writeServerDebug("customExport call performGeneratePptx, return is " + sReturnPptx);

                            }
                            //Free the connection to repository
                            myOfficeEngine.get_RepositoryBridge().freeConnectionSource();
                      } else {
                            response.setContentType("text/plain");
                            response.addHeader("content-disposition",
                                       "attachment; filename=book.txt");
                            ServletOutputStream os = response.getOutputStream();
                            os.print(content.toString());
                            os.flush();
                      }
                } catch (Exception e) {
                      writeServerDebug("ERROR:" + e.getLocalizedMessage());
                      sReturn = Repository._Return_KO;
                }
                return sReturn;
          }

PerformExport method :

   public String  performExport(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response, 
            String p_sBook_ID,  String p_sUser_ID, String p_sFormat) {

    //public String performExport(String p_sBook_ID,  String p_sUser_ID, String p_sFormat) {

            String sReturn = _Return_OK;

                  writeServerDebug("performExport(req,resp,'" + p_sBook_ID + "'," + p_sUser_ID + "," + p_sFormat + "):start");

                  // ====================================================
                  // = Get the template directory
                  // ====================================================
                  FilerManager myFiler = new FilerManager();
                  String sInputPath = myFiler.getDirectory(
                  FilerManager.DirectoryKind_Users, true);
                  // Here add TMP directories to write XML's structure and ZIP
                  // sInputPath+="TMP";

                  // ====================================================
                  // = Working variables JDBC objects.
                  // ====================================================
                  Connection con = null;
                   Statement stmt = null;
                   ResultSet rs = null;
                   String SQL = "";
                  // String sLogMsg = "loadSourceDataBaseParams():";
                  // PreparedStatement prepStmtTarget = null;

                  try {
                        writeServerDebug("performExport >> START");
                        // ---------------------------------------------------------
                        // - Establish the connection.
                        // ---------------------------------------------------------
                        con = get_RepositoryBridge().getSourceDataBaseConnection();
                  } catch (Exception ex) {
                        sReturn = Repository._Return_KO;
                  }

                  HashMap<String, Object> _hCacheBook = new HashMap<String, Object>();
                  try {
                        int iSrcCount = get_RepositoryBridge().cacheQueryData(
                                   "SELECT TOP(1) * FROM " + Books.Table + " WHERE "
                                               + Books.Column_IDNum + "=" + p_sBook_ID,
                                   _hCacheBook, "DataBase_Source");
                        int iColCount = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
                        String sColDesc = (String) (_hCacheBook.get("SQL_ColumnDesc"));
                        String sColValues = (String) (_hCacheBook
                                   .get("SQL_ColumnValues"));

                        writeServerDebug("performExport:iColCount=" + iColCount);
                        writeServerDebug("performExport:sColDesc=" + sColDesc);
                        writeServerDebug("performExport:sColValues=" + sColValues);


                        for (int iLineCounter = 1; iLineCounter <= iSrcCount; iLineCounter++) {
                              for (int iColCounter = 1; iColCounter <= iColCount; iColCounter++) {
                                   String sTmpColClass = (String) (_hCacheBook
                                               .get("SQL_ColumnDescClass(" + iColCounter + ")"));// return

                                   if (sTmpColClass.equals("java.lang.String")) {

                                          System.out.println(_hCacheBook.get(iLineCounter+"_"+iColCounter));
                                   }

                                   else if (sTmpColClass.equals("java.lang.Integer")) {

                                          System.out.println(_hCacheBook.get(iLineCounter+"_"+iColCounter));

                                   } else if (sTmpColClass.equals("java.lang.Double")) {

                                          System.out.println(_hCacheBook.get(iLineCounter+"_"+iColCounter));
                                   }  

                              }

                        }
                        int nbrCol = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
                        System.out.println("test nbr col : "+ nbrCol);
                        ZipOutputStream objx = this.CreatXml(nbrCol, 1, _hCacheBook);
                        response.setHeader("Content-disposition",
                                "attachment;filename=\testJS.zip\"");  

                        String sContentType = "application/vnd.ms-objx";  
                        response.setContentType(sContentType);

                        ServletOutputStream outStream = response.getOutputStream();
                        outStream.close();
                  }

                  catch (Exception ex) {
                        System.out.println("I AM IN THE EXCEPTION :");
                        ex.printStackTrace();
                  }


            return sReturn;
      }
SBarney
  • 39
  • 1
  • 1
  • 11
  • Does your `performExport` method work as expected? Do you have a Unit Test or something like that? Where is the connection between `ZipOutputStream objc` and the response. You get the OutputStream of the response and simply close it. The `for` loop seems to do nothing than writing some output to `System.out`. – andih Mar 24 '14 at 14:43
  • yes performExport and CreateXml method work properly when I tested in the console! the problem is that I can not, as you have said, make a link between the file that I generate and response. the for loop that contains the System.out is made ​​just for the test console – SBarney Mar 25 '14 at 08:51
  • I did the same thing for a file pptx and it works! response.setHeader("Content-disposition", "attachment;filename=\"" + sFileTarget + "\""); String sContentType = "application/vnd.ms-powerpoint"; response.setContentType(sContentType); ServletOutputStream outStream = response.getOutputStream(); ppt.write(outStream); outStream.close(); – SBarney Mar 25 '14 at 08:57
  • In the Powerpoint case you have `ppt.write(outStream)` in the objx case you have a `ZipOutputStream` which seems to have no connection to the `ResponseOuputStream` and `ServletOutputStream outStream = response.getOutputStream();outStream.close();` which simply does ... nothing. So I don't see where the objx / zip file is sent to the client / written to the response output stream. – andih Mar 25 '14 at 09:13
  • exactly! that's what I'm looking for! I do not know what focntion use to send this file to the client i.e assign the file to the output stream – SBarney Mar 25 '14 at 09:24
  • OK - then you should rephrase your Question. – andih Mar 25 '14 at 09:54
  • You have different options. You either have to pass the ResponseOutputStream to the `CreatXML` method. Or your `CreatXML` method has to return something like a byte array. Or your `CreatXML` writes the content of the Zip file to a temporary directory and you read / copy the content in your `PerformExport` method. – andih Mar 25 '14 at 10:00
  • Why? I said that I think not managing the output stream, isn't it? – SBarney Mar 25 '14 at 10:03
  • You have posted a lot of code which is not related to your problem. Anybody who tries to help you has to go to all that stuff to figure out what's the problem. The Problem itself has nothing to do with Button or smart client. The only thing you want to know how it is possible to write the content of a `ZipOutputStream` to the Servlet Response. Btw. `performExport` can't work properly. – andih Mar 25 '14 at 10:14
  • yes! but I'm not sure if this is the real problem, that's why I posted it all to see if I have other errors. thank you anyway for your help – SBarney Mar 25 '14 at 10:24
  • You should always keep in mind that it's very hard to go to the (incomplete) code of others and tell what's the problem. Here is some page which explains you what to consider when [asking about code](http://www.catb.org/~esr/faqs/smart-questions.html#code). – andih Mar 25 '14 at 11:55

1 Answers1

0

I solved the problem and here is the right code

PerformExport method :

public String  performExport(javax.servlet.http.HttpServletRequest request,javax.servlet.http.HttpServletResponse response, 
        String p_sBook_ID,  String p_sUser_ID, String p_sFormat) {

        String sReturn = _Return_OK;
            try {

                 writeServerDebug("performExport(req,resp,'" + p_sBook_ID + "'," + p_sUser_ID + "," + p_sFormat + "):start");

                  // ====================================================
                  // = Get the template directory
                  // ====================================================
                  FilerManager myFiler = new FilerManager();
                  String sInputPath = myFiler.getDirectory(
                  FilerManager.DirectoryKind_Users, true);

                  // ====================================================
                  // = Working variables JDBC objects.
                  // ====================================================
                   Connection con = null;
                   Statement stmt = null;
                   ResultSet rs = null;
                   String SQL = "";

                  try {
                        writeServerDebug("performExport >> START");
                        // ---------------------------------------------------------
                        // - Establish the connection.
                        // ---------------------------------------------------------
                        con = _RepositoryBridge.getSourceDataBaseConnection();
                  } catch (Exception ex) {
                        sReturn = Repository._Return_KO;
                  }

                  HashMap<String, Object> _hCacheBook = new HashMap<String, Object>();
                  try {
                        int iSrcCount = get_RepositoryBridge().cacheQueryData("SELECT TOP(1) * FROM " + Books.Table + " WHERE " + Books.Column_IDNum + "=" + p_sBook_ID,  _hCacheBook, "DataBase_Source");
                        int iColCount = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
                        String sColDesc = (String) (_hCacheBook.get("SQL_ColumnDesc"));
                        String sColValues = (String) (_hCacheBook
                                   .get("SQL_ColumnValues"));

                        int nbrCol = (Integer) (_hCacheBook.get("SQL_ColumnCount"));
                        String sContentType = "application/vnd.ms-objx";
                        response.setContentType(sContentType);

                        ServletOutputStream outStream = new ServletOutputStream() {
                            @Override
                            public void write(int arg0) throws IOException {
                                // TODO Auto-generated method stub
                            }
                        };

                        outStream = response.getOutputStream();
                        this.CreatXml(nbrCol, 1, _hCacheBook, outStream, response );      
                        outStream.flush();
                        outStream.close();
                  }

                  catch (Exception ex) {
                        System.out.println("I AM IN THE EXCEPTION :");
                        ex.printStackTrace();
                  }

    }
            catch (Exception e) {
                writeServerDebug("ERROR:" + e.getLocalizedMessage());
                sReturn = Repository._Return_KO;
          }
            return sReturn;
      }

CreatXML method:

public ZipOutputStream CreatXml(int nbr_col, int iLineCounter,
              HashMap<String, Object> H, ServletOutputStream out , javax.servlet.http.HttpServletResponse response ) throws IOException {

            ZipOutputStream zipfile = null;
            String BookName = null;
            String BookID = null;
            int axisID = 11 ;
            String TemplateChild = null;
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = null;
            try {
                    writeServerDebug("call function Create XML");
                    docBuilder = docFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e2) {

                  e2.printStackTrace();
            }
            // Element : book_objects
            String tableName = "book_objects";
            org.w3c.dom.Document doc = docBuilder.newDocument();
            Element p_tableName = doc.createElement(tableName);
            doc.appendChild(p_tableName);

            // Element : object
            Element p_object = doc.createElement("object");
            String []platformeversion = JavaFunctions.convertStringToArray(Repository.Portal_Version, "=");
            p_object.setAttribute("version", platformeversion[1]+"  "+getVersion());
            p_tableName.appendChild(p_object);

            String tabCol = (String) (H.get("SQL_ColumnDesc"));
            String[] colName = JavaFunctions.convertStringToArray(tabCol, ", ");
            String [][]dep = null;
            dep = Dependances.sReturnDependance();
            String [][]colVal = new String [9][2];
            int c=0;
            for (int i = 1; i <= nbr_col; i++) {

                  String columnName = colName[i - 1];
                  columnName = columnName.replaceAll(" ", "");
                  columnName = columnName.replace("(", "");
                  columnName = columnName.replace(")", "");

                  Element nomChamps = doc.createElement(columnName);

                  String value = "";
                  value = "" + H.get(iLineCounter + "_" + i);
                  if(columnName.equalsIgnoreCase(Books.Column_Name)){
                      BookName = value;
                  }
                  if(columnName.equalsIgnoreCase(Books.Column_IDNum)){
                      BookID = value;
                  }
                  if(columnName.equalsIgnoreCase(Books.Column_axis_main_idnum)){
                      axisID = (Integer) H.get(iLineCounter + "_" + i);

                  }
                  if(columnName.equalsIgnoreCase(Books.Column_Template_Child)){
                      TemplateChild = (String) H.get(iLineCounter + "_" + i);

                  }

                  //retrieve the columns and their values for the dependencies
                  for(int cpt=0; cpt<5; cpt++){
                        if(dep[cpt][0].equalsIgnoreCase(columnName)){
                          colVal[c][0]=columnName;
                          colVal[c][1]= value;
                          c++;
                        }
                  }
                    nomChamps.appendChild(doc.createTextNode((String) value));
                    p_object.appendChild(nomChamps);

            }

            String label[] = JavaFunctions.convertStringToArray(TemplateChild, "/");
            String path = "C:\\Fovea_Repository/output/";
            File outputdirectory = new File (path);

            // Create the output file
            String fileName ="ExportDirectory"+ BookName +".zip";
            response.setHeader( "Content-Disposition", "filename=" + fileName );          
            Transformer tf = null;
            try {

                  tf = TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException e1) {

                  e1.printStackTrace();
            } 
            try {
                  // Format XML
                  tf.setOutputProperty(OutputKeys.INDENT, "yes");
                  tf.setOutputProperty(OutputKeys.METHOD, "xml");
                  tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                  tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
                  File directory = new File ("C:/Fovea_Repository/ExportDirectory/");
                  if(!directory.exists()){
                      directory.delete();
                      directory.mkdir();
                    }
                  DOMSource source = new DOMSource(doc);
                  StreamResult res = new StreamResult(new File("C:/Fovea_Repository/ExportDirectory/dependance.xml"));
                  tf.transform(source, res);



                  //create a zip file (Export_directory)
                  AppZip appZip = new AppZip();
                  String sourcefolder = "C:/Fovea_Repository/ExportDirectory"; 
                  String outputfoler  = " ";

                  ZipOutputStream returnFile = appZip.ZipFile(outputfoler , sourcefolder , out, BookName , BookID);
                  zipfile = returnFile;


            } catch (TransformerException e) {
                  e.printStackTrace();
            }

           return zipfile;
      }
SBarney
  • 39
  • 1
  • 1
  • 11