public static void startDownload(
      Context context, Magazine magazine, boolean isTemp, String tempUrlKey) {
    String fileUrl = magazine.getItemUrl();
    String filePath = magazine.getItemPath();
    if (magazine.isSample()) {
      fileUrl = magazine.getSamplePdfUrl();
      filePath = magazine.getSamplePdfPath();
    } else if (isTemp) {
      fileUrl = tempUrlKey;
    }
    Log.d(
        TAG,
        "isSample: " + magazine.isSample() + "\nfileUrl: " + fileUrl + "\nfilePath: " + filePath);
    EasyTracker.getTracker().sendView("Downloading/" + FilenameUtils.getBaseName(filePath));
    DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
    request
        .setVisibleInDownloadsUi(false)
        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        .setDescription(magazine.getSubtitle())
        .setTitle(magazine.getTitle() + (magazine.isSample() ? " Sample" : ""))
        .setDestinationInExternalFilesDir(context, null, FilenameUtils.getName(filePath));
    // TODO should use cache directory?
    magazine.setDownloadManagerId(dm.enqueue(request));

    MagazineManager magazineManager = new MagazineManager(context);
    magazineManager.removeDownloadedMagazine(context, magazine);
    magazineManager.addMagazine(magazine, Magazine.TABLE_DOWNLOADED_MAGAZINES, true);
    magazine.clearMagazineDir();
    EventBus.getDefault().post(new LoadPlistEvent());
  }
