/** * Performs an XPATH lookup in an xml document whose filename is specified by the first parameter * (assumed to be in the auxiliary subdirectory) The XPATH expression is supplied as the second * string parameter The return value is of type string e.g. this is currently used primarily for * looking up the Company Prefix Index for encoding a GS1 Company Prefix into a 64-bit EPC tag */ private String xpathlookup(String xml, String expression) { try { // Parse the XML as a W3C document. DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File(xmldir + File.separator + "auxiliary" + File.separator + xml)); XPath xpath = XPathFactory.newInstance().newXPath(); String rv = (String) xpath.evaluate(expression, document, XPathConstants.STRING); return rv; } catch (ParserConfigurationException e) { System.err.println("ParserConfigurationException caught..."); e.printStackTrace(); return null; } catch (XPathExpressionException e) { System.err.println("XPathExpressionException caught..."); e.printStackTrace(); return null; } catch (SAXException e) { System.err.println("SAXException caught..."); e.printStackTrace(); return null; } catch (IOException e) { System.err.println("IOException caught..."); e.printStackTrace(); return null; } }
/** * Create an Archival Unit * * @return true If successful */ private boolean createAu() { Configuration config = getAuConfigFromForm(); AuProxy au; Element element; try { au = getRemoteApi().createAndSaveAuConfiguration(getPlugin(), config); } catch (ArchivalUnit.ConfigurationException exception) { return error("Configuration failed: " + exception.getMessage()); } catch (IOException exception) { return error("Unable to save configuration: " + exception.getMessage()); } /* * Successful creation - add the AU name and ID to the response document */ element = getXmlUtils().createElement(getResponseRoot(), AP_E_AU); XmlUtils.addText(element, au.getName()); element = getXmlUtils().createElement(getResponseRoot(), AP_E_AUID); XmlUtils.addText(element, au.getAuId()); return true; }
public void write(SecureItemTable tbl, char[] password) throws IOException { OutputStream os = new FileOutputStream(file); OutputStream xmlout; if (password.length == 0) { xmlout = os; os = null; } else { PBEKeySpec keyspec = new PBEKeySpec(password); Cipher c; try { SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = fac.generateSecret(keyspec); c = Cipher.getInstance("PBEWithMD5AndDES"); c.init(Cipher.ENCRYPT_MODE, key, pbeSpec); } catch (java.security.GeneralSecurityException exc) { os.close(); IOException ioe = new IOException("Security exception during write"); ioe.initCause(exc); throw ioe; } CipherOutputStream out = new CipherOutputStream(os, c); xmlout = out; } try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource src = new DOMSource(tbl.getDocument()); StringWriter writer = new StringWriter(); StreamResult sr = new StreamResult(writer); t.transform(src, sr); OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8); osw.write(writer.toString()); osw.close(); } catch (Exception exc) { IOException ioe = new IOException("Unable to serialize XML"); ioe.initCause(exc); throw ioe; } finally { xmlout.close(); if (os != null) os.close(); } tbl.setDirty(false); return; }
public void save() throws IOException { synchronized (this) { FileWriter fw = null; try { fw = new FileWriter(file); fw.write(toString()); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static void loadDict(String strDict) { try { BufferedReader br = new BufferedReader(new FileReader(strDict)); String line = null; while ((line = br.readLine()) != null) { int idx = line.indexOf(','); if (idx > 0) { htDict.put(line.substring(0, idx), line.substring(idx + 1)); } } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(System.out); } catch (IOException ioe) { ioe.printStackTrace(System.out); } }
public void toSave() { try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter(new FileOutputStream(filename)); StreamResult result = new StreamResult(pw); transformer.transform(source, result); } catch (TransformerException mye) { mye.printStackTrace(); } catch (IOException exp) { exp.printStackTrace(); } }
/** * 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 void copyFiles(String string, String string2) { File src = new File(string); File dest = new File(string2); FileInputStream fin; try { fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Carica un file XML e ne restituisce un riferimento per DOM * * @param path - path to xml file * @return reference to xml document */ private static Document loadDocument(String path) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(false); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(new File(path)); return d; } catch (ParserConfigurationException ex) { ex.printStackTrace(); System.exit(10); } catch (SAXException sxe) { sxe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return null; }
void reloadJTree(String url) { System.out.println("reload " + url); Document dom; try { URL uurl = new URL(url); HTMLWrapper hw = new HTMLWrapper(url); dom = hw.getDOM(); } catch (IOException e) { e.printStackTrace(); try { dom = HTML2DOM.getDOM(new FileInputStream(url)); } catch (IOException ie) { JOptionPane.showMessageDialog(this, "can't get document of the url: " + url); ie.printStackTrace(); return; } } document = dom; jtree.setRootNode(dom); }
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"); }
public static void main(String[] args) throws InvalidConfigurationException { // Reading data from xml try { new InputData().readFromFile(XML_TEST_FILENAME); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } // Configuration conf = new DefaultConfiguration(); Configuration conf = new Configuration("myconf"); TimetableFitnessFunction fitnessFunction = new TimetableFitnessFunction(); InitialConstraintChecker timetableConstraintChecker = new InitialConstraintChecker(); // Creating genes Gene[] testGenes = new Gene[CHROMOSOME_SIZE]; for (int i = 0; i < CHROMOSOME_SIZE; i++) { testGenes[i] = new GroupClassTeacherLessonTimeSG( conf, new Gene[] { new GroupGene(conf, 1), new ClassGene(conf, 1), new TeacherGene(conf, 1), new LessonGene(conf, 1), new TimeGene(conf, 1) }); } System.out.println("=================================="); // Creating chromosome Chromosome testChromosome; testChromosome = new Chromosome(conf, testGenes); testChromosome.setConstraintChecker(timetableConstraintChecker); // Setup configuration conf.setSampleChromosome(testChromosome); conf.setPopulationSize(POPULATION_SIZE); conf.setFitnessFunction(fitnessFunction); // add fitness function BestChromosomesSelector myBestChromosomesSelector = new BestChromosomesSelector(conf); conf.addNaturalSelector(myBestChromosomesSelector, false); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); CrossoverOperator myCrossoverOperator = new CrossoverOperator(conf); conf.addGeneticOperator(myCrossoverOperator); TimetableMutationOperator myMutationOperator = new TimetableMutationOperator(conf); conf.addGeneticOperator(myMutationOperator); conf.setKeepPopulationSizeConstant(false); // Creating genotype // Population pop = new Population(conf, testChromosome); // Genotype population = new Genotype(conf, pop); Genotype population = Genotype.randomInitialGenotype(conf); System.out.println("Our Chromosome: \n " + testChromosome.getConfiguration().toString()); System.out.println("------------evolution-----------------------------"); // Begin evolution Calendar cal = Calendar.getInstance(); start_t = cal.getTimeInMillis(); for (int i = 0; i < MAX_EVOLUTIONS; i++) { System.out.println( "generation#: " + i + " population size:" + (Integer) population.getPopulation().size()); if (population.getFittestChromosome().getFitnessValue() >= THRESHOLD) break; population.evolve(); } cal = Calendar.getInstance(); finish_t = cal.getTimeInMillis(); System.out.println("--------------end of evolution--------------------"); Chromosome fittestChromosome = (Chromosome) population.getFittestChromosome(); System.out.println( "-------------The best chromosome---fitness=" + fittestChromosome.getFitnessValue() + "---"); System.out.println(" Group Class Time"); for (int i = 0; i < CHROMOSOME_SIZE; i++) { GroupClassTeacherLessonTimeSG s = (GroupClassTeacherLessonTimeSG) fittestChromosome.getGene(i); System.out.println( "Gene " + i + " contains: " + (Integer) s.geneAt(GROUP).getAllele() + " " + (Integer) s.geneAt(CLASS).getAllele() + " " + (Integer) s.geneAt(TEACHER).getAllele() + " " + (Integer) s.geneAt(LESSON).getAllele() + " " + (Integer) s.geneAt(TIME).getAllele()); // GroupGene gg = (GroupGene)s.geneAt(GROUP); // System.out.println("gg's idGroup"+gg.getAllele()+" gg.getGroupSize()"+ gg.getGroupSize() ); } System.out.println("Elapsed time:" + (double) (finish_t - start_t) / 1000 + "s"); // Display the best solution OutputData od = new OutputData(); od.printToConsole(fittestChromosome); // Write population to the disk try { od.printToFile(population, GENOTYPE_FILENAME, BEST_CHROMOSOME_FILENAME); } catch (IOException e) { System.out.println("IOException raised! " + e.getMessage()); } }
public void build_bricks() { ImagePlus imp; ImagePlus orgimp; ImageStack stack; FileInfo finfo; if (lvImgTitle.isEmpty()) return; orgimp = WindowManager.getImage(lvImgTitle.get(0)); imp = orgimp; finfo = imp.getFileInfo(); if (finfo == null) return; int[] dims = imp.getDimensions(); int imageW = dims[0]; int imageH = dims[1]; int nCh = dims[2]; int imageD = dims[3]; int nFrame = dims[4]; int bdepth = imp.getBitDepth(); double xspc = finfo.pixelWidth; double yspc = finfo.pixelHeight; double zspc = finfo.pixelDepth; double z_aspect = Math.max(xspc, yspc) / zspc; int orgW = imageW; int orgH = imageH; int orgD = imageD; double orgxspc = xspc; double orgyspc = yspc; double orgzspc = zspc; lv = lvImgTitle.size(); if (filetype == "JPEG") { for (int l = 0; l < lv; l++) { if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) { IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE"); return; } } } // calculate levels /* int baseXY = 256; int baseZ = 256; if (z_aspect < 0.5) baseZ = 128; if (z_aspect > 2.0) baseXY = 128; if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect); if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect); IJ.log("Z_aspect: " + z_aspect); IJ.log("BaseXY: " + baseXY); IJ.log("BaseZ: " + baseZ); */ int baseXY = 256; int baseZ = 128; int dbXY = Math.max(orgW, orgH) / baseXY; if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2; int dbZ = orgD / baseZ; if (orgD % baseZ > 0) dbZ *= 2; lv = Math.max(log2(dbXY), log2(dbZ)) + 1; int ww = orgW; int hh = orgH; int dd = orgD; for (int l = 0; l < lv; l++) { int bwnum = ww / baseXY; if (ww % baseXY > 0) bwnum++; int bhnum = hh / baseXY; if (hh % baseXY > 0) bhnum++; int bdnum = dd / baseZ; if (dd % baseZ > 0) bdnum++; if (bwnum % 2 == 0) bwnum++; if (bhnum % 2 == 0) bhnum++; if (bdnum % 2 == 0) bdnum++; int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0); int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0); int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0); bwlist.add(bw); bhlist.add(bh); bdlist.add(bd); IJ.log("LEVEL: " + l); IJ.log(" width: " + ww); IJ.log(" hight: " + hh); IJ.log(" depth: " + dd); IJ.log(" bw: " + bw); IJ.log(" bh: " + bh); IJ.log(" bd: " + bd); int xyl2 = Math.max(ww, hh) / baseXY; if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2; if (lv - 1 - log2(xyl2) <= l) { ww /= 2; hh /= 2; } IJ.log(" xyl2: " + (lv - 1 - log2(xyl2))); int zl2 = dd / baseZ; if (dd % baseZ > 0) zl2 *= 2; if (lv - 1 - log2(zl2) <= l) dd /= 2; IJ.log(" zl2: " + (lv - 1 - log2(zl2))); if (l < lv - 1) { lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1)); IJ.selectWindow(lvImgTitle.get(0)); IJ.run( "Scale...", "x=- y=- z=- width=" + ww + " height=" + hh + " depth=" + dd + " interpolation=Bicubic average process create title=" + lvImgTitle.get(l + 1)); } } for (int l = 0; l < lv; l++) { IJ.log(lvImgTitle.get(l)); } Document doc = newXMLDocument(); Element root = doc.createElement("BRK"); root.setAttribute("version", "1.0"); root.setAttribute("nLevel", String.valueOf(lv)); root.setAttribute("nChannel", String.valueOf(nCh)); root.setAttribute("nFrame", String.valueOf(nFrame)); doc.appendChild(root); for (int l = 0; l < lv; l++) { IJ.showProgress(0.0); int[] dims2 = imp.getDimensions(); IJ.log( "W: " + String.valueOf(dims2[0]) + " H: " + String.valueOf(dims2[1]) + " C: " + String.valueOf(dims2[2]) + " D: " + String.valueOf(dims2[3]) + " T: " + String.valueOf(dims2[4]) + " b: " + String.valueOf(bdepth)); bw = bwlist.get(l).intValue(); bh = bhlist.get(l).intValue(); bd = bdlist.get(l).intValue(); boolean force_pow2 = false; /* if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true; if(force_pow2){ //force pow2 if(Pow2(bw) > bw) bw = Pow2(bw)/2; if(Pow2(bh) > bh) bh = Pow2(bh)/2; if(Pow2(bd) > bd) bd = Pow2(bd)/2; } if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2; if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2; if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2; */ if (bw > imageW) bw = imageW; if (bh > imageH) bh = imageH; if (bd > imageD) bd = imageD; if (bw <= 1 || bh <= 1 || bd <= 1) break; if (filetype == "JPEG" && (bw < 8 || bh < 8)) break; Element lvnode = doc.createElement("Level"); lvnode.setAttribute("lv", String.valueOf(l)); lvnode.setAttribute("imageW", String.valueOf(imageW)); lvnode.setAttribute("imageH", String.valueOf(imageH)); lvnode.setAttribute("imageD", String.valueOf(imageD)); lvnode.setAttribute("xspc", String.valueOf(xspc)); lvnode.setAttribute("yspc", String.valueOf(yspc)); lvnode.setAttribute("zspc", String.valueOf(zspc)); lvnode.setAttribute("bitDepth", String.valueOf(bdepth)); root.appendChild(lvnode); Element brksnode = doc.createElement("Bricks"); brksnode.setAttribute("brick_baseW", String.valueOf(bw)); brksnode.setAttribute("brick_baseH", String.valueOf(bh)); brksnode.setAttribute("brick_baseD", String.valueOf(bd)); lvnode.appendChild(brksnode); ArrayList<Brick> bricks = new ArrayList<Brick>(); int mw, mh, md, mw2, mh2, md2; double tx0, ty0, tz0, tx1, ty1, tz1; double bx0, by0, bz0, bx1, by1, bz1; for (int k = 0; k < imageD; k += bd) { if (k > 0) k--; for (int j = 0; j < imageH; j += bh) { if (j > 0) j--; for (int i = 0; i < imageW; i += bw) { if (i > 0) i--; mw = Math.min(bw, imageW - i); mh = Math.min(bh, imageH - j); md = Math.min(bd, imageD - k); if (force_pow2) { mw2 = Pow2(mw); mh2 = Pow2(mh); md2 = Pow2(md); } else { mw2 = mw; mh2 = mh; md2 = md; } if (filetype == "JPEG") { if (mw2 < 8) mw2 = 8; if (mh2 < 8) mh2 = 8; } tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2); ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2); tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2); tx1 = 1.0d - 0.5d / mw2; if (mw < bw) tx1 = 1.0d; if (imageW - i == bw) tx1 = 1.0d; ty1 = 1.0d - 0.5d / mh2; if (mh < bh) ty1 = 1.0d; if (imageH - j == bh) ty1 = 1.0d; tz1 = 1.0d - 0.5d / md2; if (md < bd) tz1 = 1.0d; if (imageD - k == bd) tz1 = 1.0d; bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW; by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH; bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD; bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d); if (imageW - i == bw) bx1 = 1.0d; by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d); if (imageH - j == bh) by1 = 1.0d; bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d); if (imageD - k == bd) bz1 = 1.0d; int x, y, z; x = i - (mw2 - mw); y = j - (mh2 - mh); z = k - (md2 - md); bricks.add( new Brick( x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1, by1, bz1)); } } } Element fsnode = doc.createElement("Files"); lvnode.appendChild(fsnode); stack = imp.getStack(); int totalbricknum = nFrame * nCh * bricks.size(); int curbricknum = 0; for (int f = 0; f < nFrame; f++) { for (int ch = 0; ch < nCh; ch++) { int sizelimit = bdsizelimit * 1024 * 1024; int bytecount = 0; int filecount = 0; int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8); byte[] packed_data = new byte[pd_bufsize]; String base_dataname = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f); String current_dataname = base_dataname + "_data" + filecount; Brick b_first = bricks.get(0); if (b_first.z_ != 0) IJ.log("warning"); int st_z = b_first.z_; int ed_z = b_first.z_ + b_first.d_; LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>(); for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); // ImagePlus test; // ImageStack tsst; // test = NewImage.createByteImage("test", imageW, imageH, imageD, // NewImage.FILL_BLACK); // tsst = test.getStack(); for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); if (ed_z > b.z_ || st_z < b.z_ + b.d_) { if (b.z_ > st_z) { for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst(); st_z = b.z_; } else if (b.z_ < st_z) { IJ.log("warning"); for (int s = st_z - 1; s > b.z_; s--) iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); st_z = b.z_; } if (b.z_ + b.d_ > ed_z) { for (int s = ed_z; s < b.z_ + b.d_; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); ed_z = b.z_ + b.d_; } else if (b.z_ + b.d_ < ed_z) { IJ.log("warning"); for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast(); ed_z = b.z_ + b.d_; } } else { IJ.log("warning"); iplist.clear(); st_z = b.z_; ed_z = b.z_ + b.d_; for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); } if (iplist.size() != b.d_) { IJ.log("Stack Error"); return; } // int zz = st_z; int bsize = 0; byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Iterator<ImageProcessor> ipite = iplist.iterator(); while (ipite.hasNext()) { // ImageProcessor tsip = tsst.getProcessor(zz+1); ImageProcessor ip = ipite.next(); ip.setRoi(b.x_, b.y_, b.w_, b.h_); if (bdepth == 8) { byte[] data = (byte[]) ip.crop().getPixels(); System.arraycopy(data, 0, bdata, bsize, data.length); bsize += data.length; } else if (bdepth == 16) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); short[] data = (short[]) ip.crop().getPixels(); for (short e : data) buffer.putShort(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } else if (bdepth == 32) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); float[] data = (float[]) ip.crop().getPixels(); for (float e : data) buffer.putFloat(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } } String filename = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f) + "_ID" + String.valueOf(i); int offset = bytecount; int datasize = bdata.length; if (filetype == "RAW") { int dummy = -1; // do nothing } if (filetype == "JPEG" && bdepth == 8) { try { DataBufferByte db = new DataBufferByte(bdata, datasize); Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null); BufferedImage img = new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY); img.setData(raster); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); String format = "jpg"; Iterator<javax.imageio.ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); javax.imageio.ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality((float) jpeg_quality * 0.01f); writer.setOutput(ios); writer.write(null, new IIOImage(img, null, null), iwp); // ImageIO.write(img, format, baos); bdata = baos.toByteArray(); datasize = bdata.length; } catch (IOException e) { e.printStackTrace(); return; } } if (filetype == "ZLIB") { byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Deflater compresser = new Deflater(); compresser.setInput(bdata); compresser.setLevel(Deflater.DEFAULT_COMPRESSION); compresser.setStrategy(Deflater.DEFAULT_STRATEGY); compresser.finish(); datasize = compresser.deflate(tmpdata); bdata = tmpdata; compresser.end(); } if (bytecount + datasize > sizelimit && bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } filecount++; current_dataname = base_dataname + "_data" + filecount; bytecount = 0; offset = 0; System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } else { System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } Element filenode = doc.createElement("File"); filenode.setAttribute("filename", current_dataname); filenode.setAttribute("channel", String.valueOf(ch)); filenode.setAttribute("frame", String.valueOf(f)); filenode.setAttribute("brickID", String.valueOf(i)); filenode.setAttribute("offset", String.valueOf(offset)); filenode.setAttribute("datasize", String.valueOf(datasize)); filenode.setAttribute("filetype", String.valueOf(filetype)); fsnode.appendChild(filenode); curbricknum++; IJ.showProgress((double) (curbricknum) / (double) (totalbricknum)); } if (bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } } } } for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); Element bricknode = doc.createElement("Brick"); bricknode.setAttribute("id", String.valueOf(i)); bricknode.setAttribute("st_x", String.valueOf(b.x_)); bricknode.setAttribute("st_y", String.valueOf(b.y_)); bricknode.setAttribute("st_z", String.valueOf(b.z_)); bricknode.setAttribute("width", String.valueOf(b.w_)); bricknode.setAttribute("height", String.valueOf(b.h_)); bricknode.setAttribute("depth", String.valueOf(b.d_)); brksnode.appendChild(bricknode); Element tboxnode = doc.createElement("tbox"); tboxnode.setAttribute("x0", String.valueOf(b.tx0_)); tboxnode.setAttribute("y0", String.valueOf(b.ty0_)); tboxnode.setAttribute("z0", String.valueOf(b.tz0_)); tboxnode.setAttribute("x1", String.valueOf(b.tx1_)); tboxnode.setAttribute("y1", String.valueOf(b.ty1_)); tboxnode.setAttribute("z1", String.valueOf(b.tz1_)); bricknode.appendChild(tboxnode); Element bboxnode = doc.createElement("bbox"); bboxnode.setAttribute("x0", String.valueOf(b.bx0_)); bboxnode.setAttribute("y0", String.valueOf(b.by0_)); bboxnode.setAttribute("z0", String.valueOf(b.bz0_)); bboxnode.setAttribute("x1", String.valueOf(b.bx1_)); bboxnode.setAttribute("y1", String.valueOf(b.by1_)); bboxnode.setAttribute("z1", String.valueOf(b.bz1_)); bricknode.appendChild(bboxnode); } if (l < lv - 1) { imp = WindowManager.getImage(lvImgTitle.get(l + 1)); int[] newdims = imp.getDimensions(); imageW = newdims[0]; imageH = newdims[1]; imageD = newdims[3]; xspc = orgxspc * ((double) orgW / (double) imageW); yspc = orgyspc * ((double) orgH / (double) imageH); zspc = orgzspc * ((double) orgD / (double) imageD); bdepth = imp.getBitDepth(); } } File newXMLfile = new File(directory + basename + ".vvd"); writeXML(newXMLfile, doc); for (int l = 1; l < lv; l++) { imp = WindowManager.getImage(lvImgTitle.get(l)); imp.changes = false; imp.close(); } }
// ----------------------------------------------------- // 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; }
// ----------------------------------------------------- // Description: Read the text from the file. // AHHGAYUU! // ----------------------------------------------------- String interpretText(String destinationDirectory, String fileName_woext, String suffix) { String line = ""; String accumulate = ""; Scanner reader = null; int dataType = 1; // For current testing try { File file = new File( destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext + "_" + suffix + ".txt"); reader = new Scanner(new FileReader(file)); if (dataType == 1) { // multiline while (reader.hasNextLine()) { accumulate += reader.nextLine().trim() + " "; } accumulate = accumulate.trim(); } else if (dataType == 2) { // address if (reader.hasNextLine()) { accumulate = reader.nextLine().trim(); } if (reader.hasNextLine()) { accumulate += "," + reader.nextLine().trim(); } if (reader.hasNextLine()) { line = reader.nextLine().trim(); int index = line.indexOf(","); String line31 = line.substring(0, index); int i = 0; int hi = line.length() - index; for (i = hi; i > 0; i--) { if (Character.isDigit(line.charAt(i))) break; } String line32 = line.substring(index + 1, i); String line33 = line.substring(i + 1, line.length() - 1); accumulate += "," + line31 + "," + line32 + "," + line33; } } else if (dataType == 3) { // single text accumulate = reader.nextLine(); } else if (dataType == 4) { // numeric // coming soon } reader.close(); return accumulate; } catch (IOException e) { e.printStackTrace(); } return ""; }