Exemplo n.º 1
1
  public static String caregarImagem(String dados, String caminho) {
    logger.info("caregarImagem  chamado " + dados);
    try {
      if (dados.length() > 10) {

        // Converte a string em bytes
        byte[] imagem = new sun.misc.BASE64Decoder().decodeBuffer(dados);

        ServletContext servletContext =
            (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

        FileOutputStream outPut = new FileOutputStream(servletContext.getRealPath("") + caminho);
        outPut.write(imagem);
        outPut.flush();
        outPut.close();
        logger.info("Dados da imagem gravdaos " + servletContext.getRealPath("") + caminho);
        return caminho;
      } else {
        logger.info("Fundo branco chamado " + caminho);
        return "imagens/fundo_branco.jpg";
      }
    } catch (FileNotFoundException e) {
      logger.info("erro FileNotFoundException " + e.getMessage());
    } catch (IOException e) {
      logger.info("erro IOException " + e.getMessage());
    }
    return "imagens/fundo_branco.jpg";
  }
Exemplo n.º 2
0
 @RequestMapping(value = "createImageIndex", method = RequestMethod.POST)
 public @ResponseBody boolean createImageIndex(HttpServletRequest request) throws IOException {
   ServletContext sc = request.getSession().getServletContext();
   String imagespath = sc.getRealPath("/src/imgfiles");
   String indexpath = sc.getRealPath("/src/imgindex");
   return imageService.createImageIndex(imagespath, indexpath);
 }
Exemplo n.º 3
0
  @RequestMapping(value = "fetchSimilarImage", method = RequestMethod.POST)
  public @ResponseBody List<Map<Object, Object>> fetchSimilarImage(
      @RequestParam("doc") MultipartFile doc, HttpServletRequest request) throws Exception {
    List<Map<Object, Object>> resultlist = new ArrayList<Map<Object, Object>>();
    if (doc.isEmpty()) {
      return resultlist;
    }

    ServletContext sc = request.getSession().getServletContext();
    String uploadpath = sc.getRealPath("/src/upload");
    String indexpath = sc.getRealPath("/src/imgindex");
    String imageName = System.currentTimeMillis() + ".png";
    File savefile = new File(new File(uploadpath), imageName);
    if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
    doc.transferTo(savefile); // save file
    List<Image> list = imageService.findSimilarImage(uploadpath + "/" + imageName, indexpath, 100);
    if (list != null && list.size() > 0) {
      int size = list.size();
      for (int index = size - 1; index >= 0; index--) {
        Map<Object, Object> map = new HashMap<Object, Object>();
        map.put("score", list.get(index).getScore());
        map.put("imageurl", list.get(index).getImagepath());
        resultlist.add(map);
      }
    }
    return resultlist;
  }
Exemplo n.º 4
0
  private void setup() throws GuanxiException {
    String KEYSTORE_FILE = "/WEB-INF/guanxi_idp/keystore/guanxi_idp.jks";
    String KEYSTORE_TYPE = "jks";
    String KEYSTORE_PRIVATE_KEY_ALIAS = "idp";

    if (!keystoreExists(servletContext.getRealPath(KEYSTORE_FILE))) {
      Random randomNumberGenerator = new Random();
      String certCN = getCNPrefix() + String.valueOf(randomNumberGenerator.nextInt());
      String keystorePassword = String.valueOf(randomNumberGenerator.nextInt());

      /* Create the keystore. Note that the keystore password and key entry password
       * must be the same for Tomcat to load the keystore
       */
      try {
        if (createSelfSignedKeystore(
            certCN,
            servletContext.getRealPath(KEYSTORE_FILE),
            keystorePassword,
            keystorePassword,
            KEYSTORE_PRIVATE_KEY_ALIAS)) {
          createConfigFile(
              certCN,
              certCN,
              KEYSTORE_TYPE,
              servletContext.getRealPath(KEYSTORE_FILE),
              keystorePassword,
              KEYSTORE_PRIVATE_KEY_ALIAS,
              keystorePassword,
              KEYSTORE_PRIVATE_KEY_ALIAS);
        }
      } catch (IOException ioe) {
        throw new GuanxiException(ioe);
      }
    }
  }
Exemplo n.º 5
0
  @RequestMapping(value = "add", method = RequestMethod.POST)
  public String add(
      String name,
      String email,
      String tel,
      String cid,
      String password,
      MultipartFile photofile,
      Model model)
      throws Exception {

    String newFileName = null;

    if (photofile.getSize() > 0) {
      newFileName = MultipartHelper.generateFilename(photofile.getOriginalFilename());
      File attachfile = new File(servletContext.getRealPath(SAVED_DIR) + "/" + newFileName);
      photofile.transferTo(attachfile);

      makeThumbnailImage(
          servletContext.getRealPath(SAVED_DIR) + "/" + newFileName,
          servletContext.getRealPath(SAVED_DIR) + "/s-" + newFileName + ".png");
    }

    Student student = new Student();
    student.setName(name);
    student.setEmail(email);
    student.setTel(tel);
    student.setCid(cid);
    student.setPassword(password);
    student.setPhoto(newFileName);

    studentDao.insert(student);

    return "redirect:list.do";
  }
Exemplo n.º 6
0
  public static void imprimeRelatorio(String nomeRelatorio, HashMap parametros, List lista) {
    try {
      JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(lista);
      FacesContext facesContext = FacesContext.getCurrentInstance();
      ServletContext servletContext =
          (ServletContext) facesContext.getExternalContext().getContext();
      String path = servletContext.getRealPath("/WEB-INF/relatorios/");
      // parametro jasper report
      parametros.put("SUBREPORT DIR", path + File.separator);
      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              servletContext.getRealPath("/WEB-INF/relatorios/")
                  + File.separator
                  + nomeRelatorio
                  + ".jasper",
              parametros,
              dataSource);
      byte[] b = JasperExportManager.exportReportToPdf(jasperPrint);

      HttpServletResponse res =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      res.setContentType("application/pdf");
      int codigo = (int) (Math.random() * 1000);
      res.setHeader("Content-disposition", "inline);filename-relatorio_" + codigo + ".pdf");
      res.getOutputStream().write(b);
      facesContext.responseComplete();

    } catch (Exception e) {
      UtilMensagens.mensagemErro("Erro ao imprimir: " + UtilErros.getMensagemErro(e));
      e.printStackTrace();
    }
  }
