/**
   * 测试文件上传
   *
   * @param fileName
   * @param uploadedInputStream
   * @param fileDetail
   * @param keywordObjs
   * @return
   */
  public String uploadFile2(
      String fileName,
      InputStream fileInputStream,
      FormDataContentDisposition fileContentDisposition) {
    String fileFullName = fileContentDisposition.getFileName();

    String fileType = fileFullName.substring(fileFullName.indexOf("."), fileFullName.length());
    String newFileName = fileName + fileType;
    File file = new File("F:/temp", newFileName);
    try {
      OutputStream outputStream = new FileOutputStream(file);
      int length = 0;

      byte[] buff = new byte[256];

      while (-1 != (length = fileInputStream.read(buff))) {
        outputStream.write(buff, 0, length);
      }
      fileInputStream.close();
      outputStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return fileFullName;
  }
  @POST
  @Path("/send")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadFile(
      @Context UriInfo info,
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail,
      @FormDataParam("endpointPath") String endpointPath,
      @FormDataParam("queryParameters") String queryParameters)
      throws URISyntaxException, UnsupportedEncodingException {

    String uploadedFileLocation = DIRECTORY + fileDetail.getFileName();

    String filePath = new File(uploadedFileLocation).getAbsolutePath();

    try {

      writeToFile(uploadedInputStream, uploadedFileLocation);

    } catch (IOException e) {
      System.out.println("[File Uploader] Error uploading file: " + filePath);
      e.printStackTrace();
    }

    URI pentahoBaseUrl = info.getBaseUri().resolve("../");
    endpointPath = pentahoBaseUrl + endpointPath;
    endpointPath += "?paramfileUrl=" + URLEncoder.encode(filePath, "UTF-8") + queryParameters;

    return Response.temporaryRedirect(new URI(endpointPath)).build();
  }
  // save uploaded file to the local disk
  private void saveToDisk(InputStream uploadedInputStream, FormDataContentDisposition fileDetail) {
    String uploadedFileLocation =
        "d://AplikacjeProsteNaukowe/upload/"
            + fileDetail.getFileName(); // specyfying where to save this file
    try {
      OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
      int read = 0;
      byte[] bytes = new byte[1024];

      out = new FileOutputStream(new File(uploadedFileLocation));
      while ((read = uploadedInputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
      }
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @POST
  @Path("/documents")
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public Response createUploadFile(
      @HeaderParam("Content-Length") final Long fileSize,
      @FormDataParam("file") final InputStream inputStream,
      @FormDataParam("file") final FormDataContentDisposition fileDetails,
      @FormDataParam("file") final FormDataBodyPart bodyPart,
      @FormDataParam("status") final String name,
      @FormDataParam("description") final String description) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, name, ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);
    inputStreamObject = inputStream;
    DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
    final Date date = DateUtils.getDateOfTenant();
    final DateTimeFormatter dtf = DateTimeFormat.forPattern("dd MMMM yyyy");
    final LocalDate localdate = dtf.parseLocalDate(dateFormat.format(date));
    final String fileUploadLocation = FileUtils.generateXlsFileDirectory();
    final String fileName = fileDetails.getFileName();
    if (!new File(fileUploadLocation).isDirectory()) {
      new File(fileUploadLocation).mkdirs();
    }
    final DataUploadCommand uploadStatusCommand =
        new DataUploadCommand(
            name,
            null,
            localdate,
            "",
            null,
            null,
            null,
            description,
            fileName,
            inputStream,
            fileUploadLocation);
    CommandProcessingResult id = this.dataUploadWritePlatformService.addItem(uploadStatusCommand);
    return Response.ok().entity(id.toString()).build();
    // return null;
  }
  @POST
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public String createDocument(
      @PathParam("entityType") final String entityType,
      @PathParam("entityId") final Long entityId,
      @HeaderParam("Content-Length") final Long fileSize,
      @FormDataParam("file") final InputStream inputStream,
      @FormDataParam("file") final FormDataContentDisposition fileDetails,
      @FormDataParam("file") final FormDataBodyPart bodyPart,
      @FormDataParam("name") final String name,
      @FormDataParam("description") final String description) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, name, ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);

    /**
     * TODO: also need to have a backup and stop reading from stream after max size is reached to
     * protect against malicious clients
     */

    /** TODO: need to extract the actual file type and determine if they are permissable */
    final DocumentCommand documentCommand =
        new DocumentCommand(
            null,
            null,
            entityType,
            entityId,
            name,
            fileDetails.getFileName(),
            fileSize,
            bodyPart.getMediaType().toString(),
            description,
            null);

    final Long documentId =
        this.documentWritePlatformService.createDocument(documentCommand, inputStream);

    return this.toApiJsonSerializer.serialize(
        CommandProcessingResult.resourceResult(documentId, null));
  }
  @POST
  @RolesAllowed({"OWER"})
  @Consumes("multipart/form-data")
  public Response update(
      @FormDataParam("name") String name,
      @FormDataParam("telephone") String telephone,
      @FormDataParam("address") String address,
      @DefaultValue("-1000") @FormDataParam("x") double x,
      @DefaultValue("-1000") @FormDataParam("y") double y,
      @FormDataParam("image") InputStream upImg,
      @FormDataParam("image") FormDataContentDisposition fileDetail,
      @Context SecurityContext securityContext) {

    RestaurantDao dao = new RestaurantDao();

    // TODO 需要判断该restaurant是否是该用户的,如果不是,则无权限修改
    User user = PublicHelper.getLoginUser(securityContext);
    if (user.getId() != r.getUser().getId()) {
      throw new WebApplicationException(Response.Status.FORBIDDEN);
    }

    r.setName(name);
    r.setAddress(address);
    r.setTelephone(telephone);
    if (x != -1000) {
      r.setX(x);
    }
    if (y != -1000) {
      r.setY(y);
    }
    r.setStatus(0);

    if (upImg != null && !StringUtils.isEmpty(fileDetail.getFileName())) {
      try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = upImg.read(data, 0, data.length)) != -1) {
          buffer.write(data, 0, nRead);
        }
        buffer.flush();
        byte[] bs = buffer.toByteArray();

        if (bs.length > 0) {
          String id = UUID.randomUUID().toString();
          String image = id + ".png";
          r.setImage(image);

          BufferedImage bi = ImageIO.read(new ByteArrayInputStream(bs));

          File file = new File(PublicConfig.getImagePath() + image);
          if (file.isDirectory()) {
            ImageIO.write(bi, "png", file);
          } else {
            file.mkdirs();
            ImageIO.write(bi, "png", file);
          }
        }

      } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
            .entity("创建菜单失败")
            .type(MediaType.TEXT_PLAIN)
            .build();
      }
    }

    dao.saveOrUpdate(r);

    return Response.status(Response.Status.OK).build();
  }
  @PUT
  @Path("{documentId}")
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public String updateDocument(
      @PathParam("entityType") final String entityType,
      @PathParam("entityId") final Long entityId,
      @PathParam("documentId") final Long documentId,
      @HeaderParam("Content-Length") final Long fileSize,
      @FormDataParam("file") final InputStream inputStream,
      @FormDataParam("file") final FormDataContentDisposition fileDetails,
      @FormDataParam("file") final FormDataBodyPart bodyPart,
      @FormDataParam("name") final String name,
      @FormDataParam("description") final String description) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, name, ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);

    final Set<String> modifiedParams = new HashSet<String>();
    modifiedParams.add("name");
    modifiedParams.add("description");

    /**
     * * Populate Document command based on whether a file has also been passed in as a part of the
     * update *
     */
    DocumentCommand documentCommand = null;
    if (inputStream != null && fileDetails.getFileName() != null) {
      modifiedParams.add("fileName");
      modifiedParams.add("size");
      modifiedParams.add("type");
      modifiedParams.add("location");
      documentCommand =
          new DocumentCommand(
              modifiedParams,
              documentId,
              entityType,
              entityId,
              name,
              fileDetails.getFileName(),
              fileSize,
              bodyPart.getMediaType().toString(),
              description,
              null);
    } else {
      documentCommand =
          new DocumentCommand(
              modifiedParams,
              documentId,
              entityType,
              entityId,
              name,
              null,
              null,
              null,
              description,
              null);
    }
    /** * TODO: does not return list of changes, should be done for consistency with rest of API */
    final CommandProcessingResult identifier =
        this.documentWritePlatformService.updateDocument(documentCommand, inputStream);

    return this.toApiJsonSerializer.serialize(identifier);
  }
  /**
   * @param entityType
   * @param entityId
   * @param documentId
   * @param fileSize
   * @param inputStream
   * @param fileDetails
   * @param bodyPart
   * @param name
   * @param description
   * @return
   */
  @PUT
  @Path("{documentId}")
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public Response updateDocument(
      @PathParam("entityType") String entityType,
      @PathParam("entityId") Long entityId,
      @PathParam("documentId") Long documentId,
      @HeaderParam("Content-Length") Long fileSize,
      @FormDataParam("file") InputStream inputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetails,
      @FormDataParam("file") FormDataBodyPart bodyPart,
      @FormDataParam("name") String name,
      @FormDataParam("description") String description) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, name, ApplicationConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);

    Set<String> modifiedParams = new HashSet<String>();
    modifiedParams.add("name");
    modifiedParams.add("description");

    /**
     * * Populate Document command based on whether a file has also been passed in as a part of the
     * update *
     */
    DocumentCommand documentCommand = null;
    if (inputStream != null && fileDetails.getFileName() != null) {
      modifiedParams.add("fileName");
      modifiedParams.add("size");
      modifiedParams.add("type");
      modifiedParams.add("location");
      documentCommand =
          new DocumentCommand(
              modifiedParams,
              documentId,
              entityType,
              entityId,
              name,
              fileDetails.getFileName(),
              fileSize,
              bodyPart.getMediaType().toString(),
              description,
              null);
    } else {
      documentCommand =
          new DocumentCommand(
              modifiedParams,
              documentId,
              entityType,
              entityId,
              name,
              null,
              null,
              null,
              description,
              null);
    }
    EntityIdentifier identifier =
        this.documentWritePlatformService.updateDocument(documentCommand, inputStream);

    return Response.ok().entity(identifier).build();
  }
  @POST
  @Path("{ticketId}/attachment")
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public String addTicketDetails(
      @PathParam("ticketId") Long ticketId,
      @PathParam("entityType") String entityType,
      @PathParam("entityId") Long entityId,
      @HeaderParam("Content-Length") Long fileSize,
      @FormDataParam("file") InputStream inputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetails,
      @FormDataParam("file") FormDataBodyPart bodyPart,
      @FormDataParam("comments") String comments,
      @FormDataParam("status") String status,
      @FormDataParam("assignedTo") Long assignedTo,
      @FormDataParam("ticketURL") String ticketURL,
      @FormDataParam("problemCode") Integer problemCode,
      @FormDataParam("priority") String priority,
      @FormDataParam("resolutionDescription") String resolutionDescription,
      @FormDataParam("username") String username) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, null, ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);

    /**
     * TODO: also need to have a backup and stop reading from stream after max size is reached to
     * protect against malicious clients
     */

    /** TODO: need to extract the actual file type and determine if they are permissable */
    Long createdbyId = context.authenticatedUser().getId();
    TicketMasterCommand ticketMasterCommand =
        new TicketMasterCommand(
            ticketId,
            comments,
            status,
            assignedTo,
            createdbyId,
            null,
            problemCode,
            priority,
            resolutionDescription,
            username);
    DocumentCommand documentCommand = null;
    if (fileDetails != null && bodyPart != null) {
      documentCommand =
          new DocumentCommand(
              null,
              null,
              entityType,
              entityId,
              null,
              fileDetails.getFileName(),
              fileSize,
              bodyPart.getMediaType().toString(),
              null,
              null);
    } else {
      documentCommand =
          new DocumentCommand(
              null, null, entityType, entityId, null, null, fileSize, null, null, null);
    }

    Long detailId =
        this.ticketMasterWritePlatformService.upDateTicketDetails(
            ticketMasterCommand, documentCommand, ticketId, inputStream, ticketURL);

    return this.toApiJsonSerializer.serialize(
        CommandProcessingResult.resourceResult(detailId, null));
  }
  @POST
  @Path("/documents")
  @Consumes({MediaType.MULTIPART_FORM_DATA})
  @Produces({MediaType.APPLICATION_JSON})
  public String createUploadFile(
      @HeaderParam("Content-Length") Long fileSize,
      @FormDataParam("file") InputStream inputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetails,
      @FormDataParam("file") FormDataBodyPart bodyPart,
      @FormDataParam("name") String name,
      @FormDataParam("description") String description) {

    FileUtils.validateFileSizeWithinPermissibleRange(
        fileSize, name, ApiConstants.MAX_FILE_UPLOAD_SIZE_IN_MB);

    int i;

    /*DocumentCommand documentCommand = new DocumentCommand(null, null, null, null, name, fileDetails.getFileName(), fileSize,
    bodyPart.getMediaType().toString(), description, null);*/
    try {
      String fileUploadLocation = FileUtils.generateXlsFileDirectory();
      String fileName = fileDetails.getFileName();
      if (!new File(fileUploadLocation).isDirectory()) {
        new File(fileUploadLocation).mkdirs();
      }

      String fileLocation = FileUtils.saveToFileSystem(inputStream, fileUploadLocation, fileName);

      InputStream excelFileToRead = new FileInputStream(fileLocation);

      XSSFWorkbook wb = new XSSFWorkbook(excelFileToRead);

      XSSFSheet sheet = wb.getSheetAt(0);
      XSSFRow row;
      XSSFCell cell;
      String serialno = "0";
      int countno = Integer.parseInt(serialno);
      if (countno == 0) {
        countno = countno + 2;
      } else if (countno == 1) {
        countno = countno + 1;
      }
      System.out.println("Excel Row No is: " + countno);
      Iterator rows = sheet.rowIterator();
      Vector<XSSFCell> v = new Vector<XSSFCell>();
      if (countno > 0) {
        countno = countno - 1;
      }
      while (rows.hasNext()) {

        row = (XSSFRow) rows.next();
        i = row.getRowNum();
        if (i > 0) {
          if (i >= countno) {
            Iterator cells = row.cellIterator();
            while (cells.hasNext()) {

              cell = (XSSFCell) cells.next();

              if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                // System.out.print(cell.getStringCellValue() +
                // " ");
                v.add(cell);
              } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                // System.out.print(cell.getNumericCellValue() +
                // " ");
                v.add(cell);
              } else {
                v.add(cell);
              }
            }
            // ItemDetailsCommand itemdetails=new
            // ItemDetailsCommand(Integer.parseInt(v.elementAt(0).toString()),v.elementAt(1).toString(),Integer.parseInt(v.elementAt(2).toString()),v.elementAt(3).toString(),v.elementAt(4).toString(),v.elementAt(5).toString(),Integer.parseInt(v.elementAt(6).toString()),Integer.parseInt(v.elementAt(7).toString()),Integer.parseInt(v.elementAt(8).toString()),v.elementAt(9).toString(),null);
            List<ItemDetailsCommand> ItemDetailsCommandList = new ArrayList<ItemDetailsCommand>();
            /*for(i=0;i<10;i++)
            {*/
            /* Iterator iterator = v.iterator();
             while(iterator.hasNext())
             {

            	System.out.println(v.elementAt(0).toString());
            	System.out.println( v.elementAt(1).toString());
            	System.out.println( v.elementAt(2).toString());
            	System.out.println( v.elementAt(3).toString());
            	System.out.println( v.elementAt(4).toString());
            	System.out.println( v.elementAt(5).toString());
            	System.out.println( v.elementAt(6).toString());
            	System.out.println( v.elementAt(7).toString());
            	System.out.println( v.elementAt(8).toString());
            	System.out.println( v.elementAt(9).toString());



            	// itemDetails = ItemDetails.create(command.getItemMasterId(), command.getSerialNumber(), command.getGrnId(),command.getProvisioningSerialNumber(), command.getQuality(),command.getStatus(), command.getOfficeId(), command.getClientId(), command.getWarranty(), command.getRemark());
            	//ItemDetailsCommand itemdetails=new ItemDetailsCommand(Long.parseLong(v.elementAt(0).toString()), v.elementAt(1).toString(), Long.parseLong(v.elementAt(2).toString()), v.elementAt(3).toString(), v.elementAt(4).toString(), v.elementAt(5).toString(), Long.parseLong(v.elementAt(6).toString()), Long.parseLong(v.elementAt(7).toString()), Long.parseLong(v.elementAt(8).toString()), v.elementAt(9).toString());
            	//ItemDetailsCommand itemdetails=new ItemDetailsCommand(Long.parseLong(v.elementAt(0).toString()), v.elementAt(1).toString(), Long.parseLong(v.elementAt(2).toString()), v.elementAt(3).toString(), v.elementAt(4).toString(), v.elementAt(5).toString(), Long.parseLong(v.elementAt(6).toString()), Long.parseLong(v.elementAt(7).toString()), Long.parseLong(v.elementAt(8).toString()), v.elementAt(9).toString());
            	//CommandProcessingResult id = this.itemDetailsWritePlatformService.addItem(itemdetails);
            	//ItemDetailsCommandList.add(itemdetails);

            	ItemDetailsCommand itemDetailsCommand=new ItemDetailsCommand();
            	new Double(v.elementAt(0).toString()).longValue();

            	itemDetailsCommand.setItemMasterId(new Double(v.elementAt(0).toString()).longValue());

            	itemDetailsCommand.setSerialNumber(v.elementAt(1).toString());
            	itemDetailsCommand.setGrnId(new Double(v.elementAt(2).toString()).longValue());
            	itemDetailsCommand.setProvisioningSerialNumber( v.elementAt(3).toString());
            	itemDetailsCommand.setQuality( v.elementAt(4).toString());
            	itemDetailsCommand.setRemark(v.elementAt(9).toString());
            	itemDetailsCommand.setStatus(v.elementAt(5).toString());
            	itemDetailsCommand.setOfficeId(new Double(v.elementAt(6).toString()).longValue());
            	itemDetailsCommand.setClientId(new Double(v.elementAt(7).toString()).longValue());
            	itemDetailsCommand.setWarranty(new Double(v.elementAt(8).toString()).longValue());
            	ItemDetailsCommandList.add(itemDetailsCommand);

            	CommandProcessingResult id = this.itemDetailsWritePlatformService.addItem(itemDetailsCommand);

            }
            */

          }
        }
      }
      Iterator iterator = v.iterator();
      while (iterator.hasNext()) {

        System.out.println(v.elementAt(0).toString());
        System.out.println(v.elementAt(1).toString());
        System.out.println(v.elementAt(2).toString());
        System.out.println(v.elementAt(3).toString());
        System.out.println(v.elementAt(4).toString());
        System.out.println(v.elementAt(5).toString());
        System.out.println(v.elementAt(6).toString());
        System.out.println(v.elementAt(7).toString());
        System.out.println(v.elementAt(8).toString());
        System.out.println(v.elementAt(9).toString());

        // itemDetails = ItemDetails.create(command.getItemMasterId(), command.getSerialNumber(),
        // command.getGrnId(),command.getProvisioningSerialNumber(),
        // command.getQuality(),command.getStatus(), command.getOfficeId(), command.getClientId(),
        // command.getWarranty(), command.getRemark());
        // ItemDetailsCommand itemdetails=new
        // ItemDetailsCommand(Long.parseLong(v.elementAt(0).toString()), v.elementAt(1).toString(),
        // Long.parseLong(v.elementAt(2).toString()), v.elementAt(3).toString(),
        // v.elementAt(4).toString(), v.elementAt(5).toString(),
        // Long.parseLong(v.elementAt(6).toString()), Long.parseLong(v.elementAt(7).toString()),
        // Long.parseLong(v.elementAt(8).toString()), v.elementAt(9).toString());
        // ItemDetailsCommand itemdetails=new
        // ItemDetailsCommand(Long.parseLong(v.elementAt(0).toString()), v.elementAt(1).toString(),
        // Long.parseLong(v.elementAt(2).toString()), v.elementAt(3).toString(),
        // v.elementAt(4).toString(), v.elementAt(5).toString(),
        // Long.parseLong(v.elementAt(6).toString()), Long.parseLong(v.elementAt(7).toString()),
        // Long.parseLong(v.elementAt(8).toString()), v.elementAt(9).toString());
        // CommandProcessingResult id = this.itemDetailsWritePlatformService.addItem(itemdetails);
        // ItemDetailsCommandList.add(itemdetails);

        ItemDetailsCommand itemDetailsCommand = new ItemDetailsCommand();
        new Double(v.elementAt(0).toString()).longValue();

        itemDetailsCommand.setItemMasterId(new Double(v.elementAt(0).toString()).longValue());

        itemDetailsCommand.setSerialNumber(v.elementAt(1).toString());
        itemDetailsCommand.setGrnId(new Double(v.elementAt(2).toString()).longValue());
        itemDetailsCommand.setProvisioningSerialNumber(v.elementAt(3).toString());
        itemDetailsCommand.setQuality(v.elementAt(4).toString());
        itemDetailsCommand.setRemark(v.elementAt(9).toString());
        itemDetailsCommand.setStatus(v.elementAt(5).toString());
        itemDetailsCommand.setOfficeId(new Double(v.elementAt(6).toString()).longValue());
        itemDetailsCommand.setClientId(new Double(v.elementAt(7).toString()).longValue());
        itemDetailsCommand.setWarranty(new Double(v.elementAt(8).toString()).longValue());
        // ItemDetailsCommandList.add(itemDetailsCommand);

        CommandProcessingResult id =
            this.itemDetailsWritePlatformService.addItem(itemDetailsCommand);
      }

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

    /**
     * TODO: also need to have a backup and stop reading from stream after max size is reached to
     * protect against malicious clients
     */

    /** TODO: need to extract the actual file type and determine if they are permissable */

    /// ItemDetailsCommand itemDetailsCommand=new ItemDetailsCommand()
    // DocumentCommand documentCommand = new DocumentCommand(null, null, entityType, entityId, name,
    // fileDetails.getFileName(), fileSize,
    ///     bodyPart.getMediaType().toString(), description, null);

    // Long documentId = this.documentWritePlatformService.createDocument(documentCommand,
    // inputStream);

    // return this.toApiJsonSerializer.serialize(CommandProcessingResult.resourceResult(1, null));
    return null;
  }