Beispiel #2
0
 /**
  * Find in the url the filename
  *
  * @param url
  * @return
  */
 private String findFileName(URL url) {
   String name = FilenameUtils.getName(url.getPath());
   if (isWellFormedFileName(name)) return name;
   name = FilenameUtils.getName(url.toString());
   if (isWellFormedFileName(name)) return name;
   return FilenameUtils.getName(url.getPath());
 }
  private void save(String filename, String uploadedBy) {
    message += "Start reading file from " + FilenameUtils.getName(filename) + "\n";
    String uuid = UploadUtils.generateUUID();
    Parser parser = null;
    UploadLog log = null;
    ParseDao dao = null;
    // save upload log table
    try {

      dao = new ParseDao();
      if (dao.isParsed(UploadUtils.getChecksumString(filename))) {
        message += "File already parsed before\n";
        return;
      }
      log = new UploadLog();
      log.setBatchID(uuid);
      log.setFilename(FilenameUtils.getName(filename));
      log.setChecksum(UploadUtils.getChecksumString(filename));
      log.setUploadedBy(uploadedBy);
      log.setDtStamp();
      dao.saveUploadLog(log);
      message += "Saved to upload log table\n";
      try {
        message += "Start parsing file\n";
        parser = new Parser();
        message += parser.doParse(filename, uuid) + "\n";
      } catch (Exception e) {
        message += "Error Parsing file " + e.getMessage();
      }
    } catch (Exception e) {
      message += "Error saving to log table " + e.getMessage();
    }
  }
  @Override
  public CriterionSettingsDto mapConfiguration(final TaskInfo taskInfo) {
    CriterionSettingsDto dto = new CriterionSettingsDto();
    extractTaskData(taskInfo, dto);

    IUserConfiguration configuration = taskInfo.getUserConfiguration();
    dto.sourceFile = FilenameUtils.getName(configuration.getSource().csv.filePath);
    dto.resultFile = FilenameUtils.getName(configuration.getResultFile());

    return dto;
  }
  @Override
  public void createOrUpdateView(String path, String config, boolean ignoreExisting) {
    validateUpdateArgs(path, config);
    String viewBaseName = FilenameUtils.getName(path);
    Jenkins.checkGoodName(viewBaseName);
    try {
      InputStream inputStream = new ByteArrayInputStream(config.getBytes("UTF-8"));

      ItemGroup parent = lookupStrategy.getParent(build.getProject(), path);
      if (parent instanceof ViewGroup) {
        View view = ((ViewGroup) parent).getView(viewBaseName);
        if (view == null) {
          if (parent instanceof Jenkins) {
            ((Jenkins) parent).addView(createViewFromXML(viewBaseName, inputStream));
          } else if (parent instanceof Folder) {
            ((Folder) parent).addView(createViewFromXML(viewBaseName, inputStream));
          } else {
            LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass()));
          }
        } else if (!ignoreExisting) {
          view.updateByXml(new StreamSource(inputStream));
        }
      } else if (parent == null) {
        throw new DslException(format(Messages.CreateView_UnknownParent(), path));
      } else {
        LOGGER.log(Level.WARNING, format("Could not create view within %s", parent.getClass()));
      }
    } catch (UnsupportedEncodingException e) {
      LOGGER.log(Level.WARNING, "Unsupported encoding used in config. Should be UTF-8.");
    } catch (IOException e) {
      e.printStackTrace();
      LOGGER.log(Level.WARNING, format("Error writing config for new view %s.", path), e);
    }
  }
 /**
  * Download file entry of given path.
  *
  * @param user current user
  * @param path user
  * @param response response
  */
 @RequestMapping("/download/**")
 public void download(User user, @RemainedPath String path, HttpServletResponse response) {
   FileEntry fileEntry = fileEntryService.getFileEntry(user, path);
   if (fileEntry == null) {
     LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
     return;
   }
   response.reset();
   try {
     response.addHeader(
         "Content-Disposition",
         "attachment;filename="
             + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
   } catch (UnsupportedEncodingException e1) {
     LOG.error(e1.getMessage(), e1);
   }
   response.setContentType("application/octet-stream; charset=UTF-8");
   response.addHeader("Content-Length", "" + fileEntry.getFileSize());
   byte[] buffer = new byte[4096];
   ByteArrayInputStream fis = null;
   OutputStream toClient = null;
   try {
     fis = new ByteArrayInputStream(fileEntry.getContentBytes());
     toClient = new BufferedOutputStream(response.getOutputStream());
     int readLength;
     while (((readLength = fis.read(buffer)) != -1)) {
       toClient.write(buffer, 0, readLength);
     }
   } catch (IOException e) {
     throw new NGrinderRuntimeException("error while download file", e);
   } finally {
     IOUtils.closeQuietly(fis);
     IOUtils.closeQuietly(toClient);
   }
 }
  private static void saveLog(final String absolutePath, final String downloadUrl)
      throws Exception {
    // System.out.println("downloadUrl: " + downloadUrl);

    final File directory = new File(absolutePath);
    if (!directory.exists()) {
      directory.mkdirs();
    }

    final String fileName = FilenameUtils.getName(downloadUrl);
    final File file = new File(absolutePath + File.separator + fileName);

    try (FileOutputStream fos = new FileOutputStream(file)) {

      final URL website = new URL(downloadUrl);
      final ReadableByteChannel rbc = Channels.newChannel(website.openStream());
      fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

      cleanFile(website.openStream(), file);
    } catch (MalformedURLException e) {
      throw e;
    } catch (IOException e) {
      throw e;
    }
  }
Beispiel #8
0
 public String add(HttpServletRequest req, HttpServletResponse resp)
     throws FileNotFoundException, IOException {
   Product p = (Product) RequestUtil.setParam(Product.class, req);
   p.setStatus(1);
   RequestUtil.Validate(Product.class, req);
   int cid = 0;
   try {
     cid = Integer.parseInt(req.getParameter("cid"));
   } catch (NumberFormatException e) {
   }
   if (cid == 0) {
     this.getErrors().put("cid", "商品类别必须选择");
   }
   if (!this.hasErrors()) {
     // 文件上传
     byte[] fs = (byte[]) req.getAttribute("fs");
     String fname = req.getParameter("img");
     fname = FilenameUtils.getName(fname);
     RequestUtil.uploadFile(fname, "img", fs, req);
   }
   if (this.hasErrors()) {
     addInput(req, resp);
     return "product/addInput.jsp";
   }
   productDao.add(p, cid);
   return redirPath + "ProductServlet?method=list";
 }
Beispiel #9
0
  public void zip(ArrayList<String> fileList, File destFile, int compressionLevel)
      throws Exception {

    if (destFile.exists()) throw new Exception("File " + destFile.getName() + " already exists!!");

    int fileLength;
    byte[] buffer = new byte[4096];

    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zipFile = new ZipOutputStream(bos);
    zipFile.setLevel(compressionLevel);

    for (int i = 0; i < fileList.size(); i++) {

      FileInputStream fis = new FileInputStream(fileList.get(i));
      BufferedInputStream bis = new BufferedInputStream(fis);
      ZipEntry ze = new ZipEntry(FilenameUtils.getName(fileList.get(i)));
      zipFile.putNextEntry(ze);

      while ((fileLength = bis.read(buffer, 0, 4096)) > 0) zipFile.write(buffer, 0, fileLength);

      zipFile.closeEntry();
      bis.close();
    }

    zipFile.close();
  }
  private void updateGeneratedViews(
      AbstractBuild<?, ?> build, BuildListener listener, Set<GeneratedView> freshViews)
      throws IOException {
    Set<GeneratedView> generatedViews =
        extractGeneratedObjects(build.getProject(), GeneratedViewsAction.class);
    Set<GeneratedView> added = Sets.difference(freshViews, generatedViews);
    Set<GeneratedView> existing = Sets.intersection(generatedViews, freshViews);
    Set<GeneratedView> removed = Sets.difference(generatedViews, freshViews);

    logItems(listener, "Adding views", added);
    logItems(listener, "Existing views", existing);
    logItems(listener, "Removing views", removed);

    // Delete views
    if (removedViewAction == RemovedViewAction.DELETE) {
      for (GeneratedView removedView : removed) {
        String viewName = removedView.getName();
        ItemGroup parent = getLookupStrategy().getParent(build.getProject(), viewName);
        if (parent instanceof ViewGroup) {
          View view = ((ViewGroup) parent).getView(FilenameUtils.getName(viewName));
          if (view != null) {
            ((ViewGroup) parent).deleteView(view);
          }
        } else if (parent == null) {
          LOGGER.log(Level.FINE, "Parent ViewGroup seems to have been already deleted");
        } else {
          LOGGER.log(Level.WARNING, format("Could not delete view within %s", parent.getClass()));
        }
      }
    }
  }
Beispiel #11
0
  /** @see ContributionItem#fill(Menu, int) */
  @Override
  public void fill(final Menu menu, int index) {
    RecentProjectsService rfs =
        (RecentProjectsService) PlatformUI.getWorkbench().getService(RecentProjectsService.class);
    RecentProjectsService.Entry[] entries = rfs.getRecentFiles();
    if (entries == null || entries.length == 0) {
      return;
    }

    // add separator
    new MenuItem(menu, SWT.SEPARATOR, index);

    int i = entries.length;
    for (RecentProjectsService.Entry entry : entries) {
      String file = entry.getFile();
      MenuItem mi = new MenuItem(menu, SWT.PUSH, index);
      String filename = FilenameUtils.getName(file);
      String shortened = shorten(file, MAX_LENGTH, filename.length());
      String nr = String.valueOf(i);
      if (i <= 9) {
        // add mnemonic for the first 9 items
        nr = "&" + nr; // $NON-NLS-1$
      }
      mi.setText(nr + "  " + shortened); // $NON-NLS-1$
      mi.setData(file);
      mi.addSelectionListener(new MenuItemSelectionListener(new File(file)));
      --i;
    }
  }
 /**
  * @param path
  * @param tmpWarDir
  * @throws IOException
  */
 private static void copy(Enumeration<String> paths, File destDir) throws IOException {
   if (paths != null) {
     while (paths.hasMoreElements()) {
       String path = paths.nextElement();
       if (path.endsWith("/")) {
         File targetDir =
             new File(destDir, FilenameUtils.getName(path.substring(0, path.lastIndexOf("/"))));
         copy(Activator.getContext().getBundle().getEntryPaths(path), targetDir);
       } else {
         URL entry = Activator.getContext().getBundle().getEntry(path);
         FileUtils.copyInputStreamToFile(
             entry.openStream(), new File(destDir, FilenameUtils.getName(path)));
       }
     }
   }
 }
Beispiel #13
0
  public String parse(ImageChunk chunk) {
    //	public String parse(final String path, final String options) {
    String output = "\\begin{figure}[H]\n\\centering\n";

    output = output + "\\includegraphics";

    double width = chunk.getActualWidth();

    if (chunk.getWidthPercentage() != 0.0) {
      output = output + "[width=" + (pageWidth * chunk.getWidthPercentage()) + "mm]";
    } else if (width > pageWidth) {
      output = output + "[width=\\textwidth]";
    } else {
      output = output + "[scale=1]";
    }

    String imgsrc = FilenameUtils.getName(chunk.getPath());
    output = output + "{" + imgsrc + "}\n";

    if (!chunk.getDescription().isEmpty()) {
      output = output + "\n\n\\caption{" + chunk.getDescription() + "}\n\n";
    }

    output = output + "\\end{figure}\n\n";

    return output;
  }
  public String putBlob(String container, Blob blob) {
    try {

      String name = FilenameUtils.getName(blob.getMetadata().getName());
      String path = FilenameUtils.getPathNoEndSeparator(blob.getMetadata().getName());

      service.uploadInputStream(
          blob.getPayload().getInput(),
          container,
          path,
          name,
          blob.getPayload().getContentMetadata().getContentLength());

      return null;
    } catch (UploadException e) {
      e.printStackTrace();
      return null;
    } catch (MethodNotSupportedException e) {
      e.printStackTrace();
      return null;
    } catch (FileNotExistsException e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse response)
      throws ServletException, IOException {
    // Extract the relevant content from the POST'd form
    if (ServletFileUpload.isMultipartContent(req)) {
      Map<String, String> responseMap;
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);

      // Parse the request
      String deploymentType = null;
      String version = null;
      String fileName = null;
      InputStream artifactContent = null;
      try {
        List<FileItem> items = upload.parseRequest(req);
        for (FileItem item : items) {
          if (item.isFormField()) {
            if (item.getFieldName().equals("deploymentType")) { // $NON-NLS-1$
              deploymentType = item.getString();
            } else if (item.getFieldName().equals("version")) { // $NON-NLS-1$
              version = item.getString();
            }
          } else {
            fileName = item.getName();
            if (fileName != null) fileName = FilenameUtils.getName(fileName);
            artifactContent = item.getInputStream();
          }
        }

        // Default version is 1.0
        if (version == null || version.trim().length() == 0) {
          version = "1.0"; // $NON-NLS-1$
        }

        // Now that the content has been extracted, process it (upload the artifact to the s-ramp
        // repo).
        responseMap = uploadArtifact(deploymentType, fileName, version, artifactContent);
      } catch (SrampAtomException e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } catch (Throwable e) {
        responseMap = new HashMap<String, String>();
        responseMap.put("exception", "true"); // $NON-NLS-1$ //$NON-NLS-2$
        responseMap.put("exception-message", e.getMessage()); // $NON-NLS-1$
        responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); // $NON-NLS-1$
      } finally {
        IOUtils.closeQuietly(artifactContent);
      }
      writeToResponse(responseMap, response);
    } else {
      response.sendError(
          HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
          Messages.i18n.format("DeploymentUploadServlet.ContentTypeInvalid")); // $NON-NLS-1$
    }
  }
 /**
  * 文件解压到默认目录
  *
  * @param file 压缩文件
  * @param onSite true-当前目录|false-文件名目录
  */
 public static void decompress(File file, boolean onSite) {
   if (onSite) {
     CompressUtilsHelper.decompress(file, new File(file.getParent()), DEFAULT_ENCODING);
     return;
   }
   String dirName = FilenameUtils.getName(file.getName());
   File dir = new File(file.getParent(), dirName);
   CompressUtilsHelper.decompress(file, dir, DEFAULT_ENCODING);
 }
 @SneakyThrows
 public void writeFrameworkFiles(FilePath frameworkPath) {
   for (String asset : ASSETS) {
     String source = IOUtils.toString(getClass().getResourceAsStream(asset));
     String assetFileName = FilenameUtils.getName(asset);
     String destinationFilename = FilenameUtils.concat(frameworkPath.getPath(), assetFileName);
     FileUtils.write(new File(destinationFilename), source);
   }
 }
 /** @return SiteMap/SiteMapIndex by guessing the content type from the binary content and URL */
 public AbstractSiteMap parseSiteMap(byte[] content, URL url)
     throws UnknownFormatException, IOException {
   if (url == null) {
     return null;
   }
   String filename = FilenameUtils.getName(url.getPath());
   String contentType = TIKA.detect(content, filename);
   return parseSiteMap(contentType, content, url);
 }
