Ejemplo n.º 1
0
  public void processInDirectory() {
    //
    // распакуем все файлы из каталага in
    //
    final int BUFFER_SIZE = 4096;
    SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    final String sessionDate = df.format(new Date());
    //
    // ищем файлы с ответом
    logger.info("Обрабатываем входной каталог " + ABS_INPUT_DIR);
    try {
      File[] directoryList =
          (new File(ABS_INPUT_DIR))
              .listFiles(
                  pathname -> !pathname.isDirectory() && pathname.getName().endsWith(".zip"));
      //
      // распаковываем каждый zip
      //
      for (File curFile : directoryList) {
        logger.info("Распаковываем " + curFile.getName());
        //
        // открываем архив
        //
        FileInputStream fis = new FileInputStream(curFile);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
          //
          // пропускаем директории, т.к. их быть не должно
          //
          if (zipEntry.isDirectory()) continue;
          //
          // из архива извлекаем только xml !!!
          //
          if (zipEntry.getName().endsWith(".xml")) {
            File unzippedFile = new File(ABS_INPUT_DIR + "/" + zipEntry.getName());
            logger.info("Извлекаем файл " + zipEntry.getName());
            FileOutputStream fos = new FileOutputStream(unzippedFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int count = 0;
            while ((count = zis.read(buffer)) > 0) {
              fos.write(buffer, 0, count);
            }
            fos.close();
          }
          zis.closeEntry();
        }
        zis.close();
        fis.close();
        Files.move(
            curFile.toPath(),
            Paths.get(ABS_ARCH_IN_DIR + "/" + sessionDate + "-" + curFile.getName()));
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      e.printStackTrace();
    }

    logger.info("Обработан входной каталог " + ABS_INPUT_DIR);
  }
Ejemplo n.º 2
0
  private void speichern(Path saveName) {
    Properties prop = new Properties();

    if (!quellListModel.isEmpty())
      for (int i = 0; i < quellListModel.getSize(); i++)
        prop.setProperty(
            String.format("quellMenu%d", i),
            quellListModel.getElementAt(i).getValueMember().toString());

    if (!zielListModel.isEmpty())
      for (int i = 0; i < zielListModel.getSize(); i++)
        prop.setProperty(
            String.format("zielMenu%d", i),
            zielListModel.getElementAt(i).getValueMember().toString());

    try {
      FileOutputStream out = new FileOutputStream(saveName.toString());
      prop.store(out, null);
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
  public void downloadFile(String relPath) {
    VOSync.debug("Downloading file from storage: " + relPath);
    Path filePath = FileSystems.getDefault().getPath(startDir.toString(), relPath.substring(1));
    try {
      WatchKey key =
          filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.remove(key);
      key.cancel();

      FileOutputStream outp = new FileOutputStream(filePath.toFile());
      DropboxFileInfo info = api.getFile(relPath, null, outp, null);
      outp.close();

      key = filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.put(key, filePath.getParent());

      MetaHandler.setFile(relPath, filePath.toFile(), info.getMetadata().rev);
    } catch (IOException ex) {
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    } catch (DropboxException ex) {
      ex.printStackTrace();
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    }
  }
  public static void main(String[] args) throws IOException {

    int servPort = Integer.parseInt(args[0]);

    String ksName = "keystore.jks";
    char ksPass[] = "password".toCharArray();
    char ctPass[] = "password".toCharArray();
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(ksName), ksPass);
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, ctPass);
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(kmf.getKeyManagers(), null, null);
      SSLServerSocketFactory ssf = sc.getServerSocketFactory();
      SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(servPort);

      while (true) {
        // Listen for a TCP connection request.
        SSLSocket c = (SSLSocket) s.accept();

        BufferedOutputStream out = new BufferedOutputStream(c.getOutputStream(), 1024);
        BufferedInputStream in = new BufferedInputStream(c.getInputStream(), 1024);

        byte[] byteBuffer = new byte[1024];
        int count = 0;
        while ((byteBuffer[count] = (byte) in.read()) != -2) {
          count++;
        }
        String newFile = new String(byteBuffer, 0, count, "US-ASCII");
        FileOutputStream writer = new FileOutputStream(newFile.trim());
        int buffSize = 0;
        while ((buffSize = in.read(byteBuffer, 0, 1024)) != -1) {
          int index = 0;
          if ((index =
                  (new String(byteBuffer, 0, buffSize, "US-ASCII"))
                      .indexOf("------MagicStringCSE283Miami"))
              == -1) {
            writer.write(byteBuffer, 0, buffSize);
          } else {
            writer.write(byteBuffer, 0, index);
            break;
          }
        }
        writer.flush();
        writer.close();

        ZipOutputStream outZip = new ZipOutputStream(new BufferedOutputStream(out));
        FileInputStream fin = new FileInputStream(newFile.trim());
        BufferedInputStream origin = new BufferedInputStream(fin, 1024);
        ZipEntry entry = new ZipEntry(newFile.trim());
        outZip.putNextEntry(entry);

        byteBuffer = new byte[1024];
        int bytes = 0;
        while ((bytes = origin.read(byteBuffer, 0, 1024)) != -1) {
          outZip.write(byteBuffer, 0, bytes);
        }
        origin.close();
        outZip.flush();
        outZip.close();
        out.flush();
        out.close();
      }
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
Ejemplo n.º 5
0
  //
  // обработка исходящего каталога АБС
  //
  public boolean processOutDirectory() {
    boolean result = true;
    try {

      //
      // читаем control.xml
      //
      File controlFile = new File(ABS_OUTPUT_DIR + "/control.xml");
      if (!controlFile.exists()) {
        logger.error("Нет файла " + controlFile.getName());
        if (new File(ABS_OUTPUT_DIR + "/control.zip").exists()) {
          logger.info("Обнаружен архив " + ABS_OUTPUT_DIR + "/control.zip");
          return true;
        }
        return false;
      }
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document controlDoc = builder.parse(controlFile);
      // готовимся изменять файл
      XPath searchPath = XPathFactory.newInstance().newXPath();

      // ищем каталоги с контейнерами
      File[] directoryList = (new File(ABS_OUTPUT_DIR)).listFiles(p -> p.isDirectory());

      //
      // просматриваем каталоги типа FILES/out/....
      //
      for (int i = 0; i < directoryList.length; i++) {
        //
        // в каталоге должен быть файл data.zip и файлы-вложения
        // файл data.zip нужно подписать и зазиповать
        //
        logger.info("Обрабатываем каталог " + directoryList[i].getAbsolutePath());
        //
        // просматриваем содержимое каталога с контейнером
        //
        File[] currentDir = (directoryList[i]).listFiles(p -> p.isFile());
        //
        // создаем zip-file
        //
        File zip = new File(directoryList[i].getAbsolutePath() + "/data_" + i + ".zip");
        logger.info("Создаем архив " + zip.getAbsolutePath());
        FileOutputStream zipStream = new FileOutputStream(zip);
        ZipOutputStream dataZip = new ZipOutputStream(zipStream);
        for (File curFile : currentDir) {
          if ("data.xml.sig".equals(curFile.getName())) continue;
          appendZipFile(dataZip, curFile);
          //
          // для файла data.zip создаем цифровую подпись и записываем файл с подписью в архив
          //
          if ("data.xml".equals(curFile.getName())) {
            fileSigner.cades(curFile.getAbsolutePath());
            String fName = curFile.getAbsolutePath();
            File signFile = new File(fName.substring(0, fName.length() - 3) + "sign");
            appendZipFile(dataZip, signFile);
            signFile.delete();
          }
          //
          // удаляем файл после включения в архив
          //
          curFile.delete();
        }
        //
        // закрываем архив и его поток
        //
        dataZip.close();
        zipStream.close();
        logger.info("Запись в архив " + zip.getAbsolutePath() + " завершена");
        //
        // вычисляем crc32
        //
        long crc32 = Utils.calculateCRC32(zip);
        long zipSize = zip.length();
        //
        // в файле control.xml ищем соответствующий узел контейнера и меняем его атрибуты
        //
        String xpathQuery = "//Containers[@ReqUID='" + directoryList[i].getName() + "']";
        Node containerNode =
            (Node) searchPath.evaluate(xpathQuery, controlDoc, XPathConstants.NODE);
        if (containerNode == null) {
          logger.error(
              "В файле control.xml  не найдено описание для контейнера "
                  + directoryList[i].getName());
          System.exit(1);
        }
        Element containerElement = (Element) containerNode;
        containerElement.setAttribute("name", zip.getName());
        containerElement.setAttribute("size", zipSize + "");
        containerElement.setAttribute("CRC", crc32 + "");
      }
      // сохраняем control.xml
      DOMSource domSource = new DOMSource(controlDoc);
      StreamResult streamResult = new StreamResult(controlFile);
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.transform(domSource, streamResult);
      transformer.reset();
      //
      // подписываем файл
      //
      fileSigner.cades(controlFile.getAbsolutePath());
      //
      // записываем файл control.xml и подпись в архив
      //
      File zip = new File(ABS_OUTPUT_DIR + "/control.zip");
      logger.info("Создаем архив " + zip.getAbsolutePath());
      FileOutputStream zipStream = new FileOutputStream(zip);
      ZipOutputStream dataZip = new ZipOutputStream(zipStream);
      //
      // дописываем управляющий файл
      //
      File cFile = new File(ABS_OUTPUT_DIR + "/control.xml");
      appendZipFile(dataZip, cFile);
      cFile.delete();
      //
      // дописываем подпись
      //
      cFile = new File(ABS_OUTPUT_DIR + "/control.sign");
      appendZipFile(dataZip, cFile);
      cFile.delete();
      logger.info("Запись в архив " + zip.getAbsolutePath() + " завершена");
      //
      // закрываем архив и его поток
      //
      dataZip.close();
      zipStream.close();
    } catch (Exception e) {
      logger.error(e.getMessage());
      e.printStackTrace();
    }

    return result;
  }