black-tan / temporary

temporary repository
0 stars 0 forks source link

test #1

Open black-tan opened 6 years ago

black-tan commented 6 years ago

test comment

black-tan commented 6 years ago

https://terms.naver.com/list.nhn?cid=58528&categoryId=58528&so=st4.asc

. Chapter 01. 소프트웨어 공학 소개        . Chapter 02. 소프트웨어 개발 프로세스        . Chapter 05. 상위 설계        . Chapter 06. 하위 설계

black-tan commented 6 years ago

public class Client { private String qNum; private Map<String, String> actionMap = new TreeMap<>(); private Socket socket; private InputStream is; private OutputStream os;

public Client(String qNum) {
    this.qNum = qNum;
    try {
        socket = new Socket("127.0.0.1", 50000);
        is = socket.getInputStream();
        os = socket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void makeActionFile() throws IOException {
    Map<String, Integer> local = getLocalFileMap();
    Map<String, Integer> server = getServerFileMap();

    for (String fileName: server.keySet()) {
        if (local.containsKey(fileName)) {
            if (local.get(fileName) < server.get(fileName)) {
                actionMap.put(fileName, "U");
            }
        } else {
            actionMap.put(fileName, "C");
        }
    }

    for (String fileName: local.keySet()) {
        if (!server.containsKey(fileName)) {
            actionMap.put(fileName, "D");
        }
    }

    File file = new File("src/" + qNum + "/target/CUD.txt");
    FileWriter writer = new FileWriter(file);
    for (String name: actionMap.keySet()) {
        writer.write(name + "|" + actionMap.get(name) + "\n");
    }
    writer.close();
}

private Map<String, Integer> getLocalFileMap() throws IOException {
    Map<String, Integer> map = new HashMap<>();
    File folder = new File("src/" + qNum + "/target");
    if (folder.exists()) {
        for (File fileName: folder.listFiles()) {
            if (fileName.getName().equals("CUD.txt")) {
                continue;
            }
            map.put(fileName.getName(), getFileVersion(fileName));
        }
    }
    return map;
}

private Map<String, Integer> getServerFileMap() throws IOException {
    Map<String, Integer> map = new TreeMap<>();
    StringBuilder sb = new StringBuilder();
    byte[] buf = new byte[1024];
    int len;
    os.write("LST".getBytes());
    while ((len = is.read(buf)) > 0) {
        if (len >= 2 && buf[len - 2] == '@' && buf[len - 1] == '@') {
            sb.append(new String(buf, 0, len - 2));
            break;
        } else {
            sb.append(new String(buf, 0, len));
        }
    }

    for (String chunk: sb.toString().split("&")) {
        map.put(chunk.split("_")[0], Integer.parseInt(chunk.split("_")[1]));
    }

    return map;
}

private int getFileVersion(File file) throws IOException {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(file));
        return Integer.parseInt(reader.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        reader.close();
    }
    return 0;
}

public void sync() throws IOException {
    backup(new File("src/" + qNum + "/target"), new File("src/" + qNum + "/backup"));
    for (String fileName: actionMap.keySet()) {
        switch (actionMap.get(fileName)) {
        case "C":
        case "U":
            if (!getServerFile(fileName)) {
                deleteFolder(new File("src/" + qNum + "/target"));
                backup(new File("src/" + qNum + "/backup"), new File("src/" + qNum + "/target"));
                deleteFolder(new File("src/" + qNum + "/backup"));
                return;
            }
            break;
        case "D":
            File file = new File("src/" + qNum + "/target/" + fileName);
            file.delete();
            break;
        }
    }
    deleteFolder(new File("src/" + qNum + "/backup"));
}

private void backup(File sourceFolder, File targetFolder) throws IOException {
    targetFolder.mkdirs();

    for (File file: sourceFolder.listFiles()) {
        if (file.getName().equals("CUD.txt")) {
            continue;
        }
        File newFile = new File(targetFolder.getAbsolutePath() + "/" + file.getName());
        byte[] buf = new byte[4096];
        int len;

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(newFile));

            while ((len = bis.read(buf)) > 0) {
                bos.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bos.close();
            bis.close();
        }
    }
}

private void deleteFolder(File folder) {
    for (File file: folder.listFiles()) {
        file.delete();
    }
    folder.delete();
}

private boolean getServerFile(String fileName) throws IOException {
    BufferedOutputStream fos = null;
    byte[] buf = new byte[4096];
    int len;

    try {
        os.write("GET".getBytes());
        os.write(fileName.getBytes());
        fos = new BufferedOutputStream(new FileOutputStream("src/" + qNum + "/target/" + fileName));
        while ((len = is.read(buf)) > 0) {
            if (len >= 2 && buf[len - 2] == '#' && buf[len - 1] == '#') {
                return false;
            }
            if (len >= 2 && buf[len - 2] == '@' && buf[len - 1] == '@') {
                fos.write(buf, 0, len - 2);
                break;
            } else {
                fos.write(buf, 0, len);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fos.close();
    }
    return true;
}

}

black-tan commented 6 years ago

public class Server implements Runnable {

private Socket socket;
private InputStream is;
private OutputStream os;
private boolean isFirst = true;

public Server(Socket socket) {
    System.out.println("Connected.");
    this.socket = socket;
    try {
        this.is = socket.getInputStream();
        this.os = socket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void run() {
    try {
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            String action = new String(buf, 0 , len);
            switch (action) {
            case "LST":
                sendList();
                break;
            case "GET":
                sendFile();
                break;
            }
        }
    } catch (IOException e) {
        //
    } finally {
        try {
            socket.close();
            System.out.println("Disconnected.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void sendList() throws IOException {
    String list = getServerFiles();
    Random random = new Random();
    int cut = random.nextInt(list.length());

    os.write(list.substring(0, cut).getBytes());
    os.write(list.substring(cut).getBytes());
    os.write("@@".getBytes());
}

private String getServerFiles() throws IOException {
    StringBuilder sb = new StringBuilder();
    File folder = new File("src/q4/source");
    if (folder.exists()) {
        for (File fileName: folder.listFiles()) {
            if (sb.length() == 0) {
                sb.append(fileName.getName() + "_" + getFileVersion(fileName));
            } else {
                sb.append("&" + fileName.getName() + "_" + getFileVersion(fileName));
            }
        }
    }
    return sb.toString();
}

private int getFileVersion(File file) throws IOException {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(file));
        return Integer.parseInt(reader.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        reader.close();
    }
    return 0;
}

private void sendFile() throws IOException {
    byte[] buf = new byte[1024];
    int len = is.read(buf);
    String fileName = new String(buf, 0, len);

    File file = new File("src/q4/source/" +  fileName);
    if (file.exists()) {
        BufferedInputStream fis = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file));
            while ((len = fis.read(buf)) > 0) {
                os.write(buf, 0, len);
                if (!isFirst) {
                    os.write("##".getBytes());
                    return;
                }
            }
            os.write("@@".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fis.close();
        }
    }
    if (isFirst) {
        isFirst = !isFirst;
    }
}

}

black-tan commented 6 years ago

`public class ServerLauncher {

public void run() throws IOException {
    ServerSocket serverSocket = new ServerSocket(50000);
    while (true) {
        Socket socket = serverSocket.accept();
        new Thread(new Server(socket)).start();
    }
}

}`

black-tan commented 6 years ago

`public class ClientLauncher {

public static void main(String[] args) throws IOException {
    Client client = new Client("q4");
    client.makeActionFile();
    client.sync();
}

}`

black-tan commented 6 years ago

`public class ServerLauncher {

public void run() throws IOException {
    ServerSocket serverSocket = new ServerSocket(50000);
    while (true) {
        Socket socket = serverSocket.accept();
        new Thread(new Server(socket)).start();
    }
}

} `

black-tan commented 6 years ago

`public class ServerLauncher {

public static void main(String[] args) throws IOException {
    new q4.server.ServerLauncher().run();
}

}`

black-tan commented 6 years ago

Card 문제 시작

public class Validator { public boolean checkIdPsw(String id, String psw) throws NoSuchAlgorithmException, IOException { boolean bRet = false; BufferedReader in = new BufferedReader(new FileReader("..//CLIENT//INSPECTOR.TXT")); String strLine; String encPsw = CardUtility.passwordEncryption(psw); while ((strLine = in.readLine()) != null) { String fileId = strLine.substring(0,8); String filePsw = strLine.substring(9);

        if (id.equals(fileId) && filePsw.equals(encPsw))
        {
            bRet = true;
            break;
        }
    }
    in.close();

    return bRet;
}   

// cardInfo : [ī��ID(8)][������ȣ(7)][����/���� �ڵ�(1)][�ֱ� �����ð�(14)]
// sample : CARD_001BUS_001N20171019143610
public void inspectCard(String startTime, String id, String busID, String cardInfo) throws IOException, ParseException
{
    String strValidateCode;

    // cardInfo parsing 
    //String cardID = cardInfo.substring(0, 8); 
    String cardBusID = cardInfo.substring(8,15); 
    String code = cardInfo.substring(15,16);
    String rideTime = cardInfo.substring(16);

    // Get Inspect Time
    String strInspectTime = CardUtility.getCurrentDateTimeString();

    // Validation
    // 1. Bus ID Match
    if (busID.equals(cardBusID))
    {
        // 2. Check Aboard Code
        if (code.equals("N"))
        {
            // 3. Time Difference
            if (CardUtility.hourDiff(strInspectTime, rideTime) < 3)
            {
                strValidateCode = "R1";
            }
            else
            {
                strValidateCode = "R4";
            }
        }
        else
        {
            strValidateCode = "R3";
        }
    }
    else
    {
        strValidateCode = "R2";
    }

    // Create Folder
    File destFolder = new File("..//"+id);
    if(!destFolder.exists()) {
        destFolder.mkdirs(); 
    }

    // File Writing
    String strFilename = destFolder+"//"+id+"_"+startTime+".TXT";
    FileWriter fw = new FileWriter(strFilename,true);
    fw.write(id+"#"+busID+"#"+cardInfo+"#"+strValidateCode+"#"+strInspectTime+"\n");
    fw.close();
}   

public void sendToServer(String inspectorID) throws UnknownHostException, IOException
{
    final int FILENAME_LEN = 27;
    Socket s = new Socket("127.0.0.1", 27015);
    OutputStream out = s.getOutputStream();
    byte[] buffer = new byte[4096];
    int readLen;

    //get all the files from a directory
    File directory = new File("..//"+inspectorID);
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if(file.isFile()) {
            String sendString = "*"+file.getName();
            long nFileLen = file.length();

            System.arraycopy(sendString.getBytes(), 0, buffer, 0, 1+FILENAME_LEN);
            CardUtility.intToByte(buffer, sendString.length(), (int)nFileLen);

            // send 
            out.write(buffer,0,sendString.length()+4);
            FileInputStream inputStream = new FileInputStream(file.getPath());
            while((readLen = inputStream.read(buffer)) != -1) {
                out.write(buffer,0,readLen);
            }   
            inputStream.close();    

            // move file to backup folder
            moveFileToBackup(file.getPath(), file.getName());
        }
    }       

    s.close();
}       

private void moveFileToBackup(String path, String name)
{
    File fileFrom = new File(path);                 // source
    File fileTo = new File("..//BACKUP//"+name);    // destination
    fileTo.delete();
    fileFrom.renameTo(fileTo);      
}   

}

black-tan commented 6 years ago

public class ValidatorLauncher { public static void main(String[] args) throws IOException, NoSuchAlgorithmException, ParseException {
Validator validator = new Validator(); InputStream in = System.in; InputStreamReader reader = new InputStreamReader(in); BufferedReader br = new BufferedReader(reader); String strInput, strId, strPassword, strBusId, strCardInfo;

    while (true)
    {
        strInput = br.readLine();   // id, password
        if (strInput.length() < 10)
        {
            System.out.println("Wrong ID Password");
            continue;
        }
        strId = strInput.substring(0,8);
        strPassword = strInput.substring(9);

        if (validator.checkIdPsw(strId, strPassword))
        {
            System.out.println("LOGIN SUCCESS");
            break;
        }
        else
        {
            System.out.println("LOGIN FAIL");
        }
    }

    // Inspection
    while (true)
    {
        strBusId = br.readLine();   // busid 

        if (strBusId.equals("LOGOUT"))
            break;

        if (strBusId.length() < 7 || strBusId.substring(0,4).equals("BUS_") != true)
        {
            System.out.println("Wrong Bus ID");
            continue;
        }

        // Get Start Time
        String strTime = CardUtility.getCurrentDateTimeString(); 

        // Card Validation
        while (true)
        {
            strCardInfo = br.readLine();
            if (strCardInfo.equals("DONE"))
            {
                break;
            }

            if (strCardInfo.length() != 30)
            {                   
                System.out.println("Wrong Card Info");              
                continue;
            }

            validator.inspectCard(strTime, strId, strBusId, strCardInfo); 
        }
    }

    // Send Files to Server
    validator.sendToServer(strId);
}

}

black-tan commented 6 years ago

public class CardServer implements Runnable { // Runnable Interface ���� public ServerSocket listener;
public void run() { final int FILENAME_LEN = 27; final int HEADER_SIZE = 1 + FILENAME_LEN + 4; final int BUF_SIZE = 4096; int recvLen; int nDataSize = 0;
String filename = ""; byte[] buffer = new byte[BUF_SIZE+HEADER_SIZE];

    listener = null;
    try {
        listener = new ServerSocket(27015);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        while (true) {
            Socket s = listener.accept();
            InputStream input = s.getInputStream();
            int nBufIndex = 0;
            int cnt = 0;
            while ((recvLen = input.read(buffer, nBufIndex, BUF_SIZE)) !=  -1) 
            {
                recvLen += nBufIndex;
                while (cnt < recvLen)
                {
                    if (buffer[cnt] == '*')
                    {
                        if (recvLen - cnt < HEADER_SIZE)
                        {
                            System.arraycopy(buffer, cnt, buffer, 0, recvLen-cnt);
                            nBufIndex = recvLen - cnt;
                            cnt = 0;
                            break;
                        }
                        cnt++;

                        filename = new String(buffer, cnt, FILENAME_LEN);
                        cnt += FILENAME_LEN;

                        nDataSize = CardUtility.byteToInt(buffer, cnt); 
                        cnt += 4;

                        if (cnt == recvLen) { // ó���� �����Ͱ� ���� �޽����� ũ�⿡ �����ϸ� -> ����� ���� ���
                            cnt = 0;
                            nBufIndex = 0;
                            break;
                        }                           
                    }

                    FileOutputStream fw = new FileOutputStream("..//SERVER//"+filename, true);
                    if (recvLen - cnt <= nDataSize)
                    {
                        fw.write(buffer, cnt, recvLen - cnt);
                        fw.close();
                        nDataSize -= (recvLen - cnt);

                        cnt = 0;
                        nBufIndex = 0;
                        break;
                    }
                    else 
                    {
                        fw.write(buffer, cnt, nDataSize);
                        fw.close();
                        cnt += nDataSize;
                        nDataSize = 0;                          
                    }
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    finally {
        try {
            listener.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
    }       
} 

}

black-tan commented 6 years ago

public class CardServerLauncher { public static void main(String[] args) throws IOException, InterruptedException { CardServer cardSever = new CardServer(); ValidatorReport report = new ValidatorReport(); Thread thread = new Thread(cardSever); thread.start();

    InputStream in = System.in;
    InputStreamReader reader = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(reader);
    String str;

    while (true)
    {
        str = br.readLine();

        if (str.equals("QUIT"))
        {
            cardSever.listener.close();
            thread.join();
            break;
        }
        else if (str.equals("REPORT"))
        {
            if (report.reportValidator())
                System.out.println("REPORT FINISH");
        }
        else {  // Date
            char cOption = 0;
            if (str.length() > 9)
            {
                cOption = str.charAt(9);
            }
            report.printReport(str.substring(0, 8), cOption);               
        }
    }           
}

}`

black-tan commented 6 years ago

public class ValidatorReport { public boolean reportValidator() throws IOException { HashMap<Integer, ReportVo> m;
String strToday = CardUtility.getCurrentDateString();

    m = new HashMap<Integer, ReportVo>();

    // File Find
    File directory = new File("..//SERVER");
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if(file.isFile() && file.getName().length() == 27 && file.getName().substring(9,17).equals(strToday)) {
            //System.out.println(file.getPath());
            analysisData(m, file.getPath());
        }
    }       

    // Save Report File
    saveReportFile(m, strToday);

    return true;
}    

private void analysisData(HashMap<Integer, ReportVo> m, String path) throws IOException
{       
    BufferedReader br = new BufferedReader(new FileReader(path));
    String line;
    while ((line = br.readLine()) != null) {
        //System.out.println(line);

        ReportVo userReport = new ReportVo();

        Integer key = Integer.parseInt(line.substring(5,8));

        if (m.get(key) == null) // insert key & value
        {
            userReport.setStrId(line.substring(0, 8));
            userReport.setCheckCard(1);
            if (line.charAt(49) == '1') {
                userReport.setFailCard(0);
            }
            else {
                userReport.setFailCard(1);
            }
            m.put(key, userReport);
        }
        else // just change value
        {
            m.get(key).increaseCheckCard();
            if (line.charAt(49) != '1') {
                m.get(key).increaseFailCard();
            }
        }
    }
    if(br != null) 
        br.close();
}

private void saveReportFile(HashMap<Integer, ReportVo> m, String strToday) throws IOException
{
    String filename;

    filename = "..//SERVER//REPORT_" + strToday + ".TXT";

    FileWriter fw = new FileWriter(filename,false);
    for( Integer key : m.keySet() ){
        //System.out.println( String.format("Ű : %s, �� : %s %d %d", key, m.get(key).getStrID(), m.get(key).getCheckCard(), m.get(key).getFailCard()) );
        fw.write(String.format("%s %d %d", m.get(key).getStrId(), m.get(key).getCheckCard(), m.get(key).getFailCard()) + "\n");
    }
    fw.close();        
}

public void printReport(String strDate, char option)
{
    ArrayList<ReportVo> reportList = new ArrayList<>();

    BufferedReader br;
    String line;
    try {
        br = new BufferedReader(new FileReader("..//SERVER//REPORT_"+strDate+".TXT"));
        while ((line = br.readLine()) != null) {
            //System.out.println(line);

            ReportVo userReport = new ReportVo();
            userReport.setStrId(line.split(" ")[0]);
            userReport.setCheckCard(Integer.parseInt(line.split(" ")[1]));
            userReport.setFailCard(Integer.parseInt(line.split(" ")[2]));

            reportList.add(userReport);
        }
        if(br != null) 
            br.close();         
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (option ==  'C')
    {
        Comparator<ReportVo> co = new Comparator<ReportVo>() {
            public int compare(ReportVo o1, ReportVo o2) {
                return (o2.getCheckCard() - o1.getCheckCard());
            }
        };
        Collections.sort(reportList, co);
    }

    for (int i=0; i<reportList.size(); i++)
    {
        System.out.println(String.format("%s %d %d",reportList.get(i).getStrId(),reportList.get(i).getCheckCard(), reportList.get(i).getFailCard()));
    }
}   

}

black-tan commented 6 years ago

public class CardUtility {
public static long hourDiff(String strTime2, String strTime1) throws ParseException { SimpleDateFormat transFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    java.util.Date date1 = transFormat.parse(strTime1);
    java.util.Date date2 = transFormat.parse(strTime2);

    long gap = date2.getTime() - date1.getTime();

    return gap/60/60/1000;
}

public static String passwordEncryption(String input) throws NoSuchAlgorithmException 
{
    MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
    byte[] result = mDigest.digest(input.getBytes());
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < result.length; i++) {
        sb.append(Integer.toString((result[i] & 0xFF) + 0x100, 16).substring(1).toUpperCase());
    }

    return sb.toString();
}   

public static void intToByte(byte [] buffer, int offset, int num)
{
    buffer[offset + 3] = (byte)(num >> 24);
    buffer[offset + 2] = (byte)(num >> 16);
    buffer[offset + 1] = (byte)(num >> 8);
    buffer[offset + 0] = (byte)(num);       
}       

public static int byteToInt(byte [] buffer, int offset)
{
    int nRet = ((((int)buffer[offset+3] & 0xff) << 24) |
            (((int)buffer[offset+2] & 0xff) << 16) |
            (((int)buffer[offset+1] & 0xff) << 8) |
            (((int)buffer[offset] & 0xff)));

    return nRet;
} 

public static String getCurrentDateTimeString()
{
    long time = System.currentTimeMillis(); 
    SimpleDateFormat dayTime = new SimpleDateFormat("yyyyMMddHHmmss");
    String strTime = dayTime.format(new Date(time));
    return strTime;
}

public static String getCurrentDateString()
{
    long time = System.currentTimeMillis(); 
    SimpleDateFormat today = new SimpleDateFormat("yyyyMMdd");
    String strToday = today.format(new Date(time));
    return strToday;
}

}