Beispiel #19
0
 /**
  * Get the parent of the file at a path.
  *
  * @param path The path
  * @return the parent path of the file; this is "/" if the given path is the root.
  * @throws InvalidPathException
  */
 public static String getParent(String path) throws InvalidPathException {
   String cleanedPath = cleanPath(path);
   String name = FilenameUtils.getName(cleanedPath);
   String parent = cleanedPath.substring(0, cleanedPath.length() - name.length() - 1);
   if (parent.isEmpty()) {
     // The parent is the root path
     return TachyonURI.SEPARATOR;
   }
   return parent;
 }
Beispiel #20
0
 /**
  * Make the file, this is a temporary file which will be changed when the script is validated.
  *
  * @param script script.
  * @return OriginalFile tempfile..
  * @throws ServerError
  */
 private OriginalFile makeFile(final String path, final String script, Ice.Current current)
     throws ServerError {
   OriginalFile file = new OriginalFile();
   file.setName(FilenameUtils.getName(path));
   file.setPath(FilenameUtils.getFullPath(path));
   file.setSize((long) script.getBytes().length);
   file.setHasher(new ChecksumAlgorithm("SHA1-160"));
   file.setHash(cpf.getProvider(ChecksumType.SHA1).putBytes(script.getBytes()).checksumAsString());
   scripts.setMimetype(file);
   return updateFile(file, current);
 }
 /**
  * @param filename The name of the file to get the extension from.
  * @return String The file extension of the supplied filename.
  */
 public static String getExtension(String filename) {
   // if filename from a url, may have querystring appended: remove it
   // TODO: we fail to generate correct extensions in the case of semi-colon separated path
   // parameters
   // which are both rare and rarely used correctly
   final int queryPos = filename.indexOf('?');
   String bareFilename = queryPos > -1 ? filename.substring(0, queryPos) : filename;
   String nameOnly = FilenameUtils.getName(bareFilename);
   final int dotPos = nameOnly.lastIndexOf('.');
   return dotPos > 0 ? nameOnly.substring(dotPos + 1) : "";
 }
  @Override
  public File getFile(String scope, String name) throws IOException {
    File file = this.getLocation(scope, name);

    File tmpFile = File.createTempFile("sua-tmp-", FilenameUtils.getName(name));
    tmpFile.delete();
    if (file.exists()) {
      FileUtils.copyFile(file, tmpFile);
    }
    this.returnedFiles.add(tmpFile);
    return tmpFile;
  }
 private void saveResult(final File orgininalFile, final String result, String suffix)
     throws IOException {
   if (suffix == null) {
     suffix = ".update.result";
   } else {
     suffix = ".update" + suffix + ".result";
   }
   final File resultFile =
       new File(
           orgininalFile.getParentFile(), FilenameUtils.getName(orgininalFile.getName()) + suffix);
   FileUtils.write(resultFile, result);
 }
Beispiel #24
0
 /**
  * 上传彩信附件
  *
  * @param file
  * @param type 附件类型 pic-图片 sound-声音文件
  * @return
  * @throws IOException
  */
 @RequestMapping(
     value = "single_upload",
     headers = "content-type=multipart/*",
     produces = "text/html",
     method = RequestMethod.POST)
 @ResponseBody
 public Object singleUpload(
     @RequestParam("mmsupfile") MultipartFile file, @RequestParam("type") String type)
     throws IOException {
   logUtils.logView(MODULE_NAME, "上传文件");
   InputStream is = file.getInputStream();
   String fileName = FilenameUtils.getName(file.getOriginalFilename());
   return contentService.uploadFile(fileName, type, is);
 }
 public static String getFileName(String url) {
   String name = FilenameUtils.getName(url);
   // if no extension defined - let's guess it
   if (FilenameUtils.getExtension(name).isEmpty()) {
     name += ".jpg";
   } else {
     // skip url params
     int urlParamsIndex = name.indexOf('?');
     if (urlParamsIndex > 0) {
       name = name.substring(0, urlParamsIndex);
     }
   }
   return name;
 }
  protected void processFile(FileItem item, String name, MutableRequest request) {
    try {
      String fileName = FilenameUtils.getName(item.getName());
      UploadedFile upload =
          new DefaultUploadedFile(
              item.getInputStream(), fileName, item.getContentType(), item.getSize());
      request.setParameter(name, name);
      request.setAttribute(name, upload);

      logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
      throw new InvalidParameterException("Can't parse uploaded file " + item.getName(), e);
    }
  }
Beispiel #27
0
 /**
  * @param context in the form of /foo
  * @param parent in the form of /foo/bar/ or /foo/bar/dar.jss
  * @param scriptPath in the form of /foo/bar/mar.jss or bar/mar.jss
  * @return String[] with keys
  */
 public static String[] getKeys(String context, String parent, String scriptPath) {
   String path;
   String normalizedScriptPath;
   context = context.equals("") ? "/" : context;
   normalizedScriptPath =
       scriptPath.startsWith("/")
           ? FilenameUtils.normalize(scriptPath, true)
           : FilenameUtils.normalize(FilenameUtils.getFullPath(parent) + scriptPath, true);
   path = FilenameUtils.getFullPath(normalizedScriptPath);
   // remove trailing "/"
   path = path.equals("/") ? path : path.substring(0, path.length() - 1);
   normalizedScriptPath = "/" + FilenameUtils.getName(normalizedScriptPath);
   return new String[] {context, path, normalizedScriptPath};
 }
  public ComponentDto createForFile(
      Component file, PathAwareVisitor.Path<ComponentDtoHolder> path) {
    ComponentDto res = createBase(file);

    res.setScope(Scopes.FILE);
    res.setQualifier(getFileQualifier(file));
    res.setName(FilenameUtils.getName(file.getReportAttributes().getPath()));
    res.setLongName(file.getReportAttributes().getPath());
    res.setPath(file.getReportAttributes().getPath());
    res.setLanguage(file.getFileAttributes().getLanguageKey());

    setParentModuleProperties(res, path);

    return res;
  }
Beispiel #29
0
 public String update(HttpServletRequest req, HttpServletResponse resp)
     throws FileNotFoundException, IOException {
   Product p = (Product) RequestUtil.setParam(Product.class, req);
   RequestUtil.Validate(Product.class, req);
   String img = req.getParameter("img");
   System.out.println(img + "----------------------");
   int cid = 0;
   try {
     cid = Integer.parseInt(req.getParameter("cid"));
   } catch (NumberFormatException e) {
   }
   if (cid == 0) {
     this.getErrors().put("cid", "商品类别必须选择");
   }
   Product tp = productDao.load(Integer.parseInt(req.getParameter("id")));
   tp.setIntro(p.getIntro());
   tp.setName(p.getName());
   tp.setPrice(p.getPrice());
   tp.setStock(p.getStock());
   boolean updateImg = false;
   if (img == null || img.trim().equals("")) {
     // 此时说明不修改图片
   } else {
     // 此时说明需要修改图片
     if (!this.hasErrors()) {
       // 是否要修改文件
       byte[] fs = (byte[]) req.getAttribute("fs");
       String fname = req.getParameter("img");
       fname = FilenameUtils.getName(fname);
       RequestUtil.uploadFile(fname, "img", fs, req);
     }
     updateImg = true;
   }
   if (this.hasErrors()) {
     req.setAttribute("p", tp);
     req.setAttribute("cs", categoryDao.list());
     return "product/updateInput.jsp";
   }
   if (updateImg) {
     // 先删除原有的图片
     String oimg = tp.getImg();
     File f = new File(SystemContext.getRealpath() + "/img/" + oimg);
     f.delete();
     tp.setImg(p.getImg());
   }
   productDao.update(tp, cid);
   return redirPath + "ProductServlet?method=list";
 }
Beispiel #30
0
 Win32FindData toWin32FindData() {
   String lName = FilenameUtils.getName(fileName);
   String sName = Utils.toShortName(fileName);
   Win32FindData d =
       new Win32FindData(
           fileAttribute,
           creationTime,
           lastAccessTime,
           lastWriteTime,
           fileSize,
           0,
           0,
           lName,
           sName);
   return d;
 }