Exemplo n.º 7
0
  /**
   * Obtiene la consulta en la base de datos y par�metros que ser�n utilizados por el reporte.
   *
   * @param parametrosCatalogo Par�metros que se le env�an al m�todo .
   * @param request Objeto que provee de informaci�n al servlet sobre el request del cliente. El
   *     contenedor de servlets crea un objeto HttpServletRequest y lo env�a como un par�metro a
   *     este m�todo.
   * @param catalogoSL Instancia del Ejb CatalogoSL que ejecuta en la base de datos las operaciones
   *     especificadas en la clase CON.
   * @param contextoServidor Objeto que contiene informaci�n acerca del entorno del servidor de
   *     aplicaciones.
   * @param contextoServlet Objeto que contiene informaci�n acerca del entorno del servlet.
   * @return Map objeto que contiene los datos para generar el reporte.
   * @throws SQLException Si se genera un error al accesar la base de datos.
   */
  public Map getParametros(
      Registro parametrosCatalogo,
      HttpServletRequest request,
      CatalogoSL catalogoSL,
      Context contextoServidor,
      ServletContext contextoServlet)
      throws Exception {
    Map parametros = new HashMap();

    String sClave = request.getParameter("CvePrestamoGrupo");

    System.out.println("sClave:" + sClave);

    String sSql =
        "SELECT  \n"
            + "CVE_GPO_EMPRESA,\n"
            + "CVE_EMPRESA,\n"
            + "ID_PRESTAMO_GRUPO,\n"
            + "CVE_PRESTAMO_GRUPO,\n"
            + "NUM_PAGO_AMORTIZACION,\n"
            + "FECHA_AMORTIZACION,\n"
            + "TO_NUMBER (IMP_SALDO_INICIAL, '999G999D0000') IMP_SALDO_INICIAL,\n"
            + "TASA_INTERES,\n"
            + "INTERES,\n"
            + "IMP_CAPITAL_AMORT,\n"
            + "IMP_PAGO,\n"
            + "IMP_ACCESORIO,\n"
            + "PAGO_TOTAL,\n"
            + "TO_NUMBER (IMP_SALDO_FINAL, '999G999D0000') IMP_SALDO_FINAL\n"
            + "FROM \n"
            + "V_TABLA_AMORTIZACION_GRUPAL\n";

    if (sClave != null && !sClave.equals("") && !sClave.equals("null")) {
      sSql = sSql + "WHERE CVE_PRESTAMO_GRUPO = '" + sClave + "' \n";
    }

    sSql = sSql + "ORDER BY  NUM_PAGO_AMORTIZACION\n";

    System.out.println("*****************Paso por aqui****************:" + sSql);

    String sTipoReporte = request.getParameter("TipoReporte");
    System.out.println("TipoReporte:" + sTipoReporte);
    parametros.put("Sql", sSql);
    parametros.put("FechaReporte", Fecha2.formatoCorporativoHora(new Date()));
    parametros.put("NomReporte", "/Reportes/Sim/reportes/SimReportesAmortizacion.jasper");
    parametros.put(
        "Subreporte1",
        contextoServlet.getRealPath(
            "/Reportes/Sim/reportes/SimReportesAmortizacion_subreport.jasper"));
    parametros.put(
        "Subreporte2",
        contextoServlet.getRealPath(
            "/Reportes/Sim/reportes/SimReportesAmortizacion_subreport2.jasper"));
    parametros.put("NombreReporte", "rep" + sClave);

    return parametros;
  }
Exemplo n.º 8
0
 /**
  * 获得应用中制定目录中文件的路径
  *
  * @param servletContStriext
  * @param _dir:文件存放的目录
  * @return
  */
 public static String getServerFilePath(ServletContext servletContext, String _dir) {
   //		String filePath = servletContStriext.getRealPath("/");
   String path = null;
   if (ServerDetector.isTomcat()) { // tomcat server
     path = servletContext.getRealPath("/") + _dir + "/";
   } else if (ServerDetector.isWebLogic()) { // weblogic server
     path = servletContext.getRealPath("/") + "\\" + _dir + "\\";
   }
   return path;
 }
  /**
   * Obtiene la consulta en la base de datos y par�metros que ser�n utilizados por el reporte.
   *
   * @param parametrosCatalogo Par�metros que se le env�an al m�todo .
   * @param request Objeto que provee de informaci�n al servlet sobre el request del cliente. El
   *     contenedor de servlets crea un objeto HttpServletRequest y lo env�a como un par�metro a
   *     este m�todo.
   * @param catalogoSL Instancia del Ejb CatalogoSL que ejecuta en la base de datos las operaciones
   *     especificadas en la clase CON.
   * @param contextoServidor Objeto que contiene informaci�n acerca del entorno del servidor de
   *     aplicaciones.
   * @param contextoServlet Objeto que contiene informaci�n acerca del entorno del servlet.
   * @return Map objeto que contiene los datos para generar el reporte.
   * @throws SQLException Si se genera un error al accesar la base de datos.
   */
  public Map getParametros(
      Registro parametrosCatalogo,
      HttpServletRequest request,
      CatalogoSL catalogoSL,
      Context contextoServidor,
      ServletContext contextoServlet)
      throws Exception {
    Map parametros = new HashMap();

    String sClave = request.getParameter("CvePrestamo");

    String sSql =
        "SELECT \n"
            + "CVE_GPO_EMPRESA,\n"
            + "CVE_EMPRESA,\n"
            + "CVE_PRESTAMO,\n"
            + "ID_PRESTAMO,\n"
            + "NOMBRE,\n"
            + "NOM_SUCURSAL,\n"
            + "FECHA_ENTREGA,\n"
            + "FECHA_REAL,\n"
            + "PERIODICIDAD_PRODUCTO,\n"
            + "PLAZO,\n"
            + "VALOR_TASA,\n"
            + "PERIODICIDAD_TASA\n"
            + "FROM \n"
            + "V_CREDITO\n"
            + "WHERE CVE_GPO_EMPRESA ='"
            + parametrosCatalogo.getDefCampo("CVE_GPO_EMPRESA")
            + "' \n"
            + "AND CVE_EMPRESA = '"
            + parametrosCatalogo.getDefCampo("CVE_EMPRESA")
            + "' \n"
            + "AND CVE_PRESTAMO = '"
            + (String) request.getParameter("CvePrestamo")
            + "' \n";

    System.out.println("*****************Paso por aqui****************:" + sSql);

    String sTipoReporte = request.getParameter("TipoReporte");
    System.out.println("TipoReporte:" + sTipoReporte);
    parametros.put("Sql", sSql);
    parametros.put("FechaReporte", Fecha2.formatoCorporativoHora(new Date()));
    parametros.put("NomReporte", "/Reportes/Sim/reportes/SimReporteEstadoCuentaGpo.jasper");
    parametros.put(
        "Subreporte1",
        contextoServlet.getRealPath("/Reportes/Sim/reportes/SimReporteEstadoCuentaGpo1.jasper"));
    parametros.put(
        "Subreporte2",
        contextoServlet.getRealPath("/Reportes/Sim/reportes/SimReporteEstadoCuentaGpo2.jasper"));
    parametros.put("NombreReporte", "rep" + sClave);

    return parametros;
  }
Exemplo n.º 10
0
 @Nonnull
 protected String getServletContextPath(@Nonnull final ServletContext aSC) {
   String sPath = aSC.getRealPath(".");
   if (sPath == null) {
     // Fallback for Undertow
     sPath = aSC.getRealPath("");
   }
   if (StringHelper.hasNoText(sPath))
     throw new IllegalStateException("Failed to determine real path of ServletContext " + aSC);
   return sPath;
 }
Exemplo n.º 11
0
  private void createConfigFile(
      String issuer,
      String nameQualifier,
      String ksType,
      String ksFile,
      String ksPassword,
      String privKeyAlias,
      String privKeyPassword,
      String certAlias)
      throws IOException {

    String SSO_CONFIG_FILE = "/WEB-INF/guanxi_idp/config/idp.xml";
    String KEYSTORE_KEY_TYPE = "dsa";

    IdpDocument idpDoc = null;
    try {
      idpDoc = IdpDocument.Factory.parse(new File(servletContext.getRealPath(SSO_CONFIG_FILE)));
    } catch (XmlException xe) {
      logger.error("Can't create config file", xe);
      return;
    }

    IdpDocument.Idp idp = idpDoc.getIdp();

    idp.getServiceProviderArray(0).setIdentity("exampleIdentity");
    idp.getServiceProviderArray(0).setCreds("exampleCreds");
    idp.getServiceProviderArray(0).setName("REPLACE_WITH_PROVIDER_ID_OF_SERVICE_PROVIDER");

    idp.getIdentityArray(0).setName("exampleIdentity");
    idp.getIdentityArray(0).setNameQualifier(nameQualifier);
    idp.getIdentityArray(0).setIssuer(issuer);

    idp.getCredsArray(0).setName("exampleCreds");
    idp.getCredsArray(0).setKeystoreType("jks");
    idp.getCredsArray(0).setKeyType(ksType);
    idp.getCredsArray(0).setKeystoreFile(ksFile);
    idp.getCredsArray(0).setKeystorePassword(ksPassword);
    idp.getCredsArray(0).setPrivateKeyAlias(privKeyAlias);
    idp.getCredsArray(0).setPrivateKeyPassword(privKeyPassword);
    idp.getCredsArray(0).setCertificateAlias(certAlias);
    idp.getCredsArray(0).setKeyType(KEYSTORE_KEY_TYPE);

    XmlOptions xmlOptions = new XmlOptions();
    xmlOptions.setSavePrettyPrint();
    xmlOptions.setSavePrettyPrintIndent(2);
    xmlOptions.setUseDefaultNamespace();

    idpDoc.save(new File(servletContext.getRealPath(SSO_CONFIG_FILE)), xmlOptions);

    servletContext.setAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG_DOC, idpDoc);
    servletContext.setAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG, idpDoc.getIdp());
  }
Exemplo n.º 12
0
  public void init() throws ServletException {
    System.out.println("Æ´Òô´Ê¿â¼ÓÔØÖÐ.........");
    ServletContext context = getServletContext();
    String path = context.getRealPath("/") + "SQL\\PinYin.mdb";
    RealPath.Path = context.getRealPath("/");
    try {
      Change change = new Change(path);
      change.getkeyPinYin();

      System.out.println("Æ´Òô´Ê¿â¼ÓÔسɹ¦");
    } catch (Exception e) {
      System.out.println("Æ´Òô´Ê¿â¼ÓÔØʧ°Ü");
    }
  }
