Advertisement
Guest User

javig

a guest
Mar 27th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.28 KB | None | 0 0
  1. package telekom1;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5.  
  6. import javax.swing.*;
  7. import java.awt.*;
  8. import java.awt.event.ActionEvent;
  9. import java.awt.event.ActionListener;
  10. import java.io.File;
  11. import java.io.FileNotFoundException;
  12. import java.io.IOException;
  13. import java.io.PrintWriter;
  14. import java.nio.file.Files;
  15. import java.nio.file.Paths;
  16. import java.nio.file.StandardOpenOption;
  17.  
  18. public class Zadanie1 extends JFrame {
  19.  
  20.     private static final long serialVersionUID = -8665668833005883229L;
  21.     private JButton dekodowanie, kodowanie;
  22.     private JTextArea textDekoduj;
  23.     private JTextArea textKoduj;
  24.     private File encoded, decoded;
  25.     // macierz korekcyjna
  26.     private static final byte[][] H = {                
  27.             {1,1,1,0,0,1,1,1,1,0,0,0,0,0,0,0},
  28.             {0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,0},
  29.             {1,0,0,1,0,1,0,1,0,0,1,0,0,0,0,0},
  30.             {1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,0},
  31.             {0,1,0,1,0,1,1,0,0,0,0,0,1,0,0,0},
  32.             {1,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0},
  33.             {1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0},
  34.             {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1}};
  35.     private byte[] T; // 16 bitów, 8 znak + 8 bity parzystości
  36.     private byte[] control; // 8 bitów wynik mnozenia macierzy
  37.  
  38.     // mnożenie macierzy (T*H), wynik w control
  39.     private void multiplyMatrix() {
  40.  
  41.         for (int i = 0; i < H.length; i++) {
  42.             for (int j = 0; j < T.length; j++)
  43.                 control[i] += T[j] * H[i][j];
  44.  
  45.             control[i] %= 2;
  46.         }
  47.     }
  48.  
  49.     // zamienia znak ASCII na 8 bitw zapisanzch w Stringu
  50.     public String ASCII2bin(byte c) {
  51.         String tmp = Integer.toBinaryString(c);
  52.  
  53.         if (tmp.length() > 8)
  54.             tmp = tmp.substring(tmp.length() - 8, tmp.length());
  55.  
  56.         while (tmp.length() < 8) {
  57.             tmp = "0" + tmp;
  58.         }
  59.  
  60.         return tmp;
  61.     }
  62.  
  63.     // zamienia 8 bitw zapisanzch w Stringu na znak ASCII
  64.     public byte bin2ASCII(String bin) {
  65.         return (byte) Integer.parseUnsignedInt(bin, 2);
  66.     }
  67.  
  68.     // ładuje String do tablicy T
  69.     private void loadT(String bin) {
  70.         byte[] b = bin.getBytes();
  71.         for (int i = 0; i < b.length; i++) {
  72.             b[i] -= 48; // 48 = ASCII '0'
  73.             T[i] = b[i];
  74.         }
  75.     }
  76.  
  77.     // zamienia znak ASCII na jego reprezentacje 16 bitową
  78.     private void encodeChar(char c) {
  79.         loadT(ASCII2bin((byte) c));
  80.         multiplyMatrix();
  81.  
  82.         // dopisz control do T
  83.         for (int i = 8; i < T.length; i++)
  84.             T[i] = control[i - 8];
  85.     }
  86.  
  87.     // oblicza wektor błędu dla 16 bitów
  88.     private void decodeChar(String bin) {
  89.         loadT(bin);
  90.         multiplyMatrix();
  91.     }
  92.  
  93.     // sprawdza czy wystąpił błąd
  94.     private boolean isCorrect() {
  95.         for (int i = 0; i < control.length; i++) {
  96.             if (control[i] == 1)
  97.                 return false;
  98.         }
  99.  
  100.         return true;
  101.     }
  102.  
  103.     // szuka 1 błędu, zwraca -1 gdy jest ich więcej
  104.     private int findError() {
  105.         boolean isFound;
  106.  
  107.         for (int i = 0; i < T.length; i++) {
  108.             isFound = true;
  109.             for (int j = 0; j < control.length; j++)
  110.                 if (H[j][i] != control[j]) {
  111.                     isFound = false;
  112.                     break;
  113.                 }
  114.             if (isFound)
  115.                 return i;
  116.         }
  117.  
  118.         return -1;
  119.     }
  120.  
  121.     // szuka 2 błędy, zwraca -1 w indexes[0] gdy jest ich więcej
  122.     private int[] findErrors() {
  123.         boolean isFound;
  124.         int[] indexes = new int[2]; // zawiera pozycje 2 błędów
  125.  
  126.         // podobnie jak wyżej, ale do tego sprawdza każdy z każdym
  127.         for (int i = 0; i < T.length - 1; i++) {
  128.             for (int j = i + 1; j < T.length; j++) {
  129.                 isFound = true;
  130.                 for (int k = 0; k < control.length; k++) {
  131.                     if (((H[k][i] + H[k][j]) % 2) != control[k]) {
  132.                         isFound = false;
  133.                         break;
  134.                     }
  135.                 }
  136.                 if (isFound) {
  137.                     indexes[0] = i;
  138.                     indexes[1] = j;
  139.                     return indexes;
  140.                 }
  141.             }
  142.         }
  143.         indexes[0] = -1;
  144.         indexes[1] = -1;
  145.         return indexes;
  146.     }
  147.  
  148.     // naprawia 1 błąd, gdy jest ich więcej przekierowuje dalej
  149.     private boolean repairError() {
  150.         int index = findError();
  151.  
  152.         if (index == -1) {
  153.             return repairErrors();
  154.         }
  155.  
  156.         // zmienia 0 -> 1 lub 1 -> 0
  157.         T[index] += 1;
  158.         T[index] %= 2;
  159.  
  160.         return true;
  161.     }
  162.  
  163.     // naprawia 2 błędy, gdy jest ich więcej zwraca false
  164.     private boolean repairErrors() {
  165.         int[] indexes = findErrors();
  166.  
  167.         if (indexes[0] == -1 && indexes[1] == -1) {
  168.             return false;
  169.         }
  170.  
  171.         T[indexes[0]] += 1;
  172.         T[indexes[0]] %= 2;
  173.  
  174.         T[indexes[1]] += 1;
  175.         T[indexes[1]] %= 2;
  176.  
  177.         return true;
  178.     }
  179.  
  180.     // koduje plik ze znakami ASCII na ich 16 bitową reprezentacje
  181.     public String encodeString(String input) {
  182.         String output = "";
  183.  
  184.         // usuń zbędne nowe linie
  185.         input = input.replaceAll(" ", "");
  186.         input = input.replaceAll("\n", "");
  187.  
  188.         // podziel String na pojedyncze znaki
  189.         char[] chars = input.toCharArray();
  190.  
  191.         for (int i = 0; i < chars.length; i++) {
  192.             // zamienia znak i ładuje do T
  193.             encodeChar(chars[i]);
  194.  
  195.             for (int j = 0; j < T.length; j++) {
  196.  
  197.                 if (j == 8)
  198.                     output += " ";
  199.  
  200.                 // zapisz 16 bitów do pliku
  201.                 output += T[j];
  202.             }
  203.             output += " \n";
  204.         }
  205.  
  206.         // wyczyszczenie tablic
  207.         Arrays.fill(control, (byte) 0);
  208.         Arrays.fill(T, (byte) 0);
  209.  
  210.         return output;
  211.     }
  212.  
  213.     // dekoduje plik z 16 bitową reprezentacją ASCII, wykrywając max 2 błędy
  214.     public String decodeString(String input) throws Exception {
  215.         String output = "";
  216.  
  217.         // usuń zbędne spacje i nowe linie
  218.         input = input.replaceAll(" ", "");
  219.         input = input.replaceAll("\n", "");
  220.  
  221.         String[] bins = new String[input.length() / 16];
  222.  
  223.         // podziel całość na 16 znakowe Stringi
  224.         for (int i = 0, j = 0; i < input.length(); i += 16, j++) {
  225.             bins[j] = input.substring(i, i + 16);
  226.             if (bins[j].charAt(0) == '1') {
  227.                 bins[j] = "0" + input.substring(i + 1, i + 16);
  228.             }
  229.         }
  230.  
  231.         for (int i = 0; i < bins.length; i++) {
  232.             // ładuje 16 bitów do T i liczy wektor błędu
  233.             decodeChar(bins[i]);
  234.  
  235.             // wykryto błąd- natępuje próba jego naprawienia
  236.             if (!isCorrect())
  237.                 if (!repairError())
  238.                     throw new Exception();
  239.  
  240.             String ascii = "";
  241.  
  242.             // złączenie 8 bitów znaku i zamiana na char
  243.             for (int j = 0; j < 8; j++) {
  244.                 ascii += T[j];
  245.             }
  246.             output += (char) bin2ASCII(ascii);
  247.  
  248.             // wyczyszczenie tablicy control
  249.             Arrays.fill(control, (byte) 0);
  250.         }
  251.  
  252.         // wyczyszczenie tablicy T
  253.         Arrays.fill(T, (byte) 0);
  254.  
  255.         return output;
  256.     }
  257.     void saveEncoded() throws IOException {
  258.         String output = textKoduj.getText();
  259.         output = output.replaceAll(" ", "");
  260.         output = output.replaceAll("\n", "");
  261.         String[] stringBytes = new String[output.length() / 8];
  262.  
  263.         // podziel całość na 8 znakowe Stringi
  264.         for (int i = 0, j = 0; i < output.length(); i += 8, j++) {
  265.             stringBytes[j] = output.substring(i, i + 8);
  266.         }
  267.  
  268.         byte[] bytes = new byte[stringBytes.length];
  269.  
  270.         for (int i = 0; i < bytes.length; i++) {
  271.             bytes[i] = bin2ASCII(stringBytes[i]);
  272.         }
  273.  
  274.         Files.write(Paths.get(encoded.toURI()), bytes, StandardOpenOption.WRITE);
  275.     }
  276.    
  277.     void saveDecoded() throws FileNotFoundException {
  278.         PrintWriter out = new PrintWriter(decoded);
  279.         out.write(textDekoduj.getText());
  280.         out.close();
  281.       }
  282.    
  283.       void encode() throws FileNotFoundException {
  284.         //saveDecoded();
  285.         String input = textDekoduj.getText();
  286.         String outpt = encodeString(input);
  287.         textKoduj.setText(outpt);
  288.       }
  289.      
  290.     void decode() throws Exception {
  291.         saveEncoded();
  292.         String input = textKoduj.getText();
  293.         String output = decodeString(input);
  294.         textDekoduj.setText(output);
  295.     }
  296.    
  297.     void reloadEncoded() throws IOException {
  298.         byte[] bytes;
  299.             bytes = Files.readAllBytes(Paths.get(encoded.toURI()));
  300.  
  301.             String input = "";
  302.  
  303.             for (int i = 0; i < bytes.length; i++) {
  304.                 input += ASCII2bin(bytes[i]);
  305.             }
  306.             textKoduj.setText(input);
  307.  
  308.        
  309.     }
  310.  
  311.     void reloadDecoded() throws FileNotFoundException {
  312.            Scanner in = new Scanner(decoded);
  313.  
  314.             // wczytaj wszystkie znaki
  315.             String input = "";
  316.             while (in.hasNextLine()) {
  317.                 input += in.nextLine();
  318.             }
  319.             textDekoduj.setText(input);
  320.             in.close();
  321.  
  322.     }
  323.     public Zadanie1(String name) throws FileNotFoundException, IOException {
  324.         super(name);
  325.  
  326.         dekodowanie = new JButton("DEKODOWANIE");
  327.         kodowanie = new JButton("KODOWANIE");
  328.  
  329.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  330.         setSize(500, 200);
  331.         setLocation(50, 50);
  332.         setLayout(new FlowLayout());
  333.  
  334.         add(kodowanie);
  335.         add(dekodowanie);
  336.  
  337.         // inicjalizacja tablic
  338.         T = new byte[16];
  339.         control = new byte[8];
  340.         //reloadEncoded();
  341.         //reloadDecoded();
  342.        
  343.         kodowanie.addActionListener(new ActionListener() {
  344.             @Override
  345.             public void actionPerformed(ActionEvent e) {
  346.  
  347.                 File currentDirFile = new File(".");
  348.                 String helper = currentDirFile.getAbsolutePath();
  349.                 String currentDir;
  350.                 try {
  351.                     currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());
  352.                     encoded = new File(currentDir + "/kodowanie.txt");
  353.                     try {
  354.                         // jeśli pliki nie istnieją- utwórz je
  355.                         if (!encoded.exists())
  356.                             encoded.createNewFile();
  357.                        
  358.                         encode();
  359.                         saveEncoded();
  360.                        
  361.                     } catch (IOException e2) {
  362.                         e2.printStackTrace();
  363.                     }
  364.                 } catch (IOException e1) {
  365.                     e1.printStackTrace();
  366.                 }
  367.             }
  368.         });
  369.  
  370.         dekodowanie.addActionListener(new ActionListener() {
  371.             @Override
  372.             public void actionPerformed(ActionEvent e) {
  373.                 File currentDirFile = new File(".");
  374.                 String helper = currentDirFile.getAbsolutePath();
  375.                 String currentDir;
  376.                 try {
  377.                     currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());
  378.                     decoded = new File(currentDir + "/dekodowanie.txt");
  379.                     try {
  380.                         // jeśli pliki nie istnieją- utwórz je
  381.                         if (!decoded.exists())
  382.                             decoded.createNewFile();
  383.                         // decode()
  384.                         decode();
  385.                         saveDecoded();
  386.                             ///////
  387.                        
  388.                     } catch (IOException e3) {
  389.                         e3.printStackTrace();
  390.                     }
  391.  
  392.                 } catch (Exception e1) {
  393.                     e1.printStackTrace();
  394.                 }
  395.             }
  396.         });
  397.         textDekoduj = new JTextArea();
  398.         textDekoduj.setBounds(1, 1, 1, 1);
  399.         add(textDekoduj);
  400.         textDekoduj.setColumns(10);
  401.  
  402.         textKoduj = new JTextArea();
  403.         textKoduj.setBounds(1, 1, 1, 1);
  404.         add(textKoduj);
  405.         textKoduj.setColumns(10);
  406.  
  407.         setVisible(true);
  408.     }
  409.  
  410.     public static void main(String[] args) throws FileNotFoundException, IOException {
  411.         @SuppressWarnings("unused")
  412.         Zadanie1 z1 = new Zadanie1("Telekomunikacja - zadanie 1");
  413.     }
  414.  
  415. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement