Package org.openqreg.bean

Examples of org.openqreg.bean.FileHolder


          } else {
            logger.log(Level.DEBUG, "File field " + name
                + " with file name " + item.getName()
                + " detected.");

            FileHolder FH = new FileHolder();
            FH.setContentType(item.getContentType());

            // ie sends entire path, other only filename
            FH.setCompletePath(item.getName());
            // no point to read file if it does not exist..
            if (null != item.getName()
                && item.getName().length() > 0) {
              // filename
              FH.setFileName(item.getName().substring(
                  item.getName().lastIndexOf("\\") + 1));
            }

            InputStream inStream = item.openStream();

            int lBufferSize = 1024;
            byte[] lByteBuffer = new byte[lBufferSize];

            int lBytesRead = 0;
            int lTotbytesRead = 0;
            int lCount = 0;

            ByteArrayOutputStream lByteArrayOutputStream = new ByteArrayOutputStream(
                lBufferSize * 2);

            while ((lBytesRead = inStream.read(lByteBuffer)) != -1) {
              lTotbytesRead += lBytesRead;
              lCount++;

              lByteArrayOutputStream.write(lByteBuffer, 0,
                  lBytesRead);
            }
            logger.log(Level.DEBUG, "Chuncks count: " + lCount);
            logger.log(Level.DEBUG, "Total bytes read: "
                + lTotbytesRead);

            FH.setFileContent(lByteArrayOutputStream.toByteArray());

            tr.put(item.getFieldName(), FH);
          }
        }
      } catch (Exception e) {
View Full Code Here


  /**
   *
   * Validate the xml file
   */
  private void validateXmlFile() {
    FileHolder fileHolder;
    String schema = "";
    XmlReader xmlReader;
    if (type == ImportType.TEXTS) {
      //We are validating a text xml file
      fileHolder = (FileHolder)fetch.getObject("IMPORTTEXT_XMLTOIMPORT");
      schema = XMLImporter.getSchema("textSchema");
      xmlReader = new XmlTextReader();
    } else {
      //We are validating a variables xml file
      fileHolder = (FileHolder)fetch.getObject("IMPORTVARIABLES_XMLTOIMPORT");
      schema = XMLImporter.getSchema("variableSchema");
      xmlReader = new XmlVariableReader();
    }

    if (fileHolder != null && fileHolder.getFileContent() != null) {
      ByteArrayInputStream is = null;
      InputStream schemaIs = null;
      URL schemaUrl = null;
     
      try
        is = new ByteArrayInputStream(fileHolder.getFileContent());
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        schemaIs = loader.getResourceAsStream(schema);
        if(schemaIs == null){
          schemaUrl = new URL(schema);
          schemaIs = schemaUrl.openStream();
        }
 
        XmlFileResult result = xmlReader.validateFile(is, schemaIs);
        Document errorDoc = null;
        if (! result.hasErrors()) {
          message = "File is OK";
         } else {
           errorDoc = styleDocument(result.getErrorDoc(),
               pageContext.getServletContext().getResourceAsStream("/xmlError.xsl"));
         }
        pageContext.setAttribute("errorMessage",
            errorDoc == null ? null : errorDoc.getRootElement());
      } catch(MalformedURLException murle){
        log.log(Level.WARN, "URL is malformed: "+ schema, murle);
      } catch(IOException ioe){
        log.log(Level.WARN, "Unable to read schema: "+ schema, ioe);
      } catch (TransformerConfigurationException tce) {
        log.log(Level.ERROR, "Unable to configure transformer", tce);
      } catch (TransformerException te) {
        log.log(Level.ERROR, "Unable to transform document", te);
      }finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException ioe) {
            log.log(Level.ERROR,"Error on closing input stream (imposible)", ioe);
          }
        }
      }
      fetch.addValue(fileHolder.getCompletePath(), "filepath");
    } else {
      message = "File is not specified";
    }
  }
View Full Code Here

  /**
   * Read and insert texts or variables into database from a xml document
   */
  @Override
  protected void createData(Connection con) throws SQLException {
    FileHolder fileHolder;
    String schema = "";
    XmlReader xmlReader;
    if (type == ImportType.TEXTS) {
      fileHolder = (FileHolder)fetch.getObject("IMPORTTEXT_XMLTOIMPORT");
      schema = XMLImporter.getSchema("textSchema");
      xmlReader = new XmlTextReader();
    } else if (type == ImportType.XLIFF) {
      fileHolder = (FileHolder)fetch.getObject("IMPORTTEXT_XLIFFTOIMPORT");
      schema = XMLImporter.getSchema("xliffSchema");
      xmlReader = new XliffReader();
    } else {
      fileHolder = (FileHolder)fetch.getObject("IMPORTVARIABLES_XMLTOIMPORT");
      //Get the schema from context.xml
      schema = XMLImporter.getSchema("variableSchema");
      xmlReader = new XmlVariableReader();
    }

    if (fileHolder != null && fileHolder.getFileContent() != null) {
      ByteArrayInputStream is = null;
      InputStream schemaIs = null;
      URL schemaUrl = null;
      try {
        is = new ByteArrayInputStream(fileHolder.getFileContent());
        //Read and insert texts into database
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        schemaIs = loader.getResourceAsStream(schema);
        if(schemaIs == null){
          schemaUrl = new URL(schema);
          schemaIs = schemaUrl.openStream();
        }

        XmlFileResult result = xmlReader.readFile(is, con, schemaIs);
        Document errorDoc = null;
        if (result.hasErrors()) {
           errorDoc = styleDocument(result.getErrorDoc(),
               pageContext.getServletContext().getResourceAsStream("xmlError.xsl"));
        } else {
          lang.load(con, false);
          if (xmlReader instanceof XmlTextReader || xmlReader instanceof XliffReader) {
            message = "File imported OK. " + result.getResult() + " texts inserted.";
          } else {
            message = "File with variables imported OK. " + result.getResult() + " pages imported.";
            //Repopulate the systemholder
            disp.populateSystemHolder();
          }
        }
        pageContext.setAttribute("errorMessage",
            errorDoc == null ? null : errorDoc.getRootElement());
      } catch(MalformedURLException murle){
        log.log(Level.WARN, "URL is malformed: "+ schema, murle);
      }catch(IOException ioe){
        log.log(Level.WARN, "Unable to read schema: "+ schema, ioe);
      } catch (DocumentException de) {
        log.log(Level.WARN, "Unable to read file", de);
      catch (TransformerConfigurationException tce) {
        log.log(Level.ERROR, "Unable to configure transformer", tce);
      } catch (TransformerException te) {
        log.log(Level.ERROR, "Unable to transform document", te);
      }finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            log.log(Level.ERROR, e);
          }
        }
      }

      fetch.addValue(fileHolder.getCompletePath(), "filepath");
    } else {
      message = "File is not specified";
    }
  }
View Full Code Here

public class AjaxFileAPI extends AbstractAjaxMethods {
  public String uploadFile(String userId, String fileName, Integer fileSize,
      String fileType, String binaryString) {
    String service = "START_PAGE";
    if (hasService(userId, service)) {
      FileHolder fh = new FileHolder();
      fh.setPath("/tmp/");
      // fh.setFileName("trams");
      fh.setFileName(fileName);
      fh.setFileContent(binaryString.getBytes(Charset
          .forName("ISO-8859-1")));
      // byte[] decoded = Base64.decodeBase64(binaryString.getBytes());
      // fh.setFileContent(decoded);
      fh.writeFileToDisk();
      return "ok";
    }
    return null;
  }
View Full Code Here

      User user, LoginAnswer loginAnswer, FetchData fetch, String langId)
      throws ServletException, IOException {
    StringBuilder out = new StringBuilder();
    String sortOrder = fetch.getValueAsString("SORTORDER");
    String[] sa = sortOrder.split("#:#");
    FileHolder fh = null;

    // get file path from context.xml
    String fileSharePath = "/tmp/";

    try {
      InitialContext ic = new InitialContext();
      fileSharePath = (String) ic.lookup("java:comp/env/fileSharePath");
    } catch (Exception e) {
      log.log(Level.ERROR,
          "FileShareUpload can't read fileSharePath from context.xml"
              + ", defaulting to /tmp/", e);
    }
    //TODO: add directory to path
//    fileSharePath += "/"+user.getId()+"/";
    try {
      for (String s : sa) {
        fh = (FileHolder) fetch.getObject(s);
        log.log(Level.INFO, "Filename = " + fh.getFileName());

        Collection<FileBean> col = FileFinder.findByNameOwner(
            fh.getFileName(), user.getId());
        if (null != col && 0 < col.size()) {
          // file exists since before for this user
          out.append("You already have a file named: "
              + fh.getFileName() + " file NOT uploaded." + "  "
              + " <br/>");

        } else {

          // write metadata to db
          FileBean file = new FileBean();
          file.setName(fh.getFileName());
          file.setSize(Integer.valueOf(fh.getFileSize()));
          // file.setContenttype(?);
          file.setPath(fileSharePath);
          file.setOwner(user.getId());
          file.setCreatedby(user.getId());
          file.setService("FILESHARE_DOWNLOAD");
          file.create();

          // fileSharePath from context.xml
          fh.setPath(fileSharePath);
          fh.writeFileToDisk();
          // String answer = XMLImporter.importFile(fh);
          out.append(fh.getFileName() + " : "
              + " successfully uploaded " + " <br/>");
        }
      }
    } catch (SQLException e) {
      log.log(Level.ERROR, "Error uploading file in FileShareUpload", e);
View Full Code Here

    @Override
    protected void giveService(HttpServletRequest req, HttpServletResponse res,
      User user, LoginAnswer loginAnswer, FetchData fetch, String langId)
      throws ServletException, IOException {
        FileHolder fileHolder;
        String schema = "";
        SAXReader saxReader = new SAXReader();
        // We are validating a variables xml file
        fileHolder = (FileHolder) fetch
                .getObject("IMPORTVARIABLES_XMLTOIMPORT");
        schema = fetch.getValueAsString("IMPORTVARIABLES_XSLSTYLESHEET");

        if (fileHolder != null && fileHolder.getFileContent() != null) {
            ByteArrayInputStream is = null;
            InputStream schemaIs = null;
            URL schemaUrl = null;

            try {
                is = new ByteArrayInputStream(fileHolder.getFileContent());
                Document doc = saxReader.read(is);
                ClassLoader loader = Thread.currentThread()
                        .getContextClassLoader();
                // Special hack to handle the case where we generate a PDF. todo: Maybe add an output parameter instead?
                if (schema != null && schema.equals("OpenQReg40ToFOP.xsl")) {
                  FopFactory fopFactory = FopFactory.newInstance();
                  FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
                    Fop fop = null;
                    try {
                        res.setContentType("application/pdf");
                        fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, res.getOutputStream());

                        // Setup JAXP using identity transformer
                        TransformerFactory factory = TransformerFactory.newInstance();
                        Transformer transformer = factory.newTransformer(new StreamSource(loader.getResourceAsStream(schema)));

                        // Set the value of a <param> in the stylesheet
                        transformer.setParameter("versionParam", "2.0");
                        transformer.setParameter("language", fetch.getValueAsString("IMPORTVARIABLES_LANGUAGE"));
                        transformer.setParameter("controldate", fetch.getValueAsString("IMPORTVARIABLES_CONTROLDATE"));
                        transformer.setParameter("showallignoredate", fetch.getValueAsString("IMPORTVARIABLES_SHOWALLIGNOREDATE"));
                        transformer.setParameter("showextravariables", fetch.getValueAsString("IMPORTVARIABLES_SHOWEXTRAVARIABLES"));
                        transformer.setParameter("extravariableprefix", fetch.getValueAsString("IMPORTVARIABLES_EXTRAVARIABLESPREFIX"));

                        DocumentSource source = new DocumentSource(doc);

                        // Resulting SAX events (the generated FO) must be piped through to FOP
                        Result result = null;
                        result = new SAXResult(fop.getDefaultHandler());
                        // Start XSLT transformation and FOP processing
                        transformer.transform(source, result);
                    } catch (FOPException e) {
                        throw new RuntimeException(e);
                    }

                } else {

                    schemaIs = loader.getResourceAsStream(schema);
                    if (schemaIs == null) {
                        schemaUrl = new URL(schema);
                        schemaIs = schemaUrl.openStream();
                    }
                    doc = styleDocument(doc, schemaIs);
                    res.setContentType("application/xml");
//                    res.setHeader(CONTENT_DISPOSTION, "attachment; filename=" + "OpenQReg41_" + fileHolder.getFileName());
                    res.setHeader(CONTENT_DISPOSTION, "attachment; filename=" + fileHolder.getFileName());

                    //Write the xml/html document nicely
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    format.setEncoding("UTF-8");

                    XMLWriter writer = new XMLWriter(res.getOutputStream(), format);
                    writer.write(doc);
                    writer.close();
                }

                //Make sure the OutputStream buffer of the Response is flushed.
                res.flushBuffer();

            } catch (MalformedURLException murle) {
                log.log(Level.WARN, "URL is malformed: " + schema, murle);
            } catch (IOException ioe) {
                log.log(Level.WARN, "Unable to read schema: " + schema, ioe);
            } catch (DocumentException doce) {
                log.log(Level.WARN, "Unable to read schema: " + schema, doce);
            } catch (TransformerConfigurationException tce) {
                log.log(Level.ERROR, "Unable to configure transformer", tce);
            } catch (TransformerException te) {
                log.log(Level.ERROR, "Unable to transform document", te);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ioe) {
                        log.log(Level.ERROR,
                                "Error on closing input stream (imposible)",
                                ioe);
                    }
                }
            }
            fetch.addValue(fileHolder.getCompletePath(), "filepath");
        }
    }
View Full Code Here

      User user, LoginAnswer loginAnswer, FetchData fetch, String langId)
      throws ServletException, IOException {
    StringBuilder out = new StringBuilder();
    String sortOrder = fetch.getValueAsString("SORTORDER");
    String[] sa = sortOrder.split("#:#");
    FileHolder fh = null;
    boolean filesImported = false;
    for (String s : sa) {
      // only try to import new / updated files
      if (null != fetch.getObject(s)) {
        fh = (FileHolder) fetch.getObject(s);
        log.log(Level.INFO, "Filename = " + fh.getFileName());
        fh.setPath("/tmp/");
        String answer = XMLImporter.importFile(fh, false);
        out.append(fh.getFileName() + " : " + answer + " <br>");
        filesImported = true;
      }
    }
    // if(filesImported) {
    // //reload stuff
View Full Code Here

  }



  private void transformXML() {
    FileHolder fileHolder;
    String schema = "";
    SAXReader saxReader = new SAXReader();
    // We are validating a variables xml file
    fileHolder = (FileHolder) fetch
        .getObject("IMPORTVARIABLES_XMLTOIMPORT");
//    schema = getSchema("variableSchema");
    schema = fetch.getValueAsString("IMPORTVARIABLES_XSLSTYLESHEET");
   
    if (fileHolder != null && fileHolder.getFileContent() != null) {
      ByteArrayInputStream is = null;
      InputStream schemaIs = null;
      URL schemaUrl = null;

      try {
        is = new ByteArrayInputStream(fileHolder.getFileContent());
        Document doc = saxReader.read(is);
        ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
        schemaIs = loader.getResourceAsStream(schema);
        if (schemaIs == null) {
          schemaUrl = new URL(schema);
          schemaIs = schemaUrl.openStream();
        }
        doc = styleDocument(doc, schemaIs);
       
        ServletResponse res = pageContext.getResponse();
        res.setContentType("application/xml")
//        res.setHeader(CONTENT_DISPOSTION, "attachment; filename=" + "transformed_"+fileHolder.getFileName());
        
//        if (xslStyleSheet != null && ! xslStyleSheet.equals("")) {
//          res.setContentType("text/xml"); 
//          xmlDocName = xmlDocName.replace(".xml", ".html");
//          is = applicationScope.getResourceAsStream("/" + xslStyleSheet);
//          doc = styleDocument(doc, is);
//        } else {
//          //No stylesheet specified
//        }
        //Write the xml/html document nicely
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
       
        XMLWriter writer = new XMLWriter(res.getOutputStream(), format);
              writer.write(doc);
              writer.close();

              //Make sure the OutputStream buffer of the Response is flushed.
              res.flushBuffer();
       
//
//        XmlFileResult result = xmlReader.validateFile(is, schemaIs);
//        Document errorDoc = null;
//        if (!result.hasErrors()) {
//          message = "File is OK";
//        } else {
//          errorDoc = styleDocument(result.getErrorDoc(), pageContext
//              .getServletContext().getResourceAsStream(
//                  "/xmlError.xsl"));
//        }
//        pageContext.setAttribute("errorMessage",
//            errorDoc == null ? null : errorDoc.getRootElement());
      } catch (MalformedURLException murle) {
        log.log(Level.WARN, "URL is malformed: " + schema, murle);
      } catch (IOException ioe) {
        log.log(Level.WARN, "Unable to read schema: " + schema, ioe);
      } catch (DocumentException doce) {
        log.log(Level.WARN, "Unable to read schema: " + schema, doce);
      } catch (TransformerConfigurationException tce) {
        log.log(Level.ERROR, "Unable to configure transformer", tce);
      } catch (TransformerException te) {
        log.log(Level.ERROR, "Unable to transform document", te);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException ioe) {
            log.log(Level.ERROR,
                "Error on closing input stream (imposible)",
                ioe);
          }
        }
      }
      fetch.addValue(fileHolder.getCompletePath(), "filepath");
    } else {
      message = "File is not specified";
    }
  }
View Full Code Here

  /**
   * Read and insert texts or variables into database from a xml document
   */
  @Override
  protected void createData(Connection con) throws SQLException {
    FileHolder fileHolder;
    String schema = "";
    XmlReader xmlReader;
    if (type == ImportType.TEXTS) {
      fileHolder = (FileHolder) fetch.getObject("IMPORTTEXT_XMLTOIMPORT");
      schema = getSchema("textSchema");
      xmlReader = new XmlTextReader();
    } else {
      fileHolder = (FileHolder) fetch
          .getObject("IMPORTVARIABLES_XMLTOIMPORT");
      // Get the schema from context.xml
      schema = getSchema("variableSchema");
      xmlReader = new XmlVariableReader();
    }

    if (fileHolder != null && fileHolder.getFileContent() != null) {
      ByteArrayInputStream is = null;
      InputStream schemaIs = null;
      URL schemaUrl = null;
      try {
        is = new ByteArrayInputStream(fileHolder.getFileContent());
        // Read and insert texts into database
        ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
        schemaIs = loader.getResourceAsStream(schema);
        if (schemaIs == null) {
          schemaUrl = new URL(schema);
          schemaIs = schemaUrl.openStream();
        }

        XmlFileResult result = xmlReader.readFile(is, con, schemaIs);
        Document errorDoc = null;
        if (result.hasErrors()) {
          errorDoc = styleDocument(result.getErrorDoc(), pageContext
              .getServletContext().getResourceAsStream(
                  "xmlError.xsl"));
        } else {
//          lang.load(con, false);
          if (xmlReader instanceof XmlTextReader) {
            message = "File imported OK. " + result.getResult()
                + " texts inserted.";
          } else {
            message = "File with variables imported OK. "
                + result.getResult() + " pages imported.";
            // Make sure the variables are re-read next time a page
            // is accessed
//            disp.clearSystemHolders();
          }
        }
        pageContext.setAttribute("errorMessage",
            errorDoc == null ? null : errorDoc.getRootElement());
      } catch (MalformedURLException murle) {
        log.log(Level.WARN, "URL is malformed: " + schema, murle);
      } catch (IOException ioe) {
        log.log(Level.WARN, "Unable to read schema: " + schema, ioe);
      } catch (DocumentException de) {
        log.log(Level.WARN, "Unable to read file", de);
      } catch (TransformerConfigurationException tce) {
        log.log(Level.ERROR, "Unable to configure transformer", tce);
      } catch (TransformerException te) {
        log.log(Level.ERROR, "Unable to transform document", te);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            log.log(Level.ERROR, e);
          }
        }
      }

      fetch.addValue(fileHolder.getCompletePath(), "filepath");
    } else {
      message = "File is not specified";
    }
  }
View Full Code Here

TOP

Related Classes of org.openqreg.bean.FileHolder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.