Java tutorial
/* * Copyright 2010 Nikita Kuklev. * * This file is part of LPServer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ package ca.uviccscu.lp.utils; import ca.uviccscu.lp.shared.Shared; import java.io.IOException; import java.io.StringWriter; 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.Node; import org.w3c.dom.Text; import java.io.File; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.Priority; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.NodeList; import static org.w3c.dom.Node.ATTRIBUTE_NODE; import static org.w3c.dom.Node.CDATA_SECTION_NODE; import static org.w3c.dom.Node.COMMENT_NODE; import static org.w3c.dom.Node.DOCUMENT_TYPE_NODE; import static org.w3c.dom.Node.ELEMENT_NODE; import static org.w3c.dom.Node.ENTITY_NODE; import static org.w3c.dom.Node.ENTITY_REFERENCE_NODE; import static org.w3c.dom.Node.NOTATION_NODE; import static org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE; import static org.w3c.dom.Node.TEXT_NODE; /** * * @author Nikita Kuklev <nikkuk@hotmail.com> * @since 2010-09-01 16:57:29 -0800 */ public class Utils { static Logger l = Logger.getLogger(Utils.class.getName()); public static void netLogger(String msg) { l.info("Communication notice: " + msg); } public static void netLogger(String msg, Level level) { l.log(Priority.INFO, "Communication notice: " + msg); } public static void netExceptionLogger(Exception ex) { l.error("Communication exception occured", ex); } public static void netExceptionLogger(Throwable ex) { l.error("Communication exception occured", ex); } public static void netExceptionLogger(String msg) { l.error("Communication exception notice: " + msg); } public static void setupLogger(String msg) { l.info("Communication notice: " + msg); } public static void setupExceptionLogger(Exception ex) { l.error("Communication exception occured", ex); } public static void setupExceptionLogger(String msg) { l.error("Communication exception notice: " + msg); } public static String concatenatePaths(String[] ar) { StringBuilder sb = new StringBuilder(); sb.append(ar[0]); for (int i = 1; i < ar.length; i++) { sb.append(File.separator); sb.append(sb); } sb.append(File.separator); l.trace("String concatenated: " + sb.toString()); return sb.toString(); } @Deprecated public static boolean checkDir(File f) { l.trace("Checking dir: " + f.getAbsolutePath()); try { boolean a = f.isDirectory(); if (a) { if (f.listFiles().length != 0) { l.error("Directory not empty"); //JDialog jd = new JDialog((JFrame) null, true); int resp = JOptionPane.showConfirmDialog(null, "Directory nonempty: " + f.getAbsolutePath() + ". Proceed? (will wipe)", "Confirm deletion", JOptionPane.YES_NO_OPTION); if (resp == JOptionPane.YES_OPTION) { FileUtils.deleteDirectory(f); } else { l.fatal("Delete denied"); System.exit(1); } } } FileUtils.forceMkdir(f); File test = new File(f.getAbsolutePath() + File.separator + "test.file"); boolean c = test.createNewFile(); return c; } catch (Exception e) { l.fatal("Az directory creation error", e); return false; } } public static void cleanupDir() throws IOException { FileUtils.forceDelete(new File(Shared.workingDirectory)); //FileUtils.deleteDirectory(new File(Shared.workingDirectory)); //FileUtils.forceDeleteOnExit(new File(Shared.workingDirectory)); //File f = new File(Shared.workingDirectory); //f.deleteOnExit(); } private static String nodeType(short type) { switch (type) { case ELEMENT_NODE: return "Element"; case DOCUMENT_TYPE_NODE: return "Document type"; case ENTITY_NODE: return "Entity"; case ENTITY_REFERENCE_NODE: return "Entity reference"; case NOTATION_NODE: return "Notation"; case TEXT_NODE: return "Text"; case COMMENT_NODE: return "Comment"; case CDATA_SECTION_NODE: return "CDATA Section"; case ATTRIBUTE_NODE: return "Attribute"; case PROCESSING_INSTRUCTION_NODE: return "Attribute"; } return "Unidentified"; } private static String xmlString = "<?xml version=\"1.0\"?>" + " <!DOCTYPE address" + " [" + " <!ELEMENT address (buildingnumber, street, city, state, zip)>" + " <!ATTLIST address xmlns CDATA #IMPLIED>" + " <!ELEMENT buildingnumber (#PCDATA)>" + " <!ELEMENT street (#PCDATA)>" + " <!ELEMENT city (#PCDATA)>" + " <!ELEMENT state (#PCDATA)>" + " <!ELEMENT zip (#PCDATA)>" + " ]>" + "" + " <address>" + " <buildingnumber> 29 </buildingnumber>" + " <street> South Street</street>" + " <city>Vancouver</city>" + "" + " <state>BC</state>" + " <zip>V6V 4U7</zip>" + " </address>"; public static String readOutDomTree(Document d) { StringBuilder sb = new StringBuilder(); Document xmlDoc = d; DocumentType doctype = xmlDoc.getDoctype(); if (doctype == null) { sb.append("\n"); sb.append("DOCTYPE is null"); sb.append("\n"); } else { sb.append("DOCTYPE node:\n" + doctype.getInternalSubset()); sb.append("\n"); } sb.append("\nDocument body contents are:"); sb.append("\n"); listNodes(xmlDoc.getDocumentElement(), "", sb); // Root element & children return sb.toString(); } private static void listNodes(Node node, String indent, StringBuilder sb) { String nodeName = node.getNodeName(); sb.append(indent + " Node: " + nodeName); sb.append("\n"); short type = node.getNodeType(); sb.append(indent + " Node Type: " + nodeType(type)); sb.append("\n"); if (type == TEXT_NODE) { sb.append(indent + " Content is: " + ((Text) node).getWholeText()); sb.append("\n"); } NodeList list = node.getChildNodes(); if (list.getLength() > 0) { sb.append(indent + " Child Nodes of " + nodeName + " are:"); sb.append("\n"); for (int i = 0; i < list.getLength(); i++) { listNodes(list.item(i), indent + " ", sb); } } } public static String documentToString(Document d) throws TransformerConfigurationException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(d); transformer.transform(source, result); String str = result.getWriter().toString(); return str; } }