Exemplo n.º 13
0
 /**
  * 在指定的 Web 应用程序目录下以指定路径创建目录.
  *
  * @param application JSP/Servlet 的 ServletContext
  * @param filePath 相对文件路径
  */
 public static boolean createDir(ServletContext application, String filePath) {
   if (!isEmpty(filePath)) {
     String physicalFilePath = application.getRealPath(filePath);
     if (!isEmpty(physicalFilePath)) {
       try {
         // 创建目录
         java.io.File dir = new java.io.File(application.getRealPath(filePath));
         return dir.mkdirs();
       } catch (Exception e) {
         System.err.println("Unable to create directory " + filePath);
       }
     }
   }
   return false;
 }
Exemplo n.º 14
0
  @Override
  public TipiContext createContext() throws IOException {

    String stylePath = myServletContext.getRealPath("Default.stylesheet");
    logger.info("StylePath: " + stylePath);
    try {
      FileInputStream fis = new FileInputStream(stylePath);
      Styles.loadStyleSheet(fis);
      fis.close();
    } catch (IOException e) {
      logger.error("Error: ", e);
    }

    if (Styles.DEFAULT_STYLE_SHEET != null) {
      setStyleSheet(Styles.DEFAULT_STYLE_SHEET);
      Style ss = Styles.DEFAULT_STYLE_SHEET.getStyle(WindowPane.class, "Default");
      logger.info(">>> " + ss);
    }
    logger.info("REAL PATH: " + myServletContext.getRealPath("/"));

    // Title.Sub
    EchoTipiContext newContext = new EchoTipiContext(this, null);
    ServletContextResourceLoader servletContextTipiLoader =
        new ServletContextResourceLoader(myServletContext, "tipi");
    newContext.setTipiResourceLoader(servletContextTipiLoader);
    ServletContextResourceLoader servletContextResourceLoader =
        new ServletContextResourceLoader(myServletContext, "resource");
    newContext.setGenericResourceLoader(servletContextResourceLoader);
    //	context.setResourceBaseDirectory(new File(myServletContext.getRealPath("/") +
    // "resource/tipi/"));

    TipiEchoExtension ed = new TipiEchoExtension();
    ed.initialize(newContext);

    getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
    TipiScreen es = new TipiScreen();
    //		newContext.processRequiredIncludes();
    es.setContext(newContext);
    es.createContainer();
    newContext.setDefaultTopLevel(es);
    try {
      logger.info("Context created: " + newContext.hashCode());
      initServlet(newContext, myServletConfig.getInitParameterNames(), ed);
    } catch (Throwable ex) {
      ex.printStackTrace();
    }
    return newContext;
  }
 public void init(final ServletContext context, final Map<String, String> paras) {
   _startTime = new Date();
   _context = context;
   _sipFactory = (SipFactory) context.getAttribute(ServletContextConstants.SIP_FACTORY);
   _mrcpFactory = (MrcpFactory) context.getAttribute(ServletContextConstants.MRCP_FACTORY);
   _appJarUrl =
       _context.getRealPath("/")
           + "WEB-INF"
           + File.separator
           + "lib"
           + File.separator
           + "tropo.jar";
   _cache = Collections.synchronizedMap(new WeakHashMap<Object, Application>());
   _tmx = ManagementFactory.getThreadMXBean();
   _mmx = ManagementFactory.getMemoryMXBean();
   try {
     _tropoBuildDate = Utils.getManifestAttribute(_appJarUrl, "Build-Date");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildDate = "Unknown";
   }
   try {
     _tropoVersionNo = Utils.getManifestAttribute(_appJarUrl, "Version-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoVersionNo = "Unknown";
   }
   try {
     _tropoBuildNo = Utils.getManifestAttribute(_appJarUrl, "Build-No");
   } catch (final IOException t) {
     LOG.error(t.toString(), t);
     _tropoBuildNo = "Unknown";
   }
   LOG.info(toString() + " / " + getVersionNo() + " / " + getBuildNo());
 }
Exemplo n.º 16
0
  public String execute() throws Exception {

    String userId = (String) ActionContext.getContext().getSession().get("userId");

    String targetDirectory = servletContext.getRealPath("Excel"); // 获得路径

    if (upload != null) {
      try {
        String targetFileName = GenerateUtils.generateFileName(uploadFileName);
        File target = new File(targetDirectory, targetFileName);

        FileUtils.copyFile(upload, target);
        String userInfoExcelPath = targetDirectory + "\\" + targetFileName;
        File excelfile = new File(userInfoExcelPath);
        String info = excelToDBService.readInfoExceltoDB(excelfile, userId, targetDirectory);
        if ("ALLSUC".equals(info)) {
          warning = "数据全部导入成功!";
        } else if ("ERR".equals(info)) {
          warning = "数据导入中出现问题,请看是否上传的是正确的excel,否则请联系管理员!";
        } else {
          warning = "部分未导入的数据生成的excel,请及时下载!";
          url = info;
        }
        if (target.exists()) {
          target.delete();
        }
        return SUCCESS;
      } catch (Exception e) {
        e.printStackTrace();
        return ERROR;
      }
    }
    warning = "请上传材料";
    return ERROR;
  }
Exemplo n.º 17
0
  public static List<String> getClientLibs(ServletContext context) throws IOException {
    List<String> list = new ArrayList<String>();
    URL resource = RaplaJNLPPageGenerator.class.getResource("/clientlibs.properties");
    if (resource != null) {
      byte[] bytes = IOUtil.readBytes(resource);
      String string = new String(bytes);

      String[] split = string.split(";");
      for (String file : split) {
        list.add("webclient/" + file);
      }
    } else {
      String base = context.getRealPath(".");
      if (base != null) {
        java.io.File baseFile = new java.io.File(base);
        java.io.File[] files = IOUtil.getJarFiles(base, "webclient");
        for (File file : files) {
          String relativeURL = IOUtil.getRelativeURL(baseFile, file);
          list.add(relativeURL);
        }
      }
    }
    int size = list.size();
    for (int i = 0; i < size; i++) {
      String entry = list.get(i);
      if (entry.indexOf("raplaclient") >= 0) {
        list.remove(i);
        list.add(0, entry);
      }
    }
    return list;
  }
Exemplo n.º 18
0
  public String execute() throws Exception {
    if (upload == null) {
      setMessage("图片不存在");
      setSuccess("0");
      return Action.SUCCESS;
    }
    // 上传文件夹
    String savePath = context.getRealPath("/upload");

    FileInputStream fis = new FileInputStream(upload);
    // 修改名字
    String filename = uploadFileName;
    int index = filename.lastIndexOf(".");
    String houzhui = filename.substring(index);
    String name = new Date().getTime() + houzhui;
    // 部署路径
    String path = savePath + "\\" + name;
    FileOutputStream fos = new FileOutputStream(path);
    // 文件名以时间名
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = fis.read(buffer)) > 0) {
      fos.write(buffer, 0, len);
    }
    fos.flush();
    fis.close();
    fos.close();
    setMessage("上传成功");
    setSuccess("1");
    setUrl("upload/" + name);
    return Action.SUCCESS;
  }
Exemplo n.º 19
0
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // TODO Auto-generated method stub
   context = getServletContext();
   System.out.println(TAG + ":doPost");
   System.out.println(context.getRealPath("/"));
 }
  @RequestMapping(value = "codiRoomMyClothesUpload", method = RequestMethod.POST)
  public String codiRoomMyClothesUpload(
      Clothes clothes, MultipartFile file, HttpServletRequest request) throws IOException {

    if (!file.isEmpty()) {

      ServletContext application = request.getServletContext();
      String url = "/resource/image/clothes";
      String path = application.getRealPath(url);
      String temp = file.getOriginalFilename();
      String fname = temp.substring(temp.lastIndexOf("\\") + 1);
      String fpath = path + "\\" + fname;

      InputStream ins = file.getInputStream(); // part.getInputStream();
      OutputStream outs = new FileOutputStream(fpath);

      byte[] buffer = new byte[1024];

      int len = 0;

      while ((len = ins.read(buffer, 0, 1024)) >= 0) outs.write(buffer, 0, len);

      outs.flush();
      outs.close();
      ins.close();

      clothes.setImage(fname);
    }

    clothesDao.addClothes(clothes);

    return "redirect:codiRoomMyClothes";
  }
Exemplo n.º 21
0
  /**
   * Calculate and return an absolute pathname to the XML file to contain our persistent storage
   * information.
   *
   * @throws Exception if an input/output error occurs
   */
  private String calculatePath() throws Exception {

    // Can we access the database via file I/O?
    String path = context.getRealPath(pathname);
    if (path != null) {
      return (path);
    }

    // Does a copy of this file already exist in our temporary directory
    File dir = (File) context.getAttribute("javax.servlet.context.tempdir");
    File file = new File(dir, "struts-example-database.xml");
    if (file.exists()) {
      return (file.getAbsolutePath());
    }

    // Copy the static resource to a temporary file and return its path
    InputStream is = context.getResourceAsStream(pathname);
    BufferedInputStream bis = new BufferedInputStream(is, 1024);
    FileOutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
    byte buffer[] = new byte[1024];
    while (true) {
      int n = bis.read(buffer);
      if (n <= 0) {
        break;
      }
      bos.write(buffer, 0, n);
    }
    bos.close();
    bis.close();
    return (file.getAbsolutePath());
  }
 public ConceptDictionary20120509Patch(
     AdministrationService adminService,
     ServletContext servletContext,
     UploadConceptsController uploadConceptsController) {
   super(
       adminService, //
       PrivilegeConstants.ADD_PERSONS, //
       PrivilegeConstants.VIEW_ADMIN_FUNCTIONS, //
       PrivilegeConstants.VIEW_PERSON_ATTRIBUTE_TYPES, //
       PrivilegeConstants.VIEW_PROGRAMS, //
       PrivilegeConstants.VIEW_USERS, //
       PrivilegeConstants.MANAGE_PERSON_ATTRIBUTE_TYPES, //
       PrivilegeConstants.MANAGE_ROLES, //
       PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES, //
       PrivilegeConstants.MANAGE_CONCEPTS, //
       PrivilegeConstants.MANAGE_CONCEPT_SOURCES, //
       PrivilegeConstants.MANAGE_CONCEPT_CLASSES, //
       PrivilegeConstants.MANAGE_CONCEPT_DATATYPES, //
       PrivilegeConstants.MANAGE_PROGRAMS, //
       PrivilegeConstants.VIEW_CONCEPTS, //
       PrivilegeConstants.VIEW_CONCEPT_SOURCES, //
       PrivilegeConstants.VIEW_CONCEPT_CLASSES, //
       PrivilegeConstants.VIEW_CONCEPT_DATATYPES, //
       PrivilegeConstants.VIEW_OBS);
   this.uploadConceptsController = uploadConceptsController;
   this.patchFile = new File(new File(servletContext.getRealPath("/")), REL_PATCH_FILE);
 }
Exemplo n.º 23
0
  @Transactional
  public String upLoadImage(int id, ServletContext servletContext, MultipartFile file) {
    BufferedImage src = null;
    int counter = 0;
    String path = "/resources/chatimgs/";

    path = servletContext.getRealPath(path);
    File destination = null;
    try {
      src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
      if (!(new File(path)).exists()) {
        (new File(path)).mkdir();
      }

      destination = new File(path + String.valueOf(id) + "_" + file.getOriginalFilename());
      while (destination.exists()) {
        counter++;
        destination =
            new File(path + String.valueOf(id) + "_" + counter + "_" + file.getOriginalFilename());
      }
      ImageIO.write(src, "png", destination);
      String finalP = destination.getAbsolutePath().replace('\\', '/');
      int cut = finalP.indexOf("webapp");
      finalP = finalP.substring(cut + 7);
      return finalP;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * Gets the path to the resultset XSL file.
   *
   * @param request The HttpServletRequest object.
   * @return xslPath The real path to the resultset XSL file.
   */
  public String getResultsetXSL(HttpServletRequest request) {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    String xslPath = servletContext.getRealPath("style/common/resultset.xsl");

    return xslPath;
  }
Exemplo n.º 25
0
  public static Response respond(
      Bindings b, ServletContext con, String name, String message, int status) {
    try {

      String context = con.getContextPath();
      String baseFilePath = ServletUtils.withTrailingSlash(con.getRealPath("/"));
      String basePrefix = name.startsWith("/") ? "" : baseFilePath;

      String[] filesToTry =
          new String[] {
            "/etc/elda/conf.d/" + context + "/_errors/" + name + ".vm",
            basePrefix + "_errors/" + name + ".vm",
            "/etc/elda/conf.d/" + context + "/_errors/" + "_error" + ".vm",
            basePrefix + "_errors/" + "_error" + ".vm"
          };

      String page = fetchPage(filesToTry, fallBack);

      if (message == null) message = "Odd, no additional information is available.";
      b.put("_message", message);

      String builtPage = apply(b, page, name, message);

      return Response.status(status).entity(builtPage).build();
    } catch (Throwable e) {
      log.error("An exception occurred when rendering an error page:");
      log.error("  " + e.getMessage());
      return Response.status(Status.INTERNAL_SERVER_ERROR).entity(fallBack).build();
    }
  }
Exemplo n.º 26
0
  protected String initRootPath(final ServletContext context) {
    String rootPath = StringUtils.replace(context.getRealPath(StringUtils.EMPTY), "\\", "/");
    rootPath = StringUtils.removeEnd(rootPath, "/");
    System.setProperty(CONTINEO_APP_ROOTDIR, rootPath);

    return rootPath;
  }
  /**
   * All files containing serialization policy are located during construction of this object.
   * Serialization policies are loaded from them (and cached) as needed.
   *
   * @param servletContext
   * @throws IOException
   */
  @Autowired(required = false)
  public MultiModuleSerializationPolicyProvider(ServletContext servletContext) throws IOException {
    for (File rpcPolicyManifest : listRpcPolicyManifestFiles(servletContext.getRealPath("/"))) {
      File moduleDir = rpcPolicyManifest.getParentFile().getParentFile();
      LineIterator entries = FileUtils.lineIterator(rpcPolicyManifest);

      while (entries.hasNext()) {
        String line = entries.nextLine();
        if (line.startsWith("#") || line.trim().length() == 0) continue;

        String[] entry = line.split(",");
        assert entry.length == 2 : "Invalid format of file: " + rpcPolicyManifest.getAbsolutePath();
        String rpcServiceInterfaceName = entry[0].trim();
        String rpcPolicyStrongFileName = entry[1].trim();

        if (serializationPolicyFiles.containsKey(rpcServiceInterfaceName)) {
          assert serializationPolicyFiles
              .get(rpcServiceInterfaceName)
              .getName()
              .equals(rpcPolicyStrongFileName);
        } else {
          File serializationPolicyFile = new File(moduleDir, rpcPolicyStrongFileName);
          assert serializationPolicyFile.exists();
          serializationPolicyFiles.put(rpcServiceInterfaceName, serializationPolicyFile);
        }
      }

      LineIterator.closeQuietly(entries);
    }
  }
Exemplo n.º 28
0
  /**
   * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    Properties boot = loadBootProperties(context);
    String contineoHome = boot.getProperty(CONTINEO_HOME);

    // replace system properties
    if (contineoHome.indexOf("$") != -1) {
      contineoHome = StrSubstitutor.replaceSystemProperties(contineoHome);
    }

    boot.setProperty(CONTINEO_HOME, initContineoHomePath(contineoHome));
    boot.setProperty(CONTINEO_APP_ROOTDIR, initRootPath(context));
    boot.setProperty(CONTINEO_APP_PLUGINSDIR, initPluginsPath(context));
    boot.setProperty(CONTINEO_APP_PLUGINREGISTRY, initPluginRegistry());

    try {
      String log4jPath = context.getRealPath("/WEB-INF/classes/log4j.xml");
      System.out.println("log4jPath = " + log4jPath);
      Log4jConfigurer.initLogging(log4jPath);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    saveBootProperties(boot, context);

    // Initialize plugins
    org.contineo.util.PluginRegistry.getInstance().init();
  }
Exemplo n.º 29
0
  /** @see HttpServlet#HttpServlet() */
  @Override
  public void init(ServletConfig config) throws ServletException {

    String log4jLocation = config.getInitParameter("log4j-properties-location");

    ServletContext sc = config.getServletContext();

    if (log4jLocation == null) {

      BasicConfigurator.configure();
    } else {
      String webAppPath = sc.getRealPath("/");
      String log4jProp = webAppPath + log4jLocation;
      File output = new File(log4jProp);

      if (output.exists()) {

        PropertyConfigurator.configure(log4jProp);
      } else {

        BasicConfigurator.configure();
      }
    }

    super.init(config);
  }
Exemplo n.º 30
0
  public void uploadImage(UploadEvent evento) throws FileNotFoundException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
    String caminhoReal = sc.getRealPath("/");
    String extensao = "";
    UploadItem item = evento.getUploadItem();
    String fileName = item.getFileName();
    String ext[] = fileName.split("\\.");
    int i = ext.length;

    if (i > 1) {
      extensao = ext[i - 1];
    }

    Long tempo = System.currentTimeMillis();
    OutputStream out =
        new FileOutputStream(caminhoReal + "/ImagensPizza/" + "img" + tempo + "." + extensao);
    setImagePath("/ImagensPizza/" + "img" + tempo + "." + extensao);

    try {
      out.write(item.getData());
      out.close();

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