public static void writeByteArrayToFile(File file, byte[] data) {
   try {
     FileUtils.writeByteArrayToFile(file, data);
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
 @CrossOrigin(origins = "*")
 @RequestMapping(value = "/sendEmailFromTo")
 @ResponseStatus(HttpStatus.OK)
 public String sendEmail(String fromAddress, String toAddress, String uuid) throws IOException {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
   Message message =
       new Message(
           fromAddress,
           toAddress,
           "Your mazda	routes exported at " + sdf.format(new Date()),
           "These are your exported cached routes from Mazda");
   byte[] data = createZip(uuid);
   Attachment attachment = new Attachment("routes.zip", data);
   message.setAttachments(attachment);
   try {
     mailService.send(message);
     log.info("Routes sent to \"{}\"", toAddress);
   } catch (CallNotFoundException ex) {
     log.error("Cannot send email: {}", ExceptionUtils.getRootCauseMessage(ex));
     File file = new File("routes_" + toAddress + "_" + System.currentTimeMillis() + ".zip");
     FileUtils.writeByteArrayToFile(file, data);
     log.info("Routes save to file: {}", file.getAbsolutePath());
   } finally {
     routeRepository.clearRoutes(uuid);
   }
   return "{}";
 }
  /*
   * (non-Javadoc)
   *
   * @see com.template.service.common.workflow.IProcessDefinitionService#
   * exportProcessPic(org.activiti.engine.repository.ProcessDefinition,
   * java.lang.String)
   */
  @Override
  public boolean exportProcessPic(String deploymentId) {

    boolean flag = true;
    ProcessDefinition processDefinition =
        repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();

    String diagramResourceName = processDefinition.getDiagramResourceName();
    try {
      diagramResourceName = processDefinition.getDiagramResourceName();
      InputStream imageStream =
          repositoryService.getResourceAsStream(
              processDefinition.getDeploymentId(), diagramResourceName);

      byte[] b = new byte[imageStream.available()];
      imageStream.read(b, 0, b.length);

      File file =
          new File(
              workFlowPicPath
                  + File.separator
                  + processDefinition.getKey()
                  + "."
                  + FilenameUtils.getExtension(diagramResourceName));
      FileUtils.writeByteArrayToFile(file, b);
    } catch (IOException e) {
      flag = false;
    }
    return flag;
  }
  @Test
  public void testPng() throws Exception {
    String path =
        ProcessDefManagerTest.class.getClassLoader().getResource("graphsub.xml").getPath();
    String value = FileUtils.readFileToString(new File(path));
    mxCodec codec = new mxCodec();
    org.w3c.dom.Document doc = mxXmlUtils.parseXml(value);
    codec = new mxCodec(doc);
    mxGraphModel model = (mxGraphModel) codec.decode(doc.getDocumentElement());
    mxGraph graph = new mxGraph();
    graph.setModel(model);
    BufferedImage image =
        mxCellRenderer.createBufferedImage(graph, null, 1, Color.WHITE, true, null);
    byte[] ret = null;
    ByteArrayOutputStream outputStream = null;
    try {
      outputStream = new ByteArrayOutputStream();
      ImageIO.write(image, "png", outputStream);
      ret = outputStream.toByteArray();
      FileUtils.writeByteArrayToFile(new File("/Users/lihao/Downloads/graph.png"), ret);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #5
0
 public static void writeByteArrayToFile(byte[] data, File file) {
   try {
     FileUtils.writeByteArrayToFile(file, data);
   } catch (IOException ioe) {
     throw new CLIException(REASON_IO_ERROR, ioe);
   }
 }
  private String saveUploadFile(MultipartFile file, String targetDir, String targetFilename) {
    if (file == null) {
      return null;
    }

    File dir = new File(targetDir);
    if (!dir.exists()) {
      log.info("dir {} not exists.create dir now.", dir.getAbsolutePath());
      dir.mkdirs();
    }
    try {
      String fileName = file.getOriginalFilename();
      log.debug("fileName:{}", fileName);
      InputStream is = file.getInputStream();
      try {
        byte[] fileBytes = IOUtils.toByteArray(is);
        FileUtils.writeByteArrayToFile(new File(targetDir + targetFilename), fileBytes);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
      } finally {
        IOUtils.closeQuietly(is);
      }
      return targetDir + targetFilename;
    } catch (IOException e) {
      log.error(e.getMessage(), e);
      return null;
    }
  }
Exemple #7
0
  /* (non-Javadoc)
   * @see sernet.verinice.interfaces.ICommand#execute()
   */
  @Override
  public void execute() {
    try {
      createFields();
      xmlData = export();
      xmlDataRiskAnalysis = exportRiskAnalyses();

      if (isVeriniceArchive()) {
        result = createVeriniceArchive();
      } else {
        result = xmlData;
      }
      if (filePath != null) {
        FileUtils.writeByteArrayToFile(new File(filePath), result);
        result = null;
      }
    } catch (final RuntimeException re) {
      getLog().error("Runtime exception while exporting", re);
      throw re;
    } catch (final Exception e) {
      getLog().error("Exception while exporting", e);
      throw new RuntimeCommandException("Exception while exporting", e);
    } finally {
      getCache().removeAll();
    }
  }
 public static void testcaV3() throws Exception {
   KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
   kpg.initialize(2048);
   KeyPair keyPair = kpg.generateKeyPair();
   X509Certificate cer = buildCARootCertV3(keyPair);
   FileUtils.writeByteArrayToFile(new File("d:\\caV3.cer"), cer.getEncoded());
   System.out.println(cer);
 }
  private void createNewPwdFile(EncryptedPassword passwordForEncoding, File pwdFile)
      throws Exception {
    if (pwdFile.exists()) {
      pwdFile.delete();
    }

    byte[] encr = encodeService.encrypt(passwordForEncoding, passwordForEncoding.getPassword());
    FileUtils.writeByteArrayToFile(pwdFile, encr);
  }
 private String writeImage(String filename, PdfImageObject image) {
   File file = getFile(filename);
   try {
     FileUtils.writeByteArrayToFile(file, image.getImageAsBytes());
   } catch (IOException e) {
     e.printStackTrace();
     return null;
   }
   return file.getAbsolutePath();
 }
 @Override
 public String saveImage(byte[] imageBytes, String fileExtensionWithoutDot) throws IOException {
   final String firstPathPart = (random.nextInt(899999999) + 1000000) + "";
   final String secondPathPart = (random.nextInt(899999999) + 1000000) + "";
   final String fileName = random.nextInt(1000) + "." + fileExtensionWithoutDot;
   final String resource =
       firstPathPart + File.separator + secondPathPart + File.separator + fileName;
   final File file = new File(basePath, resource);
   FileUtils.writeByteArrayToFile(file, imageBytes);
   return resource;
 }
 @Override
 @Transactional
 public ImportManifest saveImportFileAndExtractManifest(byte[] bytes) {
   try {
     ImportManifest manifest = extractManifest(bytes);
     File file = createImportFile();
     FileUtils.writeByteArrayToFile(file, bytes);
     manifest.setImportId(getImportId(file));
     return manifest;
   } catch (IOException e) {
     throw new ImportExportException("Cannot save import file", e);
   }
 }
  void processBalloonImage(DaisyProtocolMessage mob) {
    Log.d("PROTOCOL", "processBalloonImage");
    final BalloonImage bi = mob.getBalloonImage();
    String imagePath = DaisyProtocolRoutinesBalloon.getImagePath(data, bi.getSequenceNumber());
    byte[] previewData = bi.getImageData().toByteArray();
    try {
      FileUtils.writeByteArrayToFile(new File(imagePath), previewData);
      FileUtils.writeByteArrayToFile(
          new File(imagePath + ".pb"), bi.getBalloonStats().toByteArray());
    } catch (IOException e) {
      e.printStackTrace();
    }

    Handler h = new Handler(ctx.getMainLooper());
    h.post(
        new Runnable() {
          @Override
          public void run() {
            data.bus.post(bi);
            data.bus.post(bi.getBalloonStats());
          }
        });
  }
  /**
   * create local topology files /local-dir/nimbus/topologyId/stormjar.jar
   * /local-dir/nimbus/topologyId/stormcode.ser /local-dir/nimbus/topologyId/stormconf.ser
   *
   * @param conf
   * @param topologyId
   * @param tmpJarLocation
   * @param stormConf
   * @param topology
   * @throws IOException
   */
  private void setupStormCode(
      Map<Object, Object> conf,
      String topologyId,
      String tmpJarLocation,
      Map<Object, Object> stormConf,
      StormTopology topology)
      throws IOException {
    // local-dir/nimbus/stormdist/topologyId
    String stormroot = StormConfig.masterStormdistRoot(conf, topologyId);

    FileUtils.forceMkdir(new File(stormroot));
    FileUtils.cleanDirectory(new File(stormroot));

    // copy jar to /local-dir/nimbus/topologyId/stormjar.jar
    setupJar(conf, tmpJarLocation, stormroot);

    // serialize to file /local-dir/nimbus/topologyId/stormcode.ser
    FileUtils.writeByteArrayToFile(
        new File(StormConfig.stormcode_path(stormroot)), Utils.serialize(topology));

    // serialize to file /local-dir/nimbus/topologyId/stormconf.ser
    FileUtils.writeByteArrayToFile(
        new File(StormConfig.sotrmconf_path(stormroot)), Utils.serialize(stormConf));
  }
  public static void testcaV1() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair keyPair = kpg.generateKeyPair();
    X509Certificate cer = buildCARootCertV1(keyPair);
    System.out.println(cer);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1cer.cer"), cer.getEncoded());
    // 生成CA证书
    byte[] publicBase64 =
        org.apache.commons.codec.binary.Base64.encodeBase64(cer.getEncoded(), true);
    String publicStr = new String(publicBase64, "UTF-8");
    publicStr = PUBLIC_PREFIX + publicStr + PUBLIC_SUFFIX;
    System.out.println(publicStr);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1cer.pem"), publicStr.getBytes("UTF-8"));

    // 生成CA私钥
    byte[] privateBase64 =
        org.apache.commons.codec.binary.Base64.encodeBase64(
            keyPair.getPrivate().getEncoded(), true);
    String privateStr = new String(privateBase64, "UTF-8");
    privateStr = PRIVATE_PREFIX + privateStr + PRIVATE_SUFFIX;
    System.out.println(privateStr);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1key.pem"), privateStr.getBytes("UTF-8"));
  }
 public User registerUser(User user) throws IOException {
   UUID filename = UUID.randomUUID();
   String filePath =
       System.getProperty("geofertas.images.dir").toString().concat(filename.toString());
   File newFile = new File(filePath);
   FileUtils.writeByteArrayToFile(newFile, user.getPicture());
   user.setPicturePath(filename.toString());
   Object outcome = userDAO.registerUser(user);
   if (outcome != null) {
     User outcomeUser = (User) outcome;
     File file = new File(filePath);
     outcomeUser.setPicture(FileUtils.readFileToByteArray(file));
     return user;
   }
   return null;
 }
  /** 导出图片文件到硬盘 */
  public List<String> exportDiagrams(String exportDir) throws IOException {
    List<String> files = new ArrayList<String>();
    List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();

    for (ProcessDefinition processDefinition : list) {
      String diagramResourceName = processDefinition.getDiagramResourceName();
      String key = processDefinition.getKey();
      int version = processDefinition.getVersion();
      String diagramPath = "";

      InputStream resourceAsStream =
          repositoryService.getResourceAsStream(
              processDefinition.getDeploymentId(), diagramResourceName);
      byte[] b = new byte[resourceAsStream.available()];

      @SuppressWarnings("unused")
      int len = -1;
      resourceAsStream.read(b, 0, b.length);

      // create file if not exist
      String diagramDir = exportDir + "/" + key + "/" + version;
      File diagramDirFile = new File(diagramDir);
      if (!diagramDirFile.exists()) {
        diagramDirFile.mkdirs();
      }
      diagramPath = diagramDir + "/" + diagramResourceName;
      File file = new File(diagramPath);

      // 文件存在退出
      if (file.exists()) {
        // 文件大小相同时直接返回否则重新创建文件(可能损坏)
        logger.debug("diagram exist, ignore... : {}", diagramPath);

        files.add(diagramPath);
      } else {
        file.createNewFile();
        logger.debug("export diagram to : {}", diagramPath);

        // wirte bytes to file
        FileUtils.writeByteArrayToFile(file, b, true);

        files.add(diagramPath);
      }
    }

    return files;
  }
  public static void projectRemote(String url) {
    String dir = url.replace("/", "_").replace(':', '_');
    File projectDir = new File(StaticUtils.getConfigDir() + "/remoteProjects/" + dir);
    File projectFile = new File(projectDir, OConsts.FILE_PROJECT);

    byte[] data;
    try {
      projectDir.mkdirs();
      data = WikiGet.getURLasByteArray(url);
      FileUtils.writeByteArrayToFile(projectFile, data);
    } catch (Exception ex) {
      Log.logErrorRB(ex, "TEAM_REMOTE_RETRIEVE_ERROR", url);
      Core.getMainWindow().displayErrorRB(ex, "TEAM_REMOTE_RETRIEVE_ERROR", url);
      return;
    }

    projectOpen(projectDir);
  }
Exemple #19
0
 public String saveUser(
     HttpServletRequest request,
     HttpServletResponse response,
     UserInfo userInfo,
     BindingResult result,
     @RequestParam(value = "image", required = false) MultipartFile image)
     throws IOException {
   if (!image.isEmpty()) {
     if (image.getContentType().equals("image/jpeg")) {
       String realPath = request.getSession().getServletContext().getRealPath("/upload");
       File file = new File(realPath + "/" + image.getOriginalFilename());
       FileUtils.writeByteArrayToFile(file, image.getBytes());
     }
   }
   if (!result.hasErrors()) {
     return "front/index";
   } else {
     return "front/index";
   }
 }
 @Override
 public void populateJenkinsHome(byte[] _template, boolean clean) throws IOException {
     try {
         if (clean && tempDir.isDirectory()) {
             FileUtils.cleanDirectory(tempDir);
         }
         if (!tempDir.isDirectory() && ! tempDir.mkdirs()) {
             throw new IOException("Could not create directory: " + tempDir);
         }
         File template = File.createTempFile("template", ".dat");
         try {
             FileUtils.writeByteArrayToFile(template, _template);
             Expand expand = new Expand();
             expand.setSrc(template);
             expand.setOverwrite(true);
             expand.setDest(tempDir);
             expand.execute();
         } finally {
             template.delete();
         }
     } catch (Exception e) {
         throw new IOException(e.getMessage(), e);
     }
 }
  void processBalloonPreview(DaisyProtocolMessage mob) {
    Log.d("PROTOCOL", "processBalloonPreview");
    final BalloonPreview bp = mob.getBalloonPreview();
    String imagePath = DaisyProtocolRoutinesBalloon.getPreviewPath(data, bp.getSequenceNumber());
    byte[] previewData = bp.getPreviewData().toByteArray();
    Log.d("PROTOCOL", "previewData Size = " + previewData.length);
    try {
      Log.i("PROTOCOL", "Trying to save preview " + bp.getSequenceNumber());
      FileUtils.writeByteArrayToFile(new File(imagePath), previewData);
    } catch (IOException e) {
      e.printStackTrace();
    }

    Handler h = new Handler(ctx.getMainLooper());

    h.post(
        new Runnable() {
          @Override
          public void run() {
            data.bus.post(bp);
            data.bus.post(bp.getBalloonStats());
          }
        });
  }
  @Override
  public void onTestFailure(ITestResult result) {
    logEndOfTest(result, "FAILED");
    if (BaseUITestClass.getDRIVER() != null) {
      byte[] scrFile =
          ((TakesScreenshot) BaseUITestClass.getDRIVER()).getScreenshotAs(OutputType.BYTES);
      try {
        String filename =
            OSUtil.getPath(
                "target",
                "surefire-reports",
                "screenshots",
                String.format(
                    "%s.%s.png",
                    result.getTestClass().getRealClass().getSimpleName(), result.getName()));
        FileUtils.writeByteArrayToFile(new File(filename), scrFile);
      } catch (IOException e) {
        logger.info("Saving screenshot FAILED: " + e.getCause());
      }
    }

    logger.info(ExceptionUtils.getStackTrace(result.getThrowable()));
    logLine();
  }
  public Result upload() {
    String databaseName = "";
    System.out.println("upload function call");

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart filePart1 = body.getFile("filePart1");
    String[] searchTag = body.asFormUrlEncoded().get("db");
    String[] uploadDBName = body.asFormUrlEncoded().get("db_upload");

    databaseName = uploadDBName[0];
    System.out.println("FILE SEND!!");
    if (filePart1 != null) {
      // System.out.println("ifin ici");

    }
    File newFile1 = filePart1.getFile();
    InputStream isFile1;
    try {
      isFile1 = new FileInputStream(newFile1);
    } catch (FileNotFoundException e1) {
      isFile1 = null;
    }

    byte[] byteFile1;

    try {
      byteFile1 = IOUtils.toByteArray(isFile1);
    } catch (IOException e2) {
      byteFile1 = null;
    }
    BufferedReader reader;
    String line;
    StringBuilder stringBuilder;
    String ls;
    try {
      reader = new BufferedReader(new FileReader(newFile1));
      line = null;
      stringBuilder = new StringBuilder();
      ls = System.getProperty("line.separator");
    } catch (FileNotFoundException e1) {
      reader = null;
      line = null;
      stringBuilder = null;
      ls = null;
    }
    // System.out.println(reader);
    String[] parts;
    try {
      while ((line = reader.readLine()) != null) {
        String[] a_line_list = line.split("\t");
        String tweet = a_line_list[2];
        String id = a_line_list[0];
        String owner = a_line_list[1];
        String label = "-2";
        DataAccess.addDocument(databaseName, "tweets_unlabelled", id, owner, tweet, label, "0");
      }
    } catch (IOException e) {

    }
    try {
      FileUtils.writeByteArrayToFile(newFile1, byteFile1);
      isFile1.close();
    } catch (IOException e3) {

    }
    try {
      Thread.sleep(1000); // thread sleep for concurrent operations on ES
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    TweetDTO tweet = DataAccess.getNextTweet(databaseName);
    System.out.println(tweet.getId() + " " + tweet.getOwner() + " " + tweet.getLabel());
    return ok(labelling.render(tweet, databaseName));
  }
  public static void testGenP12() throws Exception {

    String rootCerBase64 =
        "MIIDvTCCAqWgAwIBAgIEEioP6zANBgkqhkiG9w0BAQsFADCBjjELMAkGA1UEBhMC"
            + "Q04xETAPBgNVBAgTCHNoYW5naGFpMREwDwYDVQQHEwhzaGFuZ2hhaTEzMDEGA1UE"
            + "Cgwq5LiK5rW36YeR6bm/6YeR6J6N5L+h5oGv5pyN5Yqh5pyJ6ZmQ5YWs5Y+4MQsw"
            + "CQYDVQQLEwJJVDEXMBUGA1UEAxMOb3Blbi5qbGZleC5jb20wHhcNMTQwODIxMDM0"
            + "NTQ5WhcNMjQwODE4MDM0NTQ5WjCBjjELMAkGA1UEBhMCQ04xETAPBgNVBAgTCHNo"
            + "YW5naGFpMREwDwYDVQQHEwhzaGFuZ2hhaTEzMDEGA1UECgwq5LiK5rW36YeR6bm/"
            + "6YeR6J6N5L+h5oGv5pyN5Yqh5pyJ6ZmQ5YWs5Y+4MQswCQYDVQQLEwJJVDEXMBUG"
            + "A1UEAxMOb3Blbi5qbGZleC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK"
            + "AoIBAQCQ4q4Yh8EPHbAP+BMiystXOEV56OE+IUwxSS7fRZ3ZrIEPImpnCiAe1txZ"
            + "vk0Lgv8ZWqrj4ErOT5FoOWfQW6Vva1DOXknCzFbypJMjqVnIS1/OwB64sYg4naLc"
            + "mM95GAHtEv9qxIWLbPhoLShz54znRNbM7mZJyT4BwLhKuKmfdo3UEuXvcoUFLN2l"
            + "f2wiTNmgMgpxcnCsWAx2nJaonPGCVXeQu0PXCVmCTyUUCWdT7P1io5yEpuRP/Dac"
            + "//g7Em8rkulgeO7e3gnEbrgrczsr2H1KJLTBjQmyWeWZg7LRYML6oHODrrDb0x++"
            + "yDT01p2BJHlvw/UzJq3I/CCci0lFAgMBAAGjITAfMB0GA1UdDgQWBBS1Lo57VqvU"
            + "BnfyJu51JO9csLJenjANBgkqhkiG9w0BAQsFAAOCAQEACcfPaVl5PIkBZ6cXyHuj"
            + "rJZkZH7Koqhx12DNeCoohdQkRda/gWeHVPsO7snK63sFhoY08OGVgvTRhgzwSBxJ"
            + "cx9GkCyojfHo5xZoOlSQ01PygyScd42DlseNiwXZGBfoxacLEYkIP6OXrDa+wNAP"
            + "gHnLI+37tzkafoPT0xoV/E9thvUUKX1jSIL5UCoGuso6FWLiZgDxD8wKgd22FcYo"
            + "T7B7DHG4R+0rgav81J9xjgOR3ayvNrb86iVvVBmrIiM7Gc2hf5PMiiAOaISST2cJ"
            + "x90X7TUA/f0qrYKveTvkRT77nLfzHV1a+PTS7PwkCXUt/NRm4VwseyGIgQ4FXH6W"
            + "zw==";

    // 解析root CA 证书
    X509Certificate rootcaCertificate =
        CertificateCoder.getX509Certificate(Base64.decodeBase64(rootCerBase64));
    // 解析root CA 私钥
    String rootcaDer = FileUtils.readFileToString(new File("d:\\rootcakey.pem"), "UTF-8");
    PrivateKey rootcaPrivateKey = PKCSCertificateCoder.getPrivateKeyFromPem(rootcaDer, "");
    System.out.println(rootcaPrivateKey);

    // 1.生成用户密钥对
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();

    // 2.生成用户证书请求
    PKCS10CertificationRequest p10 = genPKCS10(kp);
    SubjectPublicKeyInfo subPublicKeyInfo = p10.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subPublicKeyInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    // 3.生成用户证书
    X509Certificate clientCertificate =
        buildEndEntityCert(publicKey, rootcaPrivateKey, rootcaCertificate);
    FileUtils.writeByteArrayToFile(new File("d:\\client.cer"), clientCertificate.getEncoded());

    // 4.生成用户p12文件
    storeP12(
        kp,
        new X509Certificate[] {clientCertificate, rootcaCertificate},
        "d:\\client.p12",
        "123456");

    FileOutputStream fos = new FileOutputStream(new File("d:\\client1.p12"));
    X509Certificate[] chain =
        new X509Certificate[] {rootcaCertificate, clientCertificate, clientCertificate};
    genPKCS12File(fos, kp.getPrivate(), chain);
  }
 public static void writeFile(File file, byte[] data, boolean append) throws IOException {
   FileUtils.writeByteArrayToFile(file, data, append);
 }
  public void upload(FileUploadEvent event) {
    UUID uuidX = UUID.randomUUID();
    String nameTemp = uuidX.toString().replace("-", "_");
    ServletContext servletContext =
        (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

    nameFile = nameTemp;

    if (fisica == null && juridica == null) {
      String path =
          servletContext.getRealPath("")
              + "resources/cliente/"
              + ControleUsuarioBean.getCliente().toLowerCase()
              + "/imagens/"
              + savePath
              + "/"
              + nameTemp
              + ".png";
      File file = new File(path);
      try {
        FileUtils.writeByteArrayToFile(file, event.getFile().getContents());
      } catch (IOException e) {
        e.getMessage();
      }
    } else {
      if (!Diretorio.criar(
          "imagens/pessoa", true)) { // PASTA ex. resources/cliente/sindical/imagens/pessoa
        return;
      }

      if (fisica != null) {
        String path =
            servletContext.getRealPath("")
                + "resources/cliente/"
                + ControleUsuarioBean.getCliente().toLowerCase()
                + "/imagens/pessoa/"
                + fisica.getPessoa().getId()
                + "/"
                + nameTemp
                + ".png";
        File file = new File(path);
        try {
          FileUtils.writeByteArrayToFile(file, event.getFile().getContents());
        } catch (IOException e) {
          e.getMessage();
        }

        // CASO QUEIRA REMOVER A FOTO ANTERIOR
        //                    File fotoAntiga = new
        // File(servletContext.getRealPath("")+"resources/cliente/" +
        // ControleUsuarioBean.getCliente().toLowerCase() + "/imagens/pessoa/" + pessoa.getId() +
        // "/" + fisica.getFoto() + ".png");
        //                    if (fotoAntiga.exists()) {
        //                        FileUtils.deleteQuietly(fotoAntiga);
        //                    }
        fisica.setFoto(nameTemp);
        new Dao().update(fisica, true);
      } else {
        String path =
            servletContext.getRealPath("")
                + "resources/cliente/"
                + ControleUsuarioBean.getCliente().toLowerCase()
                + "/imagens/pessoa/"
                + juridica.getPessoa().getId()
                + "/"
                + nameTemp
                + ".png";
        File file = new File(path);
        try {
          FileUtils.writeByteArrayToFile(file, event.getFile().getContents());
        } catch (IOException e) {
          e.getMessage();
        }

        // CASO QUEIRA REMOVER A FOTO ANTERIOR
        //                    File fotoAntiga = new
        // File(servletContext.getRealPath("")+"resources/cliente/" +
        // ControleUsuarioBean.getCliente().toLowerCase() + "/imagens/pessoa/" + pessoa.getId() +
        // "/" + juridica.getFoto() + ".png");
        //                    if (fotoAntiga.exists()) {
        //                        FileUtils.deleteQuietly(fotoAntiga);
        //                    }
        juridica.setFoto(nameTemp);
        new Dao().update(juridica, true);
      }
    }

    PF.closeDialog("dlg_photo_upload");
  }
Exemple #27
0
 /**
  * With this file on board.
  *
  * @param name File name related to basedir
  * @param bytes File content to write
  * @return This object
  * @throws IOException If some IO problem
  */
 public Environment.Mock withFile(final String name, final byte[] bytes) throws IOException {
   final File file = new File(this.basedir, name);
   FileUtils.writeByteArrayToFile(file, bytes);
   return this;
 }
  public static PlateInfo parse(byte[] contents) {
    IoBuffer b = IoBuffer.allocate(contents.length);
    b.put(contents);
    b.flip();
    b.order(ByteOrder.LITTLE_ENDIAN);
    try {
      FileUtils.writeByteArrayToFile(new File("c:/dump.dat"), b.array());
    } catch (IOException e2) {
      // TODO Auto-generated catch block
      e2.printStackTrace();
    }

    long nAppType = b.getUnsignedInt(); // 4
    long nPeccancyFlag = b.getUnsignedInt(); // 4
    long dwPacketIndex = b.getUnsignedInt(); // 4
    byte[] szCarPlate = new byte[16]; // 16
    b.get(szCarPlate); // 牌照号码
    long dwCarPlateColor = b.getUnsignedInt(); // 4
    long dwCredit = b.getUnsignedInt(); // 4
    System.out.println("dwCredit = " + dwCredit);
    long dwPlateTop = b.getUnsignedInt(); // 4
    long dwPlateLeft = b.getUnsignedInt(); // 4
    long dwPlateWidth = b.getUnsignedInt(); // 4
    long dwPlateHeight = b.getUnsignedInt(); // 4
    byte[] szVehicleLogo = new byte[16]; // 车标 //16
    b.get(szVehicleLogo);
    long dwVehicleLength = b.getUnsignedInt(); // 4
    long dwRedLightSTime = b.getUnsignedInt(); // 4
    long dwCaptureTime = b.getUnsignedInt(); // 4
    long dwRedLightETime = b.getUnsignedInt(); // 4
    byte[] szPlaceID = new byte[8]; // 地点编号 //8
    b.get(szPlaceID);
    long dwTravelTime = b.getUnsignedInt(); // 4
    long dwSpeed = b.getUnsignedInt(); // 4
    byte[] szReserved = new byte[16]; // 保留 //16
    b.get(szReserved);
    long dwMediaType = b.getUnsignedInt(); // 4
    long dwImageCount = b.getUnsignedInt(); // 4

    // 取图片长度
    long imageLengths[] = new long[(int) dwImageCount];
    for (int i = 0; i < dwImageCount; i++) {
      imageLengths[i] = b.getUnsignedInt();
    }

    PlateInfo info = new PlateInfo();

    // 取图片数据
    List<byte[]> imageList = new ArrayList<byte[]>();
    for (int i = 0; i < dwImageCount; i++) {
      /*if(i==0){
      	byte[] image1Bytes = new byte[(int) imageLengths[i]];
      	b.get(image1Bytes);
      	info.setImage1(image1Bytes);
      }else if(i==1){
      	byte[] image2Bytes = new byte[(int)imageLengths[i]];
      	b.get(image2Bytes);
      	info.setImage2(image2Bytes);
      }*/
      byte[] imageBytes = new byte[(int) imageLengths[i]];
      b.get(imageBytes);
      imageList.add(imageBytes);
    }
    info.setImages(imageList);

    try {
      String carNo = new String(szCarPlate, "GBK").trim();
      info.setCarNo(carNo);
      info.setCarType(dwCarPlateColor + "");

    } catch (Exception e) {
      e.printStackTrace();
    }
    return info;
  }
  public static void main(String[] args) {
    String contextFile = args[0];
    String filter = args[1];
    String fileToProcess = args[2];
    String outputDir = args[3];

    try {
      // Load file into map.
      Map fileMap = new HashMap();
      File fileref = new File(fileToProcess);

      if (!fileref.exists()) throw new Exception("File/Directory does not exist...");

      if (fileref.isDirectory()) {
        File[] filesToProcess = fileref.listFiles();
        for (int i = 0; i < filesToProcess.length; i++) {
          File fileInDir = filesToProcess[i];
          byte[] data = FileUtils.readFileToByteArray(fileInDir);
          DropBoxRetrieverFile file = new DropBoxRetrieverFile(fileInDir.getName(), data);
          fileMap.put("TestFile" + fileInDir.getName(), file);
        }

      } else {
        byte[] data = FileUtils.readFileToByteArray(fileref);
        DropBoxRetrieverFile file = new DropBoxRetrieverFile(fileref.getName(), data);
        fileMap.put("TestFile", file);
      }

      // Load context
      final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(contextFile);
      final List ff = (List) ctx.getBean(filter);

      Iterator itf = ff.iterator();

      while (itf.hasNext()) {
        FileFilter ffs = (FileFilter) itf.next();
        fileMap = ffs.process(fileMap);
      }

      // Run the filter
      Map returnFile = fileMap;

      // Output the result.
      m_logger.info("Outputting files");

      File outputDirectory = new File(outputDir);
      if (!outputDirectory.exists()) outputDirectory.mkdir();

      Iterator it = returnFile.keySet().iterator();
      while (it.hasNext()) {
        String fileKey = (String) it.next();
        DropBoxRetrieverFile rfile = (DropBoxRetrieverFile) returnFile.get(fileKey);
        String filename = rfile.getFilename();
        File fileToWrite = new File(outputDir + File.separator + filename);
        FileUtils.writeByteArrayToFile(fileToWrite, rfile.getFileData());
        m_logger.info("File outputted as [" + filename + "] to [" + outputDir + "]");
      }

      m_logger.info("Test Finished");
    } catch (Exception e) {
      m_logger.error("Filter test failure [" + e.getMessage() + "]", e);
    }
  }
 @Override
 public void storeFile(String path, byte[] content) throws IOException {
   FileUtils.writeByteArrayToFile(new File(path), content);
 }