Question

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;
      }
Was it helpful?

Solution

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;
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top