Первая отправка

This commit is contained in:
2023-04-14 09:05:43 +06:00
commit c119086ea4
20 changed files with 4032 additions and 0 deletions

View File

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jTextField1" min="-2" pref="50" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton1" min="-2" pref="240" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jButton2" min="-2" pref="229" max="-2" attributes="0"/>
<EmptySpace pref="111" max="32767" attributes="0"/>
</Group>
<Component id="jScrollPane1" alignment="1" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jButton1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jButton2" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="103" alignment="1" groupAlignment="3" attributes="0">
<Component id="jTextField1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jScrollPane1" pref="481" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JButton" name="jButton1">
<Properties>
<Property name="text" type="java.lang.String" value="&#x414;&#x43e;&#x431;&#x430;&#x432;&#x438;&#x442;&#x44c; &#x444;&#x430;&#x439;&#x43b;&#x438;&#x43a;"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
</Events>
</Component>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTable" name="jTable1">
<Properties>
<Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
<Table columnCount="4" rowCount="0">
<Column editable="true" title="id" type="java.lang.String"/>
<Column editable="true" title="lng 1" type="java.lang.String"/>
<Column editable="true" title="lng 2" type="java.lang.String"/>
<Column editable="true" title="lng 3" type="java.lang.String"/>
</Table>
</Property>
</Properties>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JButton" name="jButton2">
<Properties>
<Property name="text" type="java.lang.String" value="&#x42d;&#x43a;&#x441;&#x43f;&#x43e;&#x440;&#x442;&#x438;&#x440;&#x43e;&#x432;&#x430;&#x442;&#x44c;"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton2ActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JTextField" name="jTextField1">
<Properties>
<Property name="text" type="java.lang.String" value="1"/>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="&#x41e;&#x442;&#x43a;&#x440;&#x44b;&#x432;&#x430;&#x435;&#x43c;&#x44b;&#x439; &#x441;&#x442;&#x43e;&#x43b;&#x431;&#x435;&#x446;"/>
</Properties>
</Component>
</SubComponents>
</Form>

View File

@ -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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//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();
}// </editor-fold>//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 <nl.getLength(); i++)
{
if (isElement(nl.item(i), "string"))
{
String msgid=nl.item(i).getAttributes().getNamedItem("name").getNodeValue();
String msgstr=nl.item(i).getLastChild().getTextContent();
//nl.item(i).getLastChild().getTextContent().trim()
int pos = -1;
for(int ii=0; ii<model.getRowCount(); ii++)
{
if(model.getValueAt(ii, 0).equals(msgid))
{
pos=i;
break;
}
}
if(pos!=-1)
{
model.setValueAt(msgstr, pos, colT);
}else
{
if(colT==1)
{
Object[] row = { msgid, msgstr, "", "" };
model.addRow(row);
}else
if(colT==2)
{
Object[] row = { msgid, "", msgstr, "" };
model.addRow(row);
}else
if(colT==3)
{ Object[] row = { msgid, "", "", msgstr };
model.addRow(row);
}
}
//System.out.println(nl.item(i).getAttributes().getNamedItem("name").toString());
}
}
} catch (ParserConfigurationException ex) {
Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(AssemblyJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}else
{
try
{
BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile().getAbsolutePath()));
String line;
String msgid="",msgstr="";
int cnt=0;
while (true)
{
line = reader.readLine();
if(line.indexOf("msgid")==0)
{
msgid = Tools.beforeLast(Tools.afterFirst(line, "\""),"\"");
cnt++;
}
if(line.indexOf("msgstr")==0)
{
msgstr = Tools.beforeLast(Tools.afterFirst(line, "\""),"\"");
cnt++;
}
if(cnt==2)
{
//Ищем идентификатор если он есть то обновляем ячейку если его нет то добавляем строку
int pos = -1;
for(int i=0; i<model.getRowCount(); i++)
{
if(model.getValueAt(i, 0).equals(msgid))
{
pos=i;
break;
}
}
if(pos!=-1)
{
model.setValueAt(msgstr, pos, colT);
}else
{
if(colT==1)
{
Object[] row = { msgid, msgstr, "", "" };
model.addRow(row);
}else
if(colT==2)
{
Object[] row = { msgid, "", msgstr, "" };
model.addRow(row);
}else
if(colT==3)
{ Object[] row = { msgid, "", "", msgstr };
model.addRow(row);
}
}
cnt=0;
}
}
} catch (IOException ex)
{
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
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
//TODO Записываем в строку в виде HTML строки затем сохраняем в файл
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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);
}
//</editor-fold>
/* 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
}

270
src/potoxml/FileFinder.java Normal file
View File

@ -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]);
}
}
}
}
}

212
src/potoxml/NewJFrame.form Normal file
View File

@ -0,0 +1,212 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="textArea2" max="32767" attributes="0"/>
<Group type="102" alignment="0" attributes="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="0" pref="0" max="32767" attributes="0"/>
</Group>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Component id="jButton2" max="32767" attributes="0"/>
<Component id="jButton3" max="32767" attributes="0"/>
</Group>
</Group>
<Component id="textArea1" alignment="0" max="32767" attributes="0"/>
<Component id="jButton1" alignment="1" min="-2" max="-2" attributes="0"/>
<Component id="jTabbedPane1" alignment="1" max="32767" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Group type="103" groupAlignment="1" attributes="0">
<Group type="102" attributes="0">
<EmptySpace min="-2" pref="24" max="-2" attributes="0"/>
<Component id="jButton2" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jButton3" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="32767" attributes="0"/>
<Component id="textArea2" min="-2" pref="118" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="textArea1" min="-2" pref="143" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton1" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="jTabbedPane1" min="-2" pref="366" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JButton" name="jButton1">
<Properties>
<Property name="text" type="java.lang.String" value="&#x421;&#x43a;&#x430;&#x43d;&#x438;&#x440;&#x43e;&#x432;&#x430;&#x442;&#x44c;"/>
<Property name="name" type="java.lang.String" value="" noResource="true"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton1ActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="&#x41f;&#x435;&#x440;&#x435;&#x431;&#x438;&#x440;&#x430;&#x435;&#x43c; &#x444;&#x430;&#x439;&#x43b;&#x44b; &#x438; &#x441;&#x43e;&#x437;&#x434;&#x430;&#x451;&#x43c; &#x435;&#x434;&#x438;&#x43d;&#x44b;&#x439; PHP &#x444;&#x430;&#x439;&#x43b;&#x438;&#x43a; &#x441; _(&#x201c;&#x441;&#x43b;&#x43e;&#x432;&#x43e;&#x201d;)."/>
</Properties>
</Component>
<Component class="java.awt.TextArea" name="textArea1">
</Component>
<Component class="java.awt.TextArea" name="textArea2">
</Component>
<Component class="javax.swing.JButton" name="jButton2">
<Properties>
<Property name="text" type="java.lang.String" value="&#x421;&#x43e;&#x445;&#x440;&#x430;&#x43d;&#x438;&#x442;&#x44c; &#x43d;&#x430;&#x441;&#x442;&#x440;&#x43e;&#x439;&#x43a;&#x438;"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton2ActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="&#x41f;&#x443;&#x442;&#x438; &#x434;&#x43b;&#x44f; &#x441;&#x43a;&#x430;&#x43d;&#x438;&#x440;&#x43e;&#x432;&#x430;&#x43d;&#x438;&#x44f;"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="jButton3">
<Properties>
<Property name="text" type="java.lang.String" value="&#x42d;&#x43a;&#x441;&#x43f;&#x43e;&#x440;&#x442;"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton3ActionPerformed"/>
</Events>
</Component>
<Container class="javax.swing.JTabbedPane" name="jTabbedPane1">
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout$JTabbedPaneConstraintsDescription">
<JTabbedPaneConstraints tabName="English">
<Property name="tabTitle" type="java.lang.String" value="English"/>
</JTabbedPaneConstraints>
</Constraint>
</Constraints>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel3" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jTextField1" min="-2" pref="573" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton4" min="-2" pref="139" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jTextField1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="jButton4" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace pref="304" max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JTextField" name="jTextField1">
<Properties>
<Property name="text" type="java.lang.String" value="jTextField1"/>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabel3">
<Properties>
<Property name="text" type="java.lang.String" value="&#x424;&#x430;&#x439;&#x43b;:"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="jButton4">
<Properties>
<Property name="text" type="java.lang.String" value="&#x412;&#x44b;&#x431;&#x440;&#x430;&#x442;&#x44c;/&#x421;&#x43e;&#x437;&#x434;&#x430;&#x442;&#x44c;"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton4ActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="jPanel2">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout$JTabbedPaneConstraintsDescription">
<JTabbedPaneConstraints tabName="&#x420;&#x443;&#x441;&#x441;&#x43a;&#x438;&#x439;">
<Property name="tabTitle" type="java.lang.String" value="&#x420;&#x443;&#x441;&#x441;&#x43a;&#x438;&#x439;"/>
</JTabbedPaneConstraints>
</Constraint>
</Constraints>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="772" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<EmptySpace min="0" pref="338" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
</Container>
</SubComponents>
</Container>
</SubComponents>
</Form>

391
src/potoxml/NewJFrame.java Normal file
View File

@ -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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//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();
}// </editor-fold>//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("<?\n");
List searchRes = null;
searchRes = finder.findAll(rootDir,"(.*\\.as$)||(.*\\.mxml$)||(.*\\.xml$)");
//выводим результаты
for (int i = 0; i < searchRes.size(); i++)
{
File curObject = (File) searchRes.get(i);
if (curObject.isDirectory())
{
System.out.println(curObject.getName() + " (папка)");
textArea1.append(curObject.getAbsolutePath() + " (папка)\n");
} else
{
System.out.println(curObject.getName() + " (" + curObject.length() + " байт)");
textArea1.append(curObject.getAbsolutePath() + " (" + curObject.length() + " байт)\n");
// Открываем файл и ищем идентификаторы
FileReader fileReader = new FileReader(curObject.getAbsolutePath());
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
//bufferedWriter.write("1\n");
while((line = bufferedReader.readLine()) != null)
{
int from=0;
while(true) //Если несколько значений в строке
{
int s=line.indexOf("_(", from);
if(s>=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 */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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);
}
//</editor-fold>
/* 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
}

17
src/tools/Circle.java Normal file
View File

@ -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; //радиус
}

287
src/tools/Download2.java Normal file
View File

@ -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<downloaded+read;i++)
{
this.buffer[i]=buffer[i-downloaded];
}
downloaded += read;
}
stateChanged();
}
// Change status to complete if this point was
//reached because downloading has finished.
if (status == DOWNLOADING)
{
status = COMPLETE;
stateChanged();
}
} catch (Exception e)
{
error();
} finally
{
// Close file.
if (file != null)
{
try
{
file.close();
} catch (Exception e)
{
}
}
// Close connection to server.
if (stream != null)
{
try
{
stream.close();
} catch (Exception e)
{
}
}
}
}
/**
* get loaded data
* @return Stream data
*/
public DataInputStream getData()
{
if (fileName.equals("")) //если сохраняем в буфер
{
return new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(buffer)));
}else
if (!fileName.equals("")) //если сохраняем в буфер
{
try
{
//System.out.println("Запрошенные данные = "+fileName);
return new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
} catch (FileNotFoundException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return null;
}
// Notify observers that this download's status has changed.
private void stateChanged()
{
setChanged();
notifyObservers(this);
//System.out.println("Загруженно = "+downloaded+" из="+size);
}
public static void main(String args[])
{
try
{
URL a = new URL("http://tiptopcity.com/java/d.php");
Download2 pobieranie = new Download2(a,"d.php");
pobieranie.download();
} catch (MalformedURLException e)
{
System.out.println("Bad URL gayos");
}
}
}

32
src/tools/Net.java Normal file
View File

@ -0,0 +1,32 @@
package tiptopTool;
/**
* Created by IntelliJ IDEA.
* User: igor
* Date: 02.03.2006
* Time: 20:13:27
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.net.*;
public class Net {
public static void main(String args[]) {
try {
URL url = new URL("http://www.ru");
LineNumberReader r = new LineNumberReader(new InputStreamReader(url.openStream()));
String s = r.readLine();
while (s!=null)
{
System.out.println(s);
s = r.readLine();
}
System.out.println(r.getLineNumber());
r.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

613
src/tools/Tools.java Normal file
View File

@ -0,0 +1,613 @@
package tools;
import java.io.*;
import java.awt.geom.Point2D;
import java.net.*;
import java.io.FileNotFoundException;
/**
* Created by IntelliJ IDEA.
* User: Igor
* Date: 29.11.2005
* Time: 20:27:28
* To change this template use File | Settings | File Templates.
*/
public class Tools
{
public static String beforeFirst(String str, String ch)
{
int i=str.indexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
public static String afterFirst(String str, String ch)
{
int i=str.indexOf(ch);
if(i!=-1)
{
return str.substring(i+ch.length());
}
return "";
}
public static String beforeLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(0,i);
}
return "";
}
public static String afterLast(String str, String ch)
{
int i=str.lastIndexOf(ch);
if(i!=-1)
{
return str.substring(i+ch.length());
}
return "";
}
/**
* Чтение флоата совместимого с Delphi
*
* @param InStream
* @return
* @throws IOException
*/
public static float readFloat(DataInputStream InStream) throws IOException
{
float f;
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;
f = Float.intBitsToFloat(count);
return f;
}
/**
* запросить страицу с сервера
*
* @param strURL Адрес (php, html)
* @return html страница
*/
public static String getHTMLFromURL(String strURL)
{
String rez = null;
String inputLine = null;
try
{
rez = new String("".getBytes(), "utf-8");
inputLine = new String("".getBytes(), "utf-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try
{
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x- www-form-urlencoded");
DataOutputStream outwriter = new DataOutputStream(conn.getOutputStream());
//outwriter.writeBytes(post);
outwriter.flush();
outwriter.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((inputLine = in.readLine()) != null)
{
rez += inputLine + "\n";
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return rez;
}
public static InputStream getHTMLFromURL2(String strURL)
{
String fileName = System.getProperty("java.io.tmpdir") + "tiptopcity.tmp";
try
{
URL u = new URL(strURL);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
InputStream is = huc.getInputStream();
int code = huc.getResponseCode();
if (code == HttpURLConnection.HTTP_OK)
{
byte[] buffer = new byte[4096]; //4 Kb
FileOutputStream outputStream = new FileOutputStream(new File(fileName));
int bytes;
while (true)
{
bytes = is.read(buffer);
if (bytes <= 0) break;
outputStream.write(buffer, 0, bytes);
}
outputStream.close();
}
huc.disconnect();
}
catch (IOException e)
{
System.out.println("Exception\n" + e);
}
try
{
return new FileInputStream(new File(fileName));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
public static byte[] getHTMLFromURL3(String strURL)
{
URL u=null;
try
{
u = new URL(strURL);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
return getHTMLFromURL3(u);
}
public static byte[] getHTMLFromURL3(URL u)
{
String fileName = System.getProperty("java.io.tmpdir") + "tiptopcity.tmp";
try
{
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
InputStream is = huc.getInputStream();
int code = huc.getResponseCode();
if (code == HttpURLConnection.HTTP_OK)
{
byte[] buffer = new byte[4096]; //4 Kb
FileOutputStream outputStream = new FileOutputStream(new File(fileName));
int bytes;
while (true)
{
bytes = is.read(buffer);
if (bytes <= 0) break;
outputStream.write(buffer, 0, bytes);
}
outputStream.close();
}
huc.disconnect();
}
catch (IOException e)
{
System.out.println("Exception\n" + e);
}
try
{
return loadFileAsBytes(fileName);
} catch (IOException e)
{
e.printStackTrace();
}
return new byte[0];
}
//для передачи XML на сервер
public static String getHTMLFromURL4(String u,String data)
{
String rez="";
try {
//String data = URLEncoder.encode("<?xml version=\"1.0\" encoding=\"utf-8\"?><metadata fn=\"0\" htmlid=\"0\" treeid=\"-1\"><filter></filter></metadata>", "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;
}
}

47
src/tools/xml/XMLIO.java Normal file
View File

@ -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));
}
}

127
src/tools/xml/XMLTools.java Normal file
View File

@ -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" <br/>
* &lt;element&gt;&lt;childName/&gt;&lt;/element&gt;
* @param parent
* @param childName
* @return Дочерный элемент либо <code>null</code>, если элементов с таким именем нет
*/
public static Element getChild(Element parent, String childName){
NodeList nl = parent.getChildNodes();
for (int i = 0; i <nl.getLength(); i++) {
if (isElement(nl.item(i), childName)){
return (Element)nl.item(i);
}
}
return null;
}
/**
* Проверяет, является ли <code>node</code> элементом (<code>instanceOf {@link Element}</code>)
* и имеет ли имя "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);
}
}