threadapp.Thread.java Source code

Java tutorial

Introduction

Here is the source code for threadapp.Thread.java

Source

/*
 * 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 threadapp;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Attr;

/**
 *
 * @author anthony
 */
public class Thread {
    public int id;
    public String title;
    public Post[] posts;

    private static String pathToThreads = "threads/";

    public Thread() {
        // find thread by id and construct
    }

    // Test Commit

    public static HashMap GetList() {
        HashMap threadList = new HashMap();

        File folder = new File(pathToThreads);
        File[] listOfFiles = folder.listFiles();
        Thread[] threads = new Thread[listOfFiles.length];

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                int id = Integer.parseInt(FilenameUtils.removeExtension(listOfFiles[i].getName()));
                Thread thread = FindById(id, false);
                threadList.put(id, thread.title);
            }
        }

        return threadList;
    }

    public static Thread FindById(int id, boolean getPosts) {
        Thread thread = new Thread();
        thread.id = id;
        String path = pathToThreads + getFilename(id);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(path);
            Element threadNode = (Element) doc.getElementsByTagName("thread").item(0);
            NodeList postList = threadNode.getElementsByTagName("post");

            thread.title = threadNode.getAttribute("title");

            if (getPosts) {
                thread.posts = Post.GetPostsFromList(postList);
            }

            return thread;

        } catch (ParserConfigurationException | SAXException | IOException ex) {
            Logger.getLogger(ThreadApp.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;

    }

    public void addPost(Post post) throws TransformerException {
        Post updatedPosts[] = new Post[this.posts.length + 1];

        //Move old posts to updated posts array
        for (int i = 0; i < this.posts.length; i++) {
            updatedPosts[i] = this.posts[i];
        }

        //Add new post to array;
        updatedPosts[this.posts.length] = post;
        this.posts = updatedPosts;

        //Update thread
        save();
    }

    private static String getFilename(int id) {
        return String.format("%03d", id) + ".xml";
    }

    public void save() throws TransformerException {
        // 1. Convert Thread object to XML
        // 2. Write to file

        try {

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // Add root element thread
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("thread");
            rootElement.setAttribute("title", this.title);
            doc.appendChild(rootElement);

            // Add post elements
            if (posts != null) {
                for (int i = 0; i < this.posts.length; i++) {
                    Element post = doc.createElement("post");
                    post.setAttribute("timestamp", Integer.toString(this.posts[i].timestamp));
                    post.appendChild(doc.createTextNode(this.posts[i].content));
                    rootElement.appendChild(post);
                }
            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("threads/" + getFilename(id)));

            // Output to console for testing
            //StreamResult result = new StreamResult(System.out);

            transformer.transform(source, result);

            System.out.println("File saved!");

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }

    }

}