commit c119086ea4f850b3afa392f8c9cb18e106d7f072 Author: igor Date: Fri Apr 14 09:05:43 2023 +0600 Первая отправка diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2247d5f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/build +/dist diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..7df2979 --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project POTOXML_JavaSE. + + + diff --git a/manifest.mf b/manifest.mf new file mode 100644 index 0000000..328e8e5 --- /dev/null +++ b/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..cdaa371 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..2d325e8 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=d935f596 +build.xml.script.CRC32=b59ecd6a +build.xml.stylesheet.CRC32=8064a381@1.68.1.46 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=d935f596 +nbproject/build-impl.xml.script.CRC32=da5956f2 +nbproject/build-impl.xml.stylesheet.CRC32=830a3534@1.80.1.48 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..c9dff58 --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,2 @@ +compile.on.save=true +user.properties.file=C:\\Users\\ivanov.i.ISTT\\AppData\\Roaming\\NetBeans\\8.2\\build.properties diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml new file mode 100644 index 0000000..6807a2b --- /dev/null +++ b/nbproject/private/private.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..fbd3814 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,71 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processor.options= +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/POTOXML_JavaSE.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class=potoxml.NewJFrame +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..003e6af --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + POTOXML_JavaSE + + + + + + + + + diff --git a/src/potoxml/AssemblyJFrame.form b/src/potoxml/AssemblyJFrame.form new file mode 100644 index 0000000..d282f1d --- /dev/null +++ b/src/potoxml/AssemblyJFrame.form @@ -0,0 +1,109 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + +
+
diff --git a/src/potoxml/AssemblyJFrame.java b/src/potoxml/AssemblyJFrame.java new file mode 100644 index 0000000..b40bdd5 --- /dev/null +++ b/src/potoxml/AssemblyJFrame.java @@ -0,0 +1,326 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package potoxml; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFileChooser; +import javax.swing.filechooser.FileNameExtensionFilter; +import javax.swing.table.DefaultTableModel; +import javax.xml.parsers.ParserConfigurationException; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; +import tools.*; +import tools.xml.XMLIO; +import static tools.xml.XMLTools.isElement; + +/** + * + * @author ivanov.i + */ +public class AssemblyJFrame extends javax.swing.JFrame { + + /** + * Creates new form AssemblyJFrame + */ + public AssemblyJFrame() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jButton1 = new javax.swing.JButton(); + jScrollPane1 = new javax.swing.JScrollPane(); + jTable1 = new javax.swing.JTable(); + jButton2 = new javax.swing.JButton(); + jTextField1 = new javax.swing.JTextField(); + jLabel1 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jButton1.setText("Добавить файлик"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + jTable1.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + + }, + new String [] { + "id", "lng 1", "lng 2", "lng 3" + } + ) { + Class[] types = new Class [] { + java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class + }; + + public Class getColumnClass(int columnIndex) { + return types [columnIndex]; + } + }); + jScrollPane1.setViewportView(jTable1); + + jButton2.setText("Экспортировать"); + jButton2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton2ActionPerformed(evt); + } + }); + + jTextField1.setText("1"); + + jLabel1.setText("Открываемый столбец"); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(18, 18, 18) + .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(111, Short.MAX_VALUE)) + .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jButton1) + .addComponent(jButton2)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel1))) + .addGap(18, 18, 18) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + + + DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); + int colT = Integer.parseInt(jTextField1.getText()); + + JFileChooser chooser = new JFileChooser(); + chooser.addChoosableFileFilter(new FileNameExtensionFilter("Android XML", "xml")); + chooser.addChoosableFileFilter(new FileNameExtensionFilter("Poedit PO", "po")); + int returnVal = chooser.showOpenDialog(this); + if(returnVal == JFileChooser.APPROVE_OPTION) + { + if(Tools.afterLast(chooser.getSelectedFile().getName(), ".").toLowerCase().equals("xml")) + { + try { + + Document doc = XMLIO.load(chooser.getSelectedFile().getAbsolutePath()); + + NodeList nl = doc.getDocumentElement().getChildNodes(); + for (int i = 0; i + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(AssemblyJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(AssemblyJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(AssemblyJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(AssemblyJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new AssemblyJFrame().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JLabel jLabel1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTable jTable1; + private javax.swing.JTextField jTextField1; + // End of variables declaration//GEN-END:variables +} diff --git a/src/potoxml/FileFinder.java b/src/potoxml/FileFinder.java new file mode 100644 index 0000000..60df0da --- /dev/null +++ b/src/potoxml/FileFinder.java @@ -0,0 +1,270 @@ +package potoxml; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Этот класс предназначен для поиска файлов + * + * @author Стаценко Владимир http://www.vova-prog.narod.ru + */ +public class FileFinder +{ + + //классы для работы с регулярными выражениями + private Pattern p = null; + private Matcher m = null; + //общий размер найденных файлов + private long totalLength = 0; + //общее количество найденных файлов + private long filesNumber = 0; + //общее количество просмотренных директорий + private long directoriesNumber = 0; + //константы для определения объектов, которые нужно найти + private final int FILES = 0; + private final int DIRECTORIES = 1; + private final int ALL = 2; + + /** + * Создает новые экземпляры FileFinder + */ + public FileFinder() + { + } + + /** + * Этот метод выполняет поиск всех объектов (файлов и директорий), начиная с + * заданной директории (startPath) + * + * @param startPath Начальная директория поиска + * @return Список (List) найденных объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + */ + public List findAll(String startPath) throws Exception + { + return find(startPath, "", ALL); + } + + /** + * Этот метод выполняет поиск объектов (файлов и директорий), которые + * соответствуют заданному регулярному выражению (mask), начиная с заданной + * директории (startPath) + * + * @param startPath Начальная директория поиска + * @param mask регулярное выражение, которому должны соответствовать имена + * найденный объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + * @return Список (List) найденных объектов + */ + public List findAll(String startPath, String mask) + throws Exception + { + return find(startPath, mask, ALL); + } + + /** + * Этот метод выполняет поиск всех файлов, начиная с заданной директории + * (startPath) + * + * @param startPath Начальная директория поиска + * @return Список (List) найденных объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + */ + public List findFiles(String startPath) + throws Exception + { + return find(startPath, "", FILES); + } + + /** + * Этот метод выполняет поиск файлов, которые соответствуют заданному + * регулярному выражению (mask), начиная с заданной директории (startPath) + * + * @param startPath Начальная директория поиска + * @param mask регулярное выражение, которому должны соответствовать имена + * найденный объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + * @return Список (List) найденных объектов + */ + public List findFiles(String startPath, String mask) + throws Exception + { + return find(startPath, mask, FILES); + } + + /** + * Этот метод выполняет поиск всех директорий (папок), начиная с заданной + * директории (startPath) + * + * @param startPath Начальная директория поиска + * @return Список (List) найденных объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + */ + public List findDirectories(String startPath) + throws Exception + { + return find(startPath, "", DIRECTORIES); + } + + /** + * Этот метод выполняет поиск директорий (папок), которые соответствуют + * заданному регулярному выражению (mask), начиная с заданной директории + * (startPath) + * + * @param startPath Начальная директория поиска + * @param mask регулярное выражение, которому должны соответствовать имена + * найденный объектов + * @throws java.lang.Exception если возникли ошибки в процессе поиска + * @return Список (List) найденных объектов + */ + public List findDirectories(String startPath, String mask) + throws Exception + { + return find(startPath, mask, DIRECTORIES); + } + + /** + * Возвращает суммарный размер найденных файлов + * + * @return размер найденных файлов (байт) + */ + public long getDirectorySize() + { + return totalLength; + } + + /** + * Возвращает общее количество найденных файлов + * + * @return количество найденных файлов + */ + public long getFilesNumber() + { + return filesNumber; + } + + /** + * Возвращает общее количество найденных директорий (папок) + * + * @return количество найденных директорий (папок) + */ + public long getDirectoriesNumber() + { + return directoriesNumber; + } + + /* + Проверяет, соответствует ли имя файла заданному + регулярному выражению. Возвращает true, если найденный + объект соответствует регулярному выражению, false - в + противном случае. + */ + private boolean accept(String name) + { + //если регулярное выражение не задано... + if (p == null) + { + //...значит объект подходит + return true; + } + //создаем Matcher + m = p.matcher(name); + //выполняем проверку + if (m.matches()) + { + return true; + } else + { + return false; + } + } + + /* + Этот метод выполняет начальные установки поиска. + Затем вызывает метод search для выполнения поиска. + */ + private List find(String startPath, String mask, int objectType) + throws Exception + { + //проверка параметров + if (startPath == null || mask == null) + { + throw new Exception("Ошибка: не заданы параметры поиска"); + } + File topDirectory = new File(startPath); + if (!topDirectory.exists()) + { + throw new Exception("Ошибка: указанный путь не существует"); + } + //если задано регулярное выражение, создаем Pattern + if (!mask.equals("")) + { + p = Pattern.compile(mask, Pattern.CASE_INSENSITIVE | Pattern.COMMENTS); //Pattern.UNIcomment_CASE + } + //обнуляем все счетчики + filesNumber = 0; + directoriesNumber = 0; + totalLength = 0; + //создаем список результатов + ArrayList res = new ArrayList(100); + + //выполняем поиск + search(topDirectory, res, objectType); + + //присваиваем null шаблону, т.к. при следующем вызове find... + //регулярное выражение может быть не задано + p = null; + //возвращаем результат + return res; + } + + /* + Этот метод выполняет поиск объектов заданного типа. + Если, в процессе поиска, встречает вложенную директорию + (папку), то рекурсивно вызывает сам себя. + Результаты поиска сохраняются в параметре res. + Текущая директория - topDirectory. + Тип объекта (файл или директория) - objectType. + */ + private void search(File topDirectory, List res, int objectType) + { + //получаем список всех объектов в текущей директории + File[] list = topDirectory.listFiles(); + //просматриваем все объекты по-очереди + for (int i = 0; i < list.length; i++) + { + //если это директория (папка)... + if (list[i].isDirectory()) + { + //...выполняем проверку на соответствие типу объекта + // и регулярному выражению... + if (objectType != FILES && accept(list[i].getName())) + { + //...добавляем текущий объект в список результатов, + //и обновляем значения счетчиков + directoriesNumber++; + res.add(list[i]); + } + //выполняем поиск во вложенных директориях + search(list[i], res, objectType); + } //если это файл + else + { + //...выполняем проверку на соответствие типу объекта + // и регулярному выражению... + if (objectType != DIRECTORIES && accept(list[i].getName())) + { + //...добавляем текущий объект в список результатов, + //и обновляем значения счетчиков + filesNumber++; + totalLength += list[i].length(); + res.add(list[i]); + } + } + } + } +} \ No newline at end of file diff --git a/src/potoxml/NewJFrame.form b/src/potoxml/NewJFrame.form new file mode 100644 index 0000000..31b397a --- /dev/null +++ b/src/potoxml/NewJFrame.form @@ -0,0 +1,212 @@ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/src/potoxml/NewJFrame.java b/src/potoxml/NewJFrame.java new file mode 100644 index 0000000..faa40cd --- /dev/null +++ b/src/potoxml/NewJFrame.java @@ -0,0 +1,391 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package potoxml; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.StringReader; +import java.util.List; +import java.util.Stack; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author ivanov.i + */ +public class NewJFrame extends javax.swing.JFrame +{ + + /** + * Creates new form NewJFrame + */ + public NewJFrame() + { + initComponents(); + + //Загружаем настройки из текстового файла + BufferedReader reader; + try + { + reader = new BufferedReader(new FileReader("settings.txt")); + String line = null; + while ((line = reader.readLine()) != null) + { + textArea2.append(line + "\n"); + } + } catch (FileNotFoundException ex) + { + Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); + } catch (IOException ex) + { + Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jButton1 = new javax.swing.JButton(); + jLabel1 = new javax.swing.JLabel(); + textArea1 = new java.awt.TextArea(); + textArea2 = new java.awt.TextArea(); + jButton2 = new javax.swing.JButton(); + jLabel2 = new javax.swing.JLabel(); + jButton3 = new javax.swing.JButton(); + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel1 = new javax.swing.JPanel(); + jTextField1 = new javax.swing.JTextField(); + jLabel3 = new javax.swing.JLabel(); + jButton4 = new javax.swing.JButton(); + jPanel2 = new javax.swing.JPanel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jButton1.setText("Сканировать"); + jButton1.setName(""); // NOI18N + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + jLabel1.setText("Перебираем файлы и создаём единый PHP файлик с _(“слово”)."); + + jButton2.setText("Сохранить настройки"); + jButton2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton2ActionPerformed(evt); + } + }); + + jLabel2.setText("Пути для сканирования"); + + jButton3.setText("Экспорт"); + jButton3.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton3ActionPerformed(evt); + } + }); + + jTextField1.setText("jTextField1"); + + jLabel3.setText("Файл:"); + + jButton4.setText("Выбрать/Создать"); + jButton4.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton4ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel3) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 573, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel3) + .addComponent(jButton4)) + .addContainerGap(304, Short.MAX_VALUE)) + ); + + jTabbedPane1.addTab("English", jPanel1); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 772, Short.MAX_VALUE) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 338, Short.MAX_VALUE) + ); + + jTabbedPane1.addTab("Русский", jPanel2); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(textArea2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(jLabel2)) + .addGap(0, 0, Short.MAX_VALUE))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) + .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addGroup(layout.createSequentialGroup() + .addGap(24, 24, 24) + .addComponent(jButton2)) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel2) + .addComponent(jButton3)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(textArea2, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void parse(String rootDir,String file) + { + // Просматриваем каталоги + FileFinder finder = new FileFinder(); + try + { + // Буферный файл для записи идентификаторов + FileWriter fileWriter = new FileWriter(file); + BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); + bufferedWriter.write("=0) + { + from=s+2; + int e=-1; + if(line.charAt(s+2) == '"') { e=line.indexOf("\")", from); } + if(line.charAt(s+2) == '\'') { e = line.indexOf("')", from); } + if(e>=0) + { + textArea1.append(line.substring(s, e + 2)+";\n"); + bufferedWriter.write(" "+line.substring(s, e + 2)+";\n"); + from=e+2; + } + }else { break; } + } + } + bufferedReader.close(); + } + } + System.out.println("Найдено " + finder.getFilesNumber() + " файлов и " + finder.getDirectoriesNumber() + " папок."); + textArea1.append("Найдено " + finder.getFilesNumber() + " файлов и " + finder.getDirectoriesNumber() + " папок.\n"); + + bufferedWriter.write("?>\n"); + bufferedWriter.close(); + + } catch (Exception err) + { + System.out.println(err.getMessage()); + } + } + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed + {//GEN-HEADEREND:event_jButton1ActionPerformed + BufferedReader reader = new BufferedReader(new StringReader(textArea2.getText())); + String line1; + String line2; + try + { + while (true) + { + line1 = reader.readLine(); + line2 = reader.readLine(); + if(line1==null || line2 == null) break; + //Парсим файлы и выписываем идентификаторы для перевода + parse(line1, line2); //Перезаписывает файл + } + } catch (IOException ex) + { + Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_jButton1ActionPerformed + + + private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed + {//GEN-HEADEREND:event_jButton2ActionPerformed + FileWriter fileWriter = null; + try + { + fileWriter = new FileWriter("settings.txt"); + BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); + bufferedWriter.write(textArea2.getText()); + bufferedWriter.close(); + } catch (IOException ex) + { + Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); + } finally + { + try + { + fileWriter.close(); + } catch (IOException ex) + { + Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); + } + } + }//GEN-LAST:event_jButton2ActionPerformed + + private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed + + new AssemblyJFrame().setVisible(true); + + }//GEN-LAST:event_jButton3ActionPerformed + + private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed + // TODO add your handling code here: + }//GEN-LAST:event_jButton4ActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) + { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try + { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) + { + if ("Nimbus".equals(info.getName())) + { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) + { + java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) + { + java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) + { + java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) + { + java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() + { + public void run() + { + new NewJFrame().setVisible(true); + } + }); + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jButton1; + private javax.swing.JButton jButton2; + private javax.swing.JButton jButton3; + private javax.swing.JButton jButton4; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JPanel jPanel1; + private javax.swing.JPanel jPanel2; + private javax.swing.JTabbedPane jTabbedPane1; + private javax.swing.JTextField jTextField1; + private java.awt.TextArea textArea1; + private java.awt.TextArea textArea2; + // End of variables declaration//GEN-END:variables +} diff --git a/src/tools/Circle.java b/src/tools/Circle.java new file mode 100644 index 0000000..eef2ca3 --- /dev/null +++ b/src/tools/Circle.java @@ -0,0 +1,17 @@ +package tools; + +import java.awt.geom.Point2D; + +/** + * Created by IntelliJ IDEA. + * User: Admin + * Date: 14.07.2008 + * Time: 13:01:41 + * To change this template use File | Settings | File Templates. + */ + +public class Circle +{ + Point2D.Float cnt=new Point2D.Float(); //центр + float r=0; //радиус +} diff --git a/src/tools/Download2.java b/src/tools/Download2.java new file mode 100644 index 0000000..8e4fc80 --- /dev/null +++ b/src/tools/Download2.java @@ -0,0 +1,287 @@ +package tiptopTool; + +import java.net.MalformedURLException; +import java.net.URL; +import java.net.HttpURLConnection; +import java.net.URLConnection; +import java.io.*; +import java.util.Observable; +import java.util.Observer; + +/** + * Created by IntelliJ IDEA. + * User: Igor + * Date: 11.12.2005 + * Time: 13:45:51 + * To change this template use File | Settings | File Templates. + */ + +// This class downloads a file from a URL. +public class Download2 extends Observable implements Runnable +{ + +// Max size of download buffer. + private static final int MAX_BUFFER_SIZE = 1024; + +// These are the status names. + public static final String STATUSES[] = {"Загрузка", "Пауза", "Завершенно", "Отменено", "Ошыбка"}; + +// These are the status codes. + public static final int DOWNLOADING = 0; + public static final int PAUSED = 10; + public static final int COMPLETE = 2; + public static final int CANCELLED = 3; + public static final int ERROR = 4; + + public static URL urla; + public URL url; // download URL //bylo private + public String fileName; //путь к файлу + public String description=""; + private int size; // size of download in bytes + private int downloaded; // number of bytes downloaded + private int status; // current status of download + + private byte buffer[];//if save in the buffer +// Constructor for Download. + + public int getDownloaded() + { + return downloaded; + } + + public Download2(URL url,String fileName) + { + this.url = url; + this.fileName=fileName; + size = -1; + downloaded = 0; + status = DOWNLOADING; + } +// Get this download's URL. + public String getUrl() + { + return url.toString(); + } +// Get this download's size. + public int getSize() + { + return size; + } +// Get this download's progress. + public float getProgress() + { + return ((float) downloaded / size) * 100; + } +// Get this download's status. + public int getStatus() + { + return status; + } +// Pause this download. + public void pause() + { + status = PAUSED; + stateChanged(); + } +// Resume this download. + public void resume() + { + status = DOWNLOADING; + stateChanged(); + download(); + } +// Cancel this download. + public void cancel() + { + status = CANCELLED; + stateChanged(); + } +// Mark this download as having an error. + private void error() + { + status = ERROR; + stateChanged(); + } +// Start or resume downloading. + public void download() + { + Thread thread = new Thread(this); + thread.start(); + } +// Download + public void run() + { + //System.out.println("run"); + RandomAccessFile file = null; + InputStream stream = null; + + try + { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestProperty("Range","bytes=" + downloaded + "-");// Specify what portion of file to download. + // Connect to server. + connection.connect(); //System.out.println("connection to " + connection.getContentType()+" ResponseCode " + connection.getResponseCode()); + if (connection.getResponseCode() / 100 != 2) // провери отве севера + { + error(); + } + // Connect to server. + //connection.connect(); + //System.out.println(connection.getHeaderField(0).toString()); + //System.out.println("Тип пакета = " + connection.getContentType()); + //System.out.println("Заголовок = " + connection.getHeaderField(1)); + //System.out.println("Класс " + connection.toString()); + //System.out.println("Код ответа " + connection.getResponseCode()); + +// Check for valid content length. + int contentLength = connection.getContentLength(); + //System.out.println("Размер загружаемого файла =" + contentLength); + if (contentLength < 1) + { + error(); + } +// Set the size for this download if it +//hasn't been already set. + if (size == -1) + { + size = contentLength; + stateChanged(); + } + +// Open file and seek to the end of it. + if (!fileName.equals("")) + { + file = new RandomAccessFile(fileName, "rw"); + file.seek(downloaded); + } + if (fileName.equals("")) //фаил не задан сохраняем в буфер + { + this.buffer = new byte[size]; + } + + stream = connection.getInputStream(); + while (status == DOWNLOADING) + { + if (!fileName.equals("")) //если сохраняем в фаил + { + byte buffer[]; + if (size - downloaded > MAX_BUFFER_SIZE) + { + buffer = new byte[MAX_BUFFER_SIZE]; + } else + { + buffer = new byte[size - downloaded]; + } + // Read from server into buffer. + int read = stream.read(buffer); + if (read == -1) + break; + // Write buffer to file. + file.write(buffer, 0, read); + downloaded += read; + } + if (fileName.equals("")) //если сохраняем в буфер + { + byte buffer[]; + if (size - downloaded > MAX_BUFFER_SIZE) + { + buffer = new byte[MAX_BUFFER_SIZE]; + } else + { + buffer = new byte[size - downloaded]; + } + // Read from server into buffer. + int read = stream.read(buffer); + if (read == -1) + break; + // Write small buffer to big buffer. + for(int i=downloaded;i", "UTF-8"); + byte[] mas=data.getBytes(); + URL url = new URL(u); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setUseCaches (false); + conn.setRequestMethod("POST"); + conn.setRequestProperty( "User-Agent", "Mozilla/4.0" ); + conn.setRequestProperty( "Content-Type", "text/xml" ); + conn.setRequestProperty( "Content-Length", String.valueOf(mas.length)); + OutputStream wr = conn.getOutputStream(); + wr.write(mas); + wr.flush(); + int rc = conn.getResponseCode(); + if(rc==200) // Get the response + { + String line=""; + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + while ((line = rd.readLine()) != null) + { + rez += line; + } + rd.close(); + } + wr.close(); + } catch (Exception e) + { + e.printStackTrace(); + } + return rez; + } + + public static byte[] loadFileAsBytes(String fileName) throws IOException + { + return loadFileAsBytes(new File(fileName)); + } + + public static byte[] loadFileAsBytes(File file) throws IOException + { + byte[] result = new byte[(int) file.length()]; + loadFileAsBytes(file, result); + return result; + } + + public static void loadFileAsBytes(File file, byte[] buf) throws IOException + { + loadFileAsBytes(file, buf, 0, buf.length); + } + + public static void loadFileAsBytes(File file, byte[] buf, int off, int len) throws IOException + { + FileInputStream f = new FileInputStream(file); + try + { + f.read(buf, off, len); + } finally + { + try + { + f.close(); + } catch (Exception e) + { + } + } + } + + public static String loadFileAsString(File file, String encoding) throws IOException + { + InputStreamReader f = encoding == null ? new FileReader(file) : + new InputStreamReader(new FileInputStream(file), encoding); + StringBuffer sb = new StringBuffer(); + try + { + char[] buf = new char[32768]; + int len; + while ((len = f.read(buf, 0, buf.length)) >= 0) + { + sb.append(buf, 0, len); + } + return sb.toString(); + } finally + { + try + { + f.close(); + } catch (Exception e) + { + } + ; + } + } + + public static String loadFileAsString(String fileName, String encoding)throws IOException + { + return loadFileAsString(new File(fileName), encoding); + } + + public static char[] loadFileAsChars(String fileName, String encoding) throws IOException + { + return loadFileAsChars(new File(fileName), encoding); + } + + public static char[] loadFileAsChars(File file, String encoding) throws IOException + { + String buf = loadFileAsString(file, encoding); + char[] result = new char[buf.length()]; + buf.getChars(0, result.length, result, 0); + return result; + } + + + public static void loadFileAsChars(File file, String encoding, char[] buf) throws IOException + { + loadFileAsChars(file, encoding, buf, 0, buf.length); + } + + + public static void loadFileAsChars(File file, String encoding,char[] buf, int off, int len) throws IOException + { + InputStreamReader f = encoding == null ? + new FileReader(file) : + new InputStreamReader( + new FileInputStream(file), encoding); + try + { + f.read(buf, off, len); + + } finally + { + try + { + f.close(); + } catch (Exception e) + { + }; + } + } + + public static void saveFileFromString(String fileName, String encoding, String v) throws IOException + { + saveFileFromString(new File(fileName), encoding, v); + } + + + public static void saveFileFromString(File file, String encoding, String v) throws IOException + { + if (v == null) + { + file.delete(); + return; + } + char[] buf = new char[v.length()]; + v.getChars(0, buf.length, buf, 0); + saveFileFromChars(file, encoding, buf); + } + + + public static void saveFileFromChars( String fileName, String encoding, char[] buf) throws IOException + { + saveFileFromChars(new File(fileName), encoding, buf); + } + + + public static void saveFileFromChars(File file, String encoding, char[] buf) throws IOException + { + if (buf == null) + { + file.delete(); + return; + } + saveFileFromChars(file, encoding, buf, 0, buf.length); + } + + + public static void saveFileFromChars(File file, String encoding, char[] buf, int off, int len) throws IOException + { + if (buf == null) + { + file.delete(); + return; + } + OutputStreamWriter f = encoding == null ? new FileWriter(file) : new OutputStreamWriter(new FileOutputStream(file), encoding); + try + { + f.write(buf, off, len); + } catch (IOException e) + { + try + { + f.close(); + } catch (Exception e1) + { + } + ; + return; + } + f.close(); + } + + /** + * Чтение Integera совместимого с delphi + * + * @param InStream + * @return + * @throws IOException + */ + public static int readInt(DataInputStream InStream) throws IOException + { + int ch1, ch2, ch3, ch4, count; + ch1 = InStream.readUnsignedByte(); + ch2 = InStream.readUnsignedByte(); + ch3 = InStream.readUnsignedByte(); + ch4 = InStream.readUnsignedByte(); + + count = (ch4 << 24) | (ch3 << 16) | (ch2 << 8) | ch1; + return count; + } + + /** + * Чтение ASCI строки из файла знак конца строки #0 + * + * @param InStream + * @param i + * @return + * @throws IOException + */ + public static String readString(DataInputStream InStream, int i) throws IOException + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int ch; + while (true) + { + ch = InStream.readUnsignedByte(); + //System.out.println(ch); + ch = ch ^ i; //вот это надо будет потом удалить + //System.out.println("xor="+ch); + if (ch == 0) break; + baos.write(ch); + } + return baos.toString(); + } + + /** + * Вернуть расширение файла + * + * @return расширение + */ + public static String getExpansion(String fileName) + { + String exp = ""; + for (int i = fileName.length() - 1; i > 0; i--) + { + if (fileName.charAt(i) == '.') + { + break; + } else + { + exp = fileName.charAt(i) + exp; + } + } + return exp; + } + + /** + * Вернуть название файла + * + * @param path - путь + * @return + */ + public static String getFileName(String path) + { + path = path.replace('\\', '/'); + int lastSep = path.lastIndexOf('/'); + return path.substring(lastSep + 1); + } + + //узнать точку пересичений 2х линай если x=0 и y=0 то не пересиклась + public static Point2D.Float getCrossingLine(Point2D.Float PHead0, Point2D.Float PTail0, Point2D.Float PHead1, Point2D.Float PTail1) + { + Point2D.Float rezPoint = new Point2D.Float(); + + float a0, b0, c0, a1, b1, c1; + boolean bRez = true; + a0 = PTail0.y - PHead0.y; + b0 = PHead0.x - PTail0.x; + c0 = PTail0.x * PHead0.y - PHead0.x * PTail0.y; + + a1 = PTail1.y - PHead1.y; + b1 = PHead1.x - PTail1.x; + c1 = PTail1.x * PHead1.y - PHead1.x * PTail1.y; + + if (b1 == 0) rezPoint.x = PHead1.x;//если перпендикулярна oy + else rezPoint.x = (-(b0 * c1 / b1) + c0) / ((b0 * a1 / b1) - a0); + if (a1 == 0) rezPoint.y = PHead1.y;//если перпендикулярна oy + else rezPoint.y = (-(c1 * a0 / a1) + c0) / ((a0 * b1 / a1) - b0); + //проверка на вхождение в отрезоки (с погрешностью 0.0000001) + //по x + if ((rezPoint.x < Math.min(PHead0.x, PTail0.x) - 0.0000001) || (rezPoint.x > Math.max(PHead0.x, PTail0.x) + 0.0000001)) + bRez = false; + if ((rezPoint.x < Math.min(PHead1.x, PTail1.x) - 0.0000001) || (rezPoint.x > Math.max(PHead1.x, PTail1.x) + 0.0000001)) + bRez = false; + //по y + if ((rezPoint.y < Math.min(PHead0.y, PTail0.y) - 0.0000001) || (rezPoint.y > Math.max(PHead0.y, PTail0.y) + 0.0000001)) + bRez = false; + if ((rezPoint.y < Math.min(PHead1.y, PTail1.y) - 0.0000001) || (rezPoint.y > Math.max(PHead1.y, PTail1.y) + 0.0000001)) + bRez = false; + + if (!bRez) + { + rezPoint.x = 0; + rezPoint.y = 0; + } + return rezPoint; + } + + public class Triangle + { + int a,b,c; + } + + + public static float getLength(Point2D point1, Point2D point2) + { + return (float) Math.sqrt((point1.getX() - point2.getX()) * (point1.getX() - point2.getX()) + (point1.getY() - point2.getY()) * (point1.getY() - point2.getY())); + } + + /** + * узнать градус точки относительно заданного центра(радианы)} + */ + public static double getAngle(Point2D.Float CenterPoint,Point2D.Float ResearchedPoint) + { + double A, B, C, Angle; + Angle = 0; + A = (Math.abs(ResearchedPoint.y - CenterPoint.y) * 1.0); // А И В катеты треугольника + B = (Math.abs(ResearchedPoint.x - CenterPoint.x) * 1.0); + C = Math.sqrt(A * A + B * B); // С гипотенуза треугольника + if (C > 0) + { + Angle = Math.asin(B / C); + + if ((ResearchedPoint.x > CenterPoint.x) && (ResearchedPoint.y >= CenterPoint.y)) Angle = Math.PI/2 - Angle; + else //попрвка на сектора + if ((ResearchedPoint.x <= CenterPoint.x) && (ResearchedPoint.y > CenterPoint.y)) + Angle = Math.PI/2.0 + Angle; + else//попрвка на сектора + if ((ResearchedPoint.x < CenterPoint.x) && (ResearchedPoint.y <= CenterPoint.y)) + Angle = 3.0/2.0*Math.PI - Angle; + else//попрвка на сектора + if ((ResearchedPoint.x >= CenterPoint.x) && (ResearchedPoint.y < CenterPoint.y)) + Angle = 3.0 / 2.0 * Math.PI + Angle;//попрвка на сектора + } + return Angle; + } + + //узнать уравнение окружности проходящей через 3 точки + public static Circle fnCalcCircle(Point2D.Float p1, Point2D.Float p2, Point2D.Float p3) + { + Circle сircle=new Circle(); + float a1, b1, a2, b2, c1, c2; + float k1, k2; + a1 = 2 * (p1.x - p2.x); + b1 = 2 * (p2.y - p1.y); + c1 = ((p2.y - p1.y) * p2.y + (p2.y - p1.y) * p1.y) - ((p1.x - p2.x) * p1.x + (p1.x - p2.x) * p2.x); + a2 = 2 * (p3.x - p2.x); + b2 = 2 * (p2.y - p3.y); + c2 = ((p2.y - p3.y) * p2.y + (p2.y - p3.y) * p3.y) - ((p3.x - p2.x) * p3.x + (p3.x - p2.x) * p2.x); + if (b1 != 0) + { + k1 = (b2 * a1) / b1 - a2; + if (k1 == 0) //3 точки в 1 линии + { + сircle.r = 0; + return сircle; + } + сircle.cnt.x = ((c2 - (b2 * c1) / b1) / k1); + сircle.cnt.y = (c1 + a1 * сircle.cnt.x) / b1; + } else if (b2 != 0) + { + k2 = (b1 * a2) / b2 - a1; + if (k2 == 0) //3 точки в 1 линии + { + сircle.r = 0; + return сircle; + } + сircle.cnt.x = (c1 - (b1 * c2) / b2) / k2; + сircle.cnt.y = (c2 + a2 * сircle.cnt.x) / b2; + } else + { //всё в ё точке + сircle.r = 0; + } + сircle.r = (float) Math.sqrt((сircle.cnt.x - p1.x) * (сircle.cnt.x - p1.x) + (сircle.cnt.y - p1.y) * (сircle.cnt.y - p1.y)); + return сircle; + } + +} diff --git a/src/tools/xml/XMLIO.java b/src/tools/xml/XMLIO.java new file mode 100644 index 0000000..9599869 --- /dev/null +++ b/src/tools/xml/XMLIO.java @@ -0,0 +1,47 @@ +package tools.xml; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.dom.DOMSource; +import java.io.*; + +/** + * Created by IntelliJ IDEA. + * User: Igor + * Date: 18.12.2005 + * Time: 15:27:36 + * To change this template use File | Settings | File Templates. + */ +public class XMLIO +{ + public static Document newDocument() throws ParserConfigurationException + { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + } + + public static Document load(InputStream is) throws ParserConfigurationException, IOException, SAXException + { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); + } + + public static Document load(String filename) throws ParserConfigurationException, IOException, SAXException + { + return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filename)); + } + + public static void save(String filename, Document document) throws TransformerException, FileNotFoundException + { + save(new FileOutputStream(filename), document); + } + + public static void save(OutputStream out, Document document) throws TransformerException + { + TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(out)); + } +} diff --git a/src/tools/xml/XMLTools.java b/src/tools/xml/XMLTools.java new file mode 100644 index 0000000..ea36b4c --- /dev/null +++ b/src/tools/xml/XMLTools.java @@ -0,0 +1,127 @@ +package tools.xml; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSSerializer; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by IntelliJ IDEA. + * User: Igor + * Date: 18.12.2005 + * Time: 15:26:59 + * To change this template use File | Settings | File Templates. + */ +public class XMLTools +{ + public static Document parse(String xmlString) throws IOException, ParserConfigurationException, SAXException + { + return XMLIO.load(new ByteArrayInputStream(xmlString.getBytes())); + } + public static Document parse(InputStream xmlString) throws IOException, ParserConfigurationException, SAXException + { + return XMLIO.load(xmlString); + } + + /** + * Возвращает вложенный элемент "childName" элемента "parent"
+ * <element><childName/></element> + * @param parent + * @param childName + * @return Дочерный элемент либо null, если элементов с таким именем нет + */ + public static Element getChild(Element parent, String childName){ + NodeList nl = parent.getChildNodes(); + for (int i = 0; i node элементом (instanceOf {@link Element}) + * и имеет ли имя "tagname" + * @param node + * @param tagname + * @return + */ + public static boolean isElement(Node node, String tagname){ + return node instanceof Element && node.getNodeName().equals(tagname); + } + + //вернуть первый попавшийся узел среди дочерних + public static Node getFirstNodeOnName(Node node,String nodename) + { + Node[] mas=new Node[50]; //depth + int pos=0; + mas[pos] = node.getFirstChild(); + while (mas[pos] != null) + { + if(mas[pos].getNodeName().equals(nodename)) + { + return mas[pos]; + } + if(mas[pos].getFirstChild()!=null) + { + pos++; + mas[pos]=mas[pos-1].getFirstChild(); + }else + { + //если не идёт дальше пытаемся подняться в верх по дереву + while (true) + { + mas[pos] = mas[pos].getNextSibling(); + if (mas[pos]==null) + { + if(pos>0){ pos--; }else{ break; } + }else + { + break; + } + } + } + } + return null; + } + + /** + * Return first from childs in first deep level on name + * @param node Find in + * @param nodename Name node + * @return node + */ + public static Node getNodeOnName(Node node,String nodename) + { + if(node==null) return null; + Node nextNode = node.getFirstChild(); + while(nextNode != null) + { + if(nextNode.getNodeName().equals(nodename)) return nextNode; + nextNode=nextNode.getNextSibling(); + } + return null; + } + + //Сериализовать узел в строку + public static String getOuterXML(Node node) + { + DOMImplementationLS domImplementation = (DOMImplementationLS) node.getOwnerDocument().getImplementation(); + LSSerializer lsSerializer = domImplementation.createLSSerializer(); + if (!(node instanceof Document)) + { + lsSerializer.getDomConfig().setParameter("xml-declaration", false); + } + return lsSerializer.writeToString(node); + } + +}