private void deflate(String tmpDir, String path) { String tmpFile = "tmp-" + Utils.timestamp() + ".zip"; try { ZipFile zipFile = new ZipFile(tmpFile); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); parameters.setIncludeRootFolder(false); zipFile.addFolder(tmpDir, parameters); } catch (Exception e) { e.printStackTrace(); return; } File from = null; File to = null; try { File target = new File(path); if (target.exists()) FileUtils.forceDelete(target); from = new File(tmpFile); to = new File(path); FileUtils.moveFile(from, to); } catch (IOException e) { Utils.onError(new Error.FileMove(tmpFile, path)); } try { FileUtils.deleteDirectory(new File(tmpDir)); } catch (IOException e) { Utils.log("can't delete temporary folder"); } }
/** * Transforms the given XML file using the specified XSL file. * * @param origXmlFile The file containg the XML to transform * @param xslFile The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(File origXmlFile, File xslFile) { if (!origXmlFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null); return null; } if (!xslFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null); return null; } try { logger.logComment("The xslFile is " + xslFile + " *************"); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource xslFileSource = new StreamSource(xslFile); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null); return null; } }
/** * @param sourceFile File to read from * @return List of String objects with the shas */ public static FileRequestFileContent readRequestFile(final File sourceFile) { if (!sourceFile.isFile() || !(sourceFile.length() > 0)) { return null; } Document d = null; try { d = XMLTools.parseXmlFile(sourceFile.getPath()); } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception in readRequestFile, during XML parsing", t); return null; } if (d == null) { logger.log(Level.SEVERE, "Could'nt parse the request file"); return null; } final Element rootNode = d.getDocumentElement(); if (rootNode.getTagName().equals(TAG_FrostFileRequestFile) == false) { logger.severe( "Error: xml request file does not contain the root tag '" + TAG_FrostFileRequestFile + "'"); return null; } final String timeStampStr = XMLTools.getChildElementsTextValue(rootNode, TAG_timestamp); if (timeStampStr == null) { logger.severe("Error: xml file does not contain the tag '" + TAG_timestamp + "'"); return null; } final long timestamp = Long.parseLong(timeStampStr); final List<Element> nodelist = XMLTools.getChildElementsByTagName(rootNode, TAG_shaList); if (nodelist.size() != 1) { logger.severe("Error: xml request files must contain only one element '" + TAG_shaList + "'"); return null; } final Element rootShaNode = nodelist.get(0); final List<String> shaList = new LinkedList<String>(); final List<Element> xmlKeys = XMLTools.getChildElementsByTagName(rootShaNode, TAG_sha); for (final Element el : xmlKeys) { final Text txtname = (Text) el.getFirstChild(); if (txtname == null) { continue; } final String sha = txtname.getData(); shaList.add(sha); } final FileRequestFileContent content = new FileRequestFileContent(timestamp, shaList); return content; }
public static void main(final String[] args) { final File targetFile = new File("D:\\abc.def"); final File tmp = new File(targetFile.getPath() + ".frftmp"); if (!FileAccess.compressFileGZip(targetFile, tmp)) { return; // error } targetFile.delete(); tmp.renameTo(targetFile); }
public static Document getDocumentE(String filename) throws Exception { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException(filename); } Document doc = null; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); doc = docBuilder.parse(filename); return doc; }
public void apply(String path, String[] scripts) throws ParserConfigurationException, TransformerConfigurationException { File target = new File(path); if (target.isDirectory()) { String callerDir = this.targetDir; this.targetDir = path; for (String script : scripts) call(script); this.targetDir = callerDir; } else { String tmpDir = inflate(path); if (tmpDir == null) return; apply(tmpDir, scripts); deflate(tmpDir, path); } }
public void apply(String path, NodeList[] operations) throws ParserConfigurationException, TransformerConfigurationException { File target = new File(path); if (target.isDirectory()) { String callerDir = this.targetDir; this.targetDir = path; for (NodeList ops : operations) { for (int i = 0; i < ops.getLength(); i++) call(ops.item(i)); } this.targetDir = callerDir; } else { String tmpDir = inflate(path); if (tmpDir == null) return; apply(tmpDir, operations); deflate(tmpDir, path); } }
private void processDelete(Node operation) { String path = absolutePath(operation.getTextContent()); File target = new File(path); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } try { if (target.isDirectory()) { FileUtils.deleteDirectory(target); } else { FileUtils.forceDelete(target); } } catch (IOException ex) { Utils.onError(new Error.FileDelete(target.getPath())); } }
/** * EPML2PNML * * @param args String[] */ private static void EPML2PNML(String[] args) { if (args.length != 2) { System.out.println("���ṩEPML�ļ�·����PNML���Ŀ¼!"); System.exit(-1); } epmlImport epml = new epmlImport(); // load the single epml file String filename = args[0]; try { EPCResult epcRes = (EPCResult) epml.importFile(new FileInputStream(filename)); // convert all epc models to pnml files ArrayList<ConfigurableEPC> alEPCs = epcRes.getAllEPCs(); PnmlExport export = new PnmlExport(); for (ConfigurableEPC epc : alEPCs) { String id = epc.getIdentifier(); if (id.equals("1An_klol") || id.equals("1An_l1y8") || id.equals("1Ex_dzq9") || id.equals("1Ex_e6dx") || id.equals("1Ku_9soy") || id.equals("1Ku_a4cg") || id.equals("1Or_lojl") || id.equals("1Pr_d1ur") || id.equals("1Pr_djki") || id.equals("1Pr_dkfa") || id.equals("1Pr_dl73") || id.equals("1Ve_musj") || id.equals("1Ve_mvwz")) continue; // save pnml files to the same folder File outFile = new File(args[1] + "/" + id + ".pnml"); if (outFile.exists()) continue; FileOutputStream fos = new FileOutputStream(outFile); PetriNet petri = AMLtoPNML.convert(epc); try { export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos); } catch (Exception ex1) { ex1.printStackTrace(System.out); } } } catch (IOException ex) { ex.printStackTrace(System.out); } System.out.println("EPML Conversion Done"); }
private static InputSource getConfigSource(Class pAppClass) throws DataNotFoundException { URL resource = pAppClass.getResource(CONFIG_FILE_NAME); String resourceFileName = resource.toExternalForm(); File resourceFile = new File(resourceFileName); InputStream configResourceStream = pAppClass.getResourceAsStream(CONFIG_FILE_NAME); if (null == configResourceStream) { throw new DataNotFoundException( "unable to find XML configuration file resource: " + CONFIG_FILE_NAME + " for class: " + pAppClass.getName()); } InputSource inputSource = new InputSource(configResourceStream); if (!resourceFile.exists()) { inputSource.setSystemId(resourceFileName); } return (inputSource); }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
public ComposeImageTile(Sector sector, String mimeType, Level level, int width, int height) throws IOException { super(sector, level, -1, -1); // row and column aren't used and need to signal that this.width = width; this.height = height; this.file = File.createTempFile(WWIO.DELETE_ON_EXIT_PREFIX, WWIO.makeSuffixForMimeType(mimeType)); }
public static AppConfig get(Class pAppClass, String pAppDir) throws DataNotFoundException, InvalidInputException, FileNotFoundException { AppConfig appConfig = null; if (null == pAppDir) { // we don't know where we are installed, so punt and look for // the config file as a class resource: appConfig = new AppConfig(pAppClass); } else { File appDirFile = new File(pAppDir); if (!appDirFile.exists()) { throw new DataNotFoundException("could not find application directory: " + pAppDir); } String configFileName = appDirFile.getAbsolutePath() + "/config/" + AppConfig.CONFIG_FILE_NAME; appConfig = new AppConfig(new File(configFileName)); } return appConfig; }
protected void determineProjectName() throws ASExternalImporterException { String exceptionMessage = null; if (projectType == ProjectType.IPR) { // We are sure that determineProjectType() didn't throw exception, so iprFile is not null and // it represents *.ipr file projectName = iprFile.getName().replaceFirst("\\.ipr$", ""); } else if (projectType == ProjectType.IDEA) { File nameFile = new File(ideaDir.getPath(), ".name"); try { BufferedReader reader = new BufferedReader(new FileReader(nameFile)); String name = reader.readLine(); if (StringUtils.isWhitespace(name)) { exceptionMessage = ".name file in path " + nameFile.getPath() + " is empty"; } projectName = name.trim(); } catch (FileNotFoundException e) { exceptionMessage = "Cannot find .name file in path " + nameFile.getPath(); } catch (IOException e) { exceptionMessage = "Cannot read .name file in path " + nameFile.getPath(); } } else { // Actually unreachable (see setProject()) exceptionMessage = "Project type was not determined"; } if (exceptionMessage != null) { resetStateAndThrowException(exceptionMessage); } }
// ## operation Chemkin(double,double,String) public Chemkin(double p_rtol, double p_atol, String p_reactorType) { // #[ operation Chemkin(double,double,String) if (p_rtol < 0 || p_atol < 0) throw new InvalidChemkinParameterException("Negative rtol or atol!"); if (p_reactorType == null) throw new NullPointerException(); String dir = System.getProperty("RMG.workingDirectory"); // create the documentTypesDefinitions File docFile = new File("chemkin/documentTypeDefinitions"); docFile.mkdir(); copyFiles( dir + "/software/reactorModel/documentTypeDefinitions/reactorInput.dtd", "chemkin/documentTypeDefinitions/reactorInput.dtd"); copyFiles( dir + "/software/reactorModel/documentTypeDefinitions/reactorOutput.dtd", "chemkin/documentTypeDefinitions/reactorOutput.dtd"); rtol = p_rtol; atol = p_atol; reactorType = p_reactorType; }
private static void AML2PNML(String[] args) { if (args.length != 3) { System.out.println("���ṩAML����Ŀ¼��PNML���Ŀ¼�Լ��ֵ��ļ�!"); System.exit(-1); } System.out.println("����Ŀ¼��" + args[0]); System.out.println("���Ŀ¼��" + args[1]); System.out.println("�ֵ��ļ���" + args[2]); // load the dict AMLtoPNML.loadDict(args[2]); File srcDir = new File(args[0]); File[] lstAML = srcDir.listFiles(); PnmlExport export = new PnmlExport(); for (int i = 0; i < lstAML.length; i++) { if (lstAML[i].isDirectory()) { continue; } System.out.print(lstAML[i].getName() + "==>"); try { FileInputStream fis = new FileInputStream(lstAML[i]); int idx = lstAML[i].getName().indexOf(".xml"); File outFile = new File(args[1] + "/" + lstAML[i].getName().substring(0, idx) + ".pnml"); FileOutputStream fos = new FileOutputStream(outFile); EPCResult epcRes = (EPCResult) AMLtoPNML.importFile(fis); ConfigurableEPC epc = epcRes.getMainEPC(); PetriNet petri = AMLtoPNML.convert(epc); export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos); System.out.println(outFile.getName()); } catch (FileNotFoundException ex) { ex.printStackTrace(System.out); } catch (IOException ioe) { ioe.printStackTrace(System.out); } catch (Exception e) { e.printStackTrace(System.out); } } System.out.println("Conversion Done"); }
/** * Transforms the given XML string using the specified XSL file. * * @param xmlString The String containg the XML to transform * @param xslFile The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(String xmlString, File xslFile) { if (!xslFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null); return null; } String shortString = new String(xmlString); if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "..."; try { logger.logComment("The xslFile is " + xslFile.getAbsolutePath() + " *************"); TransformerFactory tFactory = TransformerFactory.newInstance(); logger.logComment("Transforming string: " + shortString); StreamSource xslFileSource = new StreamSource(xslFile); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); String shortResult = writer.toString(); if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "..."; logger.logComment("Result: " + shortResult); return writer.toString(); } catch (TransformerException e) { GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null); return null; } }
public void getFilesFromFolder(List filesAndFolders, String savePath) { // create a File object for the parent directory File downloadsDirectory = new File(savePath); // create the folder if needed. downloadsDirectory.mkdir(); for (int i = 0; i < filesAndFolders.size(); i++) { Object links = filesAndFolders.get(i); List linksArray = (ArrayList) links; if (i == 0) { for (int j = 0; j < linksArray.size(); j += 2) { // We've got an array of file urls so download each one to a directory with the folder // name String fileURL = linksArray.get(j).toString(); String fileName = linksArray.get(j + 1).toString(); downloadFile(fileURL, savePath, fileName); progress++; Message msg = mHandler.obtainMessage(); msg.arg1 = progress; mHandler.sendMessage(msg); } } else if (i == 1) { // we've got an array of folders so recurse down the levels, extracting subfolders and files // until we've downloaded everything. for (int j = 0; j < linksArray.size(); j += 2) { String folderURL = linksArray.get(j).toString(); String folderName = linksArray.get(j + 1).toString(); String page = getData(folderURL); List newFilesAndFolders = parsePage(page); String dlDirPath = savePath + folderName + "/"; getFilesFromFolder(newFilesAndFolders, dlDirPath); } } } }
/** * opens existing file * * @param a_file */ public GlyphFile(File a_file) { super(); m_fileName = a_file; URL url = null; try { url = a_file.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } init(url); }
private Element getTopLevelElement(File file) throws ASExternalImporterException { BufferedReader reader; try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { throw new ASExternalImporterException("Cannot find " + file.getPath()); } DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); Document doc; try { doc = fact.newDocumentBuilder().parse(new InputSource(reader)); } catch (Exception e) { throw new ASExternalImporterException("Corrupted file: " + file.getPath()); } Element el = doc.getDocumentElement(); if (el == null) { throw new ASExternalImporterException("Corrupted file: " + file.getPath()); } return el; }
@Override protected void addRunConfigurations() { runConfigurations.clear(); // Shared configurations if (projectType == ProjectType.IDEA) { File runConfigDir = new File(ideaDir.getPath() + "/runConfigurations"); if (runConfigDir.isDirectory()) { String[] runConfigurationNames = runConfigDir.list( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); for (String s : runConfigurationNames) { try { runConfigurations.add(new ASIdeaRunConfiguration(runConfigDir.getPath() + "/" + s)); } catch (ASExternalImporterException e) { // Ignore } } } } else if (projectType == ProjectType.IPR) { Element iprTop; try { iprTop = getTopLevelElement(iprFile); } catch (ASExternalImporterException e) { return; } addRunConfigurationFromXMLTree(iprTop, "ProjectRunConfigurationManager"); } // Non-shared configurations Element workspaceTop; try { if (projectType == ProjectType.IDEA) { workspaceTop = getTopLevelElement(new File(ideaDir.getPath() + File.separator + "workspace.xml")); } else if (projectType == ProjectType.IPR) { workspaceTop = getTopLevelElement(iwsFile); } else { // O_o return; } } catch (ASExternalImporterException e) { return; } addRunConfigurationFromXMLTree(workspaceTop, "RunManager"); }
private void determineProjectType() throws ASExternalImporterException { File dir = new File(projectPath); File[] files = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".ipr"); } }); if (files != null && files.length > 0) { iprFile = files[0]; projectType = ProjectType.IPR; File iws = new File(projectPath, iprFile.getName().replaceFirst("\\.ipr$", ".iws")); if (!iws.exists()) { resetStateAndThrowException( "Cannot find " + iws.getName() + " file in path " + projectPath); } iwsFile = iws; return; } files = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.equals(".idea"); } }); if (files != null && files.length > 0) { ideaDir = files[0]; projectType = ProjectType.IDEA; return; } // If neither *.ipr file, nor .idea directory is found resetStateAndThrowException( "Cannot find neither *.ipr file, nor .idea directory in path " + projectPath); }
private void processCopy(Node operation) { List<Node> fromNode = getChildNodes(operation, "from"); List<Node> toNode = getChildNodes(operation, "to"); if (fromNode.isEmpty() || toNode.isEmpty()) { return; } String path = fromNode.get(0).getTextContent(); String fromPath = (new File(path).isAbsolute()) ? path : absolutePath(path); String toPath = absolutePath(toNode.get(0).getTextContent()); Boolean copyContents = fromPath.endsWith(File.separator + "*"); File from = new File((copyContents) ? fromPath.substring(0, fromPath.length() - 2) : fromPath); File to = new File(toPath); if (!from.exists()) { Utils.onError(new Error.FileNotFound(from.getPath())); return; } try { if (copyContents) { FileUtils.forceMkdir(to); FileUtils.copyDirectory(from, to); } else if (from.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyDirectoryToDirectory(from, to); } else { if (to.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyFileToDirectory(from, to); } else { File toDir = new File(Utils.getParentDir(to)); FileUtils.forceMkdir(toDir); FileUtils.copyFile(from, to); } } } catch (IOException ex) { Utils.onError(new Error.FileCopy(from.getPath(), to.getPath())); } }
protected void locateModules() throws ASExternalImporterException { modules.clear(); File f; String fDescription; // Both .ipr and modules.xml files have the same structure if (projectType == ProjectType.IPR) { f = iprFile; fDescription = "project"; } else if (projectType == ProjectType.IDEA) { f = new File(ideaDir.getPath() + File.separator + "modules.xml"); fDescription = "modules"; } else { // Unreachable throw new ASExternalImporterException("Project type was not determined"); } BufferedReader reader; try { reader = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { // Unreachable throw new ASExternalImporterException("Cannot find " + fDescription + " file " + f.getPath()); } DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); Document doc; try { doc = fact.newDocumentBuilder().parse(new InputSource(reader)); } catch (Exception e) { throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath()); } Element el = doc.getDocumentElement(); if (el == null) { throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath()); } NodeList list = el.getChildNodes(); Node moduleNode = null; for (int i = 0; i < list.getLength(); i++) { NamedNodeMap nodeMap = list.item(i).getAttributes(); if (nodeMap != null && nodeMap.getNamedItem("name") != null) { if ("ProjectModuleManager".equals(nodeMap.getNamedItem("name").getNodeValue())) { moduleNode = list.item(i); break; } } } if (moduleNode == null) { throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath()); } NodeList moduleNodeList = null; for (int i = 0; i < moduleNode.getChildNodes().getLength(); i++) { if ("modules".equals(moduleNode.getChildNodes().item(i).getNodeName())) { moduleNodeList = moduleNode.getChildNodes().item(i).getChildNodes(); break; } } if (moduleNodeList == null) { throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath()); } for (int i = 0; i < moduleNodeList.getLength(); i++) { NamedNodeMap nodeMap = moduleNodeList.item(i).getAttributes(); if (nodeMap != null && nodeMap.getNamedItem("filepath") != null) { modules.add( new ASIdeaModule( nodeMap .getNamedItem("filepath") .getNodeValue() .replace("$PROJECT_DIR$", projectPath))); } } resolveModuleDependencies(); }
/** * Initializes the <code>TextTransition</code> by the File <code>file</code>. * * @param file * @exception IOException * @exception SAXException * @exception ParserConfigurationException */ public void setup(File file) throws IOException, SAXException, ParserConfigurationException { setup(file.toURL()); }
public void setFile(File file) { elt.setAttribute("file", file.getPath()); }
// ----------------------------------------------------- // Description: Determine if a template exists for the // given file and return true on success. // ----------------------------------------------------- boolean templateExistFor(String fileName, String destinationDirectory) { templateIdentified = false; // from template int intOriginX = 0; int intOriginY = 0; // from template int intX = 0; int intY = 0; int intWidth = 0; int intHeight = 0; // calculated int viaTemplateX = 0; int viaTemplateY = 0; int viaTemplatePlusWidth = 0; int viaTemplatePlusHeight = 0; String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.')); String pathPlusFileName_woext = destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext; try { File folder = new File(templateLocation); File[] listOfFiles = folder.listFiles(); long startTime = System.currentTimeMillis(); for (File file : listOfFiles) { if (file.isFile()) { templateName = ""; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("condition"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String myX = getTagValue("x", eElement); String myY = getTagValue("y", eElement); String myWidth = getTagValue("width", eElement); String myHeight = getTagValue("height", eElement); String mySuffix = getTagValue("suffix", eElement); String myRequirements = getTagValue("required", eElement); intX = Integer.parseInt(myX); intY = Integer.parseInt(myY); intWidth = Integer.parseInt(myWidth); intHeight = Integer.parseInt(myHeight); viaTemplateX = intX - (intOriginX - pageX); viaTemplateY = intY - (intOriginY - pageY); viaTemplatePlusWidth = viaTemplateX + intWidth; viaTemplatePlusHeight = viaTemplateY + intHeight; Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-crop", String.format("%dx%d+%d+%d", intWidth, intHeight, viaTemplateX, viaTemplateY), "+repage", pathPlusFileName_woext + "_" + mySuffix + ".png"); Spawn.execute( Settings.Programs.CONVERT.path(), pathPlusFileName_woext + "_trim.png", "-fill", "none", "-stroke", "red", "-strokewidth", "3", "-draw", String.format( "rectangle %d,%d %d,%d", viaTemplateX, viaTemplateY, viaTemplatePlusWidth, viaTemplatePlusHeight), "+repage", pathPlusFileName_woext + "_draw.png"); Spawn.execute( Settings.Programs.TESSERACT.path(), pathPlusFileName_woext + "_" + mySuffix + ".png", pathPlusFileName_woext + "_" + mySuffix); String line = ""; // String that holds current file line String accumulate = ""; try { FileReader input = new FileReader(pathPlusFileName_woext + "_" + mySuffix + ".txt"); BufferedReader bufRead = new BufferedReader(input); line = bufRead.readLine(); while (line != null) { accumulate += line; line = bufRead.readLine(); } bufRead.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } String[] requirements = myRequirements.split("#"); for (String requirement : requirements) { if (requirement.equals(accumulate.trim())) { templateName = file.getName(); templateIdentified = true; return templateIdentified; } } } } } } // record end time long endTime = System.currentTimeMillis(); System.out.println( "Template Search [" + fileName + "] " + (endTime - startTime) / 1000 + " seconds"); } catch (Exception e) { e.printStackTrace(); } return templateIdentified; }
/** * XML Circuit constructor * * @param file the file that contains the XML description of the circuit * @param g the graphics that will paint the node * @throws CircuitLoadingException if the internal circuit can not be loaded */ public CircuitUI(File file, Graphics g) throws CircuitLoadingException { this(""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc; Element root; Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>(); try { builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException sxe) { throw new CircuitLoadingException("SAX exception raised, invalid XML file."); } catch (ParserConfigurationException pce) { throw new CircuitLoadingException( "Parser exception raised, parser configuration is invalid."); } catch (IOException ioe) { throw new CircuitLoadingException("I/O exception, file cannot be loaded."); } root = (Element) doc.getElementsByTagName("Circuit").item(0); this.setName(root.getAttribute("name")); NodeList nl = root.getElementsByTagName("Node"); Element e; Node n; Class cl; for (int i = 0; i < nl.getLength(); ++i) { e = (Element) nl.item(i); try { cl = Class.forName(e.getAttribute("class")); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } try { n = ((Node) cl.newInstance()); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } this.nodes.add(n); n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y"))); if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name")); if (n instanceof giraffe.ui.CompositeNode) { try { ((CompositeNode) n) .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g); } catch (Exception exc) { /* try to load from the lib */ ((CompositeNode) n) .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g); } } NodeList nlist = e.getElementsByTagName("Anchor"); Element el; for (int j = 0; j < nlist.getLength(); ++j) { el = (Element) nlist.item(j); Anchor a = n.getAnchor(new Integer(el.getAttribute("id"))); NodeList linklist = el.getElementsByTagName("Link"); Element link; Link l; for (int k = 0; k < linklist.getLength(); ++k) { link = (Element) linklist.item(k); int id = new Integer(link.getAttribute("id")); int index = new Integer(link.getAttribute("index")); if (id >= this.linkID) linkID = id + 1; if (linkstable.containsKey(id)) { l = linkstable.get(id); l.addLinkedAnchorAt(a, index); a.addLink(l); } else { l = new Link(id); l.addLinkedAnchorAt(a, index); this.links.add(l); linkstable.put(id, l); a.addLink(l); } } } } }
public String getShortFileName() { return m_fileName.getName(); }
private void processTxt(Node operation) { List<Node> targets = getChildNodes(operation, "target"); List<Node> optionNodes = getChildNodes(operation, "opt"); List<Node> separatorNode = getChildNodes(operation, "separator"); if (targets.isEmpty() || optionNodes.isEmpty()) { return; } String defaultSeparator = "="; String globalSeparator = defaultSeparator; if (!separatorNode.isEmpty()) { globalSeparator = separatorNode.get(0).getTextContent(); if (globalSeparator.length() != 1) { globalSeparator = defaultSeparator; } } Map<String, String> options = new HashMap<String, String>(); Map<String, String> processedOptions = new HashMap<String, String>(); for (int i = 0; i < optionNodes.size(); i++) { Node option = optionNodes.get(i); String name = option.getAttributes().getNamedItem("name").getNodeValue(); String value = option.getTextContent(); if (options.containsKey(name)) { options.remove(name); } options.put(name, value); } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); File tmpFile = new File(Utils.timestamp()); BufferedWriter bw = null; BufferedReader br = null; try { Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator"); String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue(); if (separator.length() != 1) { separator = globalSeparator; } bw = new BufferedWriter(new FileWriter(tmpFile)); if (target.exists()) { br = new BufferedReader(new FileReader(target)); for (String line; (line = br.readLine()) != null; ) { String[] parts = line.split(separator); if (parts.length < 2) { bw.write(line); bw.newLine(); continue; } String optName = parts[0].trim(); if (options.containsKey(optName)) { String optValue = options.get(optName); bw.write(optName + " " + separator + " " + optValue); bw.newLine(); processedOptions.put(optName, optValue); options.remove(optName); } else if (processedOptions.containsKey(optName)) { bw.write(optName + " " + separator + " " + processedOptions.get(optName)); bw.newLine(); } else { bw.write(line); bw.newLine(); } } br.close(); } for (Map.Entry<String, String> entry : options.entrySet()) { bw.write(entry.getKey() + " " + separator + " " + entry.getValue()); bw.newLine(); } bw.close(); FileUtils.copyFile(tmpFile, target); FileUtils.forceDelete(tmpFile); } catch (IOException ex) { Utils.onError(new Error.WriteTxtConfig(target.getPath())); } } }