List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:com.linkedin.pinot.core.segment.creator.impl.inv.OffHeapBitmapInvertedIndexCreator.java
@Override public void seal() throws IOException { FileOutputStream fos = null; FileInputStream fisOffsets = null; FileInputStream fisBitmaps = null; final DataOutputStream bitmapsOut; final DataOutputStream offsetsOut; String tempOffsetsFile = invertedIndexFile + ".offsets"; String tempBitmapsFile = invertedIndexFile + ".binary"; try {// w w w.j a va2s. co m // build the posting list constructPostingLists(); // we need two separate streams, one to write the offsets and another to write the serialized // bitmap data. We need two because we dont the serialized length of each bitmap without // constructing. offsetsOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempOffsetsFile))); bitmapsOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempBitmapsFile))); // write out offsets of bitmaps. The information can be used to access a certain bitmap // directly. // Totally (invertedIndex.length+1) offsets will be written out; the last offset is used to // calculate the length of // the last bitmap, which might be needed when accessing bitmaps randomly. // If a bitmap's offset is k, then k bytes need to be skipped to reach the bitmap. int startOffset = 4 * (cardinality + 1); offsetsOut.writeInt(startOffset);// The first bitmap's offset MutableRoaringBitmap bitmap = new MutableRoaringBitmap(); for (int i = 0; i < cardinality; i++) { bitmap.clear(); int length = postingListLengths.get(i); for (int j = 0; j < length; j++) { int bufferOffset = postingListStartOffsets.get(i) + j; int value = postingListBuffer.get(bufferOffset); bitmap.add(value); } // serialize bitmap to bitmapsOut stream bitmap.serialize(bitmapsOut); startOffset += bitmap.serializedSizeInBytes(); // write offset offsetsOut.writeInt(startOffset); } offsetsOut.close(); bitmapsOut.close(); // merge the two files by simply writing offsets data first and then bitmap serialized data fos = new FileOutputStream(invertedIndexFile); fisOffsets = new FileInputStream(tempOffsetsFile); fisBitmaps = new FileInputStream(tempBitmapsFile); FileChannel channelOffsets = fisOffsets.getChannel(); channelOffsets.transferTo(0, channelOffsets.size(), fos.getChannel()); FileChannel channelBitmaps = fisBitmaps.getChannel(); channelBitmaps.transferTo(0, channelBitmaps.size(), fos.getChannel()); LOGGER.debug("persisted bitmap inverted index for column : " + spec.getName() + " in " + invertedIndexFile.getAbsolutePath()); } catch (Exception e) { LOGGER.error("Exception while creating bitmap index for column:" + spec.getName(), e); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(fisOffsets); IOUtils.closeQuietly(fisOffsets); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(fos); // MMaputils handles the null checks for buffer MmapUtils.unloadByteBuffer(origValueBuffer); origValueBuffer = null; valueBuffer = null; if (origLengths != null) { MmapUtils.unloadByteBuffer(origLengths); origLengths = null; lengths = null; } MmapUtils.unloadByteBuffer(origPostingListBuffer); origPostingListBuffer = null; postingListBuffer = null; MmapUtils.unloadByteBuffer(origPostingListCurrentOffsets); origPostingListCurrentOffsets = null; postingListCurrentOffsets = null; MmapUtils.unloadByteBuffer(origPostingListLengths); origPostingListLengths = null; postingListLengths = null; MmapUtils.unloadByteBuffer(origPostingListStartOffsets); origPostingListStartOffsets = null; postingListStartOffsets = null; FileUtils.deleteQuietly(new File(tempOffsetsFile)); FileUtils.deleteQuietly(new File(tempBitmapsFile)); } }
From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java
/** * updat this save this local segment into the db * //from w w w. j a v a 2 s. c o m * @param connection * @param addsi */ protected void updateDBPatchFilesystem(Connection connection) throws SQLException, IOException { PreparedStatement segmentUpdate = null; PreparedStatement segmentInsert = null; FileChannel packetStream = null; FileInputStream packetFIS = null; FileChannel sharedStream = null; FileOutputStream sharedFOS = null; File packetFile = null; File sharedFinalFile = null; File sharedTempFile = null; long newVersion = System.currentTimeMillis(); try { sharedTempFile = new File(getSharedTempFileName(INDEX_PATCHNAME)); sharedFinalFile = new File(getSharedFileName(INDEX_PATCHNAME, sharedStructuredStorage)); packetFile = clusterStorage.packPatch(); if (packetFile.exists()) { packetFIS = new FileInputStream(packetFile); packetStream = packetFIS.getChannel(); File sharedTempFileParent = sharedTempFile.getParentFile(); if (!sharedTempFileParent.exists() && !sharedTempFileParent.mkdirs()) { log.warn("couldn't create " + sharedTempFileParent.getPath()); } sharedFOS = new FileOutputStream(sharedTempFile); sharedStream = sharedFOS.getChannel(); doBlockedStream(packetStream, sharedStream); packetStream.close(); sharedStream.close(); segmentUpdate = connection .prepareStatement("update search_segments set version_ = ?, size_ = ? where name_ = ? "); segmentInsert = connection .prepareStatement("insert into search_segments ( name_, version_, size_ ) values ( ?,?,?)"); segmentUpdate.clearParameters(); segmentUpdate.setLong(1, newVersion); segmentUpdate.setLong(2, packetFile.length()); segmentUpdate.setString(3, INDEX_PATCHNAME); if (segmentUpdate.executeUpdate() != 1) { segmentInsert.clearParameters(); segmentInsert.setString(1, INDEX_PATCHNAME); segmentInsert.setLong(2, newVersion); segmentInsert.setLong(3, packetFile.length()); if (segmentInsert.executeUpdate() != 1) { throw new SQLException(" Failed to add patch packet "); } } long st = System.currentTimeMillis(); if (!sharedTempFile.renameTo(sharedFinalFile)) { log.warn("Couldn't rename file " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath()); } if (searchService.hasDiagnostics()) { log.info("Renamed " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath() + " in " + (System.currentTimeMillis() - st) + "ms"); } } else { log.warn("Packet file does not exist " + packetFile.getPath()); } } finally { try { if (packetStream != null) { packetStream.close(); packetFIS.close(); } } catch (Exception ex) { log.debug(ex); } try { packetFile.delete(); } catch (Exception ex) { log.debug(ex); } try { if (sharedStream != null) { sharedStream.close(); sharedFOS.close(); } } catch (Exception ex) { log.debug(ex); } try { sharedTempFile.delete(); } catch (Exception ex) { log.debug(ex); } try { segmentUpdate.close(); } catch (Exception ex) { log.debug(ex); } try { segmentInsert.close(); } catch (Exception ex) { log.debug(ex); } } }
From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java
/** * updat this save this local segment into the db * /*from w w w . j av a2 s . c om*/ * @param connection * @param addsi */ protected void updateDBSegmentFilesystem(Connection connection, SegmentInfo addsi) throws SQLException, IOException { PreparedStatement segmentUpdate = null; PreparedStatement segmentInsert = null; FileChannel packetStream = null; FileInputStream packetFIS = null; FileChannel sharedStream = null; FileOutputStream sharedFOS = null; File packetFile = null; File sharedFinalFile = null; File sharedTempFile = null; long newVersion = System.currentTimeMillis(); try { sharedTempFile = new File(getSharedTempFileName(addsi.getName())); sharedFinalFile = new File(getSharedFileName(addsi.getName(), sharedStructuredStorage)); packetFile = clusterStorage.packSegment(addsi, newVersion); if (packetFile.exists()) { packetFIS = new FileInputStream(packetFile); packetStream = packetFIS.getChannel(); File parentFile = sharedTempFile.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { log.warn("Unable to create directory " + sharedTempFile.getParentFile().getPath()); } sharedFOS = new FileOutputStream(sharedTempFile); sharedStream = sharedFOS.getChannel(); // Copy file contents from source to destination doBlockedStream(packetStream, sharedStream); packetStream.close(); sharedStream.close(); segmentUpdate = connection.prepareStatement( "update search_segments set version_ = ?, size_ = ? where name_ = ? and version_ = ?"); segmentInsert = connection .prepareStatement("insert into search_segments ( name_, version_, size_ ) values ( ?,?,?)"); if (addsi.isInDb()) { segmentUpdate.clearParameters(); segmentUpdate.setLong(1, newVersion); segmentUpdate.setLong(2, packetFile.length()); segmentUpdate.setString(3, addsi.getName()); segmentUpdate.setLong(4, addsi.getVersion()); if (segmentUpdate.executeUpdate() != 1) { throw new SQLException(" ant Find packet to update " + addsi); } } else { segmentInsert.clearParameters(); segmentInsert.setString(1, addsi.getName()); segmentInsert.setLong(2, newVersion); segmentInsert.setLong(3, packetFile.length()); if (segmentInsert.executeUpdate() != 1) { throw new SQLException(" Failed to insert packet " + addsi); } } addsi.setVersion(newVersion); File sharedParentFile = sharedFinalFile.getParentFile(); if (!sharedParentFile.exists() && !sharedParentFile.mkdirs()) { log.warn("Couln't create directory " + sharedParentFile.getPath()); } long st = System.currentTimeMillis(); if (!sharedTempFile.renameTo(sharedFinalFile)) { log.warn("Couldn't rename " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath()); } if (searchService.hasDiagnostics()) { log.info("Renamed " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath() + " in " + (System.currentTimeMillis() - st) + "ms"); } log.info("DB Updated " + addsi); } else { log.warn("Packet file does not exist " + packetFile.getPath()); } } finally { try { packetStream.close(); packetFIS.close(); } catch (Exception ex) { log.debug(ex); } try { packetFile.delete(); } catch (Exception ex) { log.debug(ex); } try { sharedStream.close(); sharedFOS.close(); } catch (Exception ex) { log.debug(ex); } try { sharedTempFile.delete(); } catch (Exception ex) { log.debug(ex); } try { segmentUpdate.close(); } catch (Exception ex) { log.debug(ex); } try { segmentInsert.close(); } catch (Exception ex) { log.debug(ex); } } }
From source file:MyZone.Settings.java
private boolean saveXML(String filename, Document dom) { File file = null;//from ww w . java2s. co m FileChannel channel = null; FileLock lock = null; FileOutputStream toWrite = null; try { if (!new File(filename).exists()) { String dirName = filename.substring(0, filename.lastIndexOf("/")); boolean success = (new File(dirName)).mkdirs(); if (!success && !(new File(dirName)).exists()) { return false; } OutputFormat format = new OutputFormat(dom); format.setIndenting(true); file = new File(filename); toWrite = new FileOutputStream(file, false); XMLSerializer serializer = new XMLSerializer(toWrite, format); serializer.serialize(dom); } else { file = new File(filename); toWrite = new FileOutputStream(file, false); channel = toWrite.getChannel(); while ((lock = channel.tryLock()) == null) { Thread.yield(); } OutputFormat format = new OutputFormat(dom); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(toWrite, format); serializer.serialize(dom); return true; } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } return false; } finally { try { if (lock != null) { lock.release(); } if (channel != null) { channel.close(); } if (toWrite != null) { toWrite.flush(); toWrite.close(); } } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } return false; } } return false; }
From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java
private void writeFile(File fileIn, char[] charArrayIn, int bufSize) { try {//from w ww . j a v a 2 s . c om FileOutputStream outputFile = null; outputFile = new FileOutputStream(fileIn, true); FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate((bufSize * 2) + 1000); for (char ch : charArrayIn) { buf.putChar(ch); } buf.flip(); try { outChannel.write(buf); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } } catch (IOException e) { throw new EJBException(e); } }
From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java
private void writeFile(File fileIn, String dataIn, int bufSize) { ByteBuffer dataByteBuffer = ByteBuffer.wrap(dataIn.getBytes()); try {/* w ww. ja v a2 s . c om*/ FileOutputStream outputFile = null; outputFile = new FileOutputStream(fileIn, true); WritableByteChannel outChannel = outputFile.getChannel(); try { outChannel.write(dataByteBuffer); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } } catch (IOException e) { throw new EJBException(e); } }
From source file:es.pode.publicacion.negocio.servicios.SrvPublicacionServiceImpl.java
/** * Mueve el contenido de un directorio a otro directorio. * /*from w ww .j ava 2 s . c o m*/ * @param oldDir * Directorio origen. * @param newDir * Directorio destino. * @return devuelve el tamanio del directorio movido. * @throws Exception * */ protected Long handleMoveDir(File oldDir, File newDir) throws IOException { long longitudTransferida = 0; if (oldDir.isDirectory()) { newDir.mkdirs(); String list[] = oldDir.list(); for (int i = 0; i < list.length; i++) { String dest1 = newDir.getAbsolutePath() + "/" + list[i]; String src1 = oldDir.getAbsolutePath() + "/" + list[i]; longitudTransferida += handleMoveDir(new File(src1), new File(dest1)).longValue(); } } else { FileInputStream fin = new FileInputStream(oldDir); FileOutputStream fos = new FileOutputStream(newDir); FileChannel sourceChannel = fin.getChannel(); FileChannel targetChannel = fos.getChannel(); longitudTransferida = sourceChannel.size(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } return new Long(longitudTransferida); }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
private void writeFile(File fileIn, String dataIn, int bufSize) { ByteBuffer dataByteBuffer = ByteBuffer.wrap(dataIn.getBytes()); try {/*from ww w . j ava2 s .c om*/ FileOutputStream outputFile = new FileOutputStream(fileIn, true); WritableByteChannel outChannel = outputFile.getChannel(); try { outChannel.write(dataByteBuffer); outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } } catch (IOException e) { throw new EJBException(e); } }
From source file:net.sf.firemox.xml.tbs.Tbs.java
/** * Converts the given tbs XML node to its binary form writing in the given * OutputStream./*from w w w.ja v a 2s . c om*/ * * @see net.sf.firemox.token.IdTokens#PLAYER_REGISTER_SIZE * @see net.sf.firemox.stack.phasetype.PhaseType * @see net.sf.firemox.clickable.ability.SystemAbility * @see net.sf.firemox.tools.StatePicture * @param node * the XML card structure * @param out * output stream where the card structure will be saved * @return the amount of written action in the output. * @throws IOException * error during the writing. * @see net.sf.firemox.deckbuilder.MdbLoader#loadMDB(String, int) */ public final int buildMdb(Node node, OutputStream out) throws IOException { final FileOutputStream fileOut = (FileOutputStream) out; referencedTest = new HashMap<String, Node>(); referencedAbilities = new HashMap<String, Node>(); referencedActions = new HashMap<String, List<Node>>(); referencedAttachments = new HashMap<String, Node>(); referencedNonMacroActions = new HashSet<String>(); referencedNonMacroAttachments = new HashSet<String>(); macroActions = new Stack<List<Node>>(); resolveReferences = false; MToolKit.writeString(out, node.getAttribute("name")); System.out.println("Building " + node.getAttribute("name") + " rules..."); MToolKit.writeString(out, node.getAttribute("version")); MToolKit.writeString(out, node.getAttribute("author")); MToolKit.writeString(out, node.getAttribute("comment")); // Write database configuration final Node database = node.get("database-properties"); Map<String, IdPropertyType> properties = new HashMap<String, IdPropertyType>(); for (java.lang.Object obj : database) { if (obj instanceof Node) { Node nodePriv = (Node) obj; String propertyType = nodePriv.getAttribute("type"); IdPropertyType propertyId; if (propertyType == null || propertyType.equals(String.class.getName())) { if ("true".equalsIgnoreCase(nodePriv.getAttribute("translate"))) { propertyId = IdPropertyType.SIMPLE_TRANSLATABLE_PROPERTY; } else { propertyId = IdPropertyType.SIMPLE_PROPERTY; } } else if ("java.util.List".equals(propertyType)) { if ("true".equalsIgnoreCase(nodePriv.getAttribute("translate"))) { propertyId = IdPropertyType.COLLECTION_TRANSLATABLE_PROPERTY; } else { propertyId = IdPropertyType.COLLECTION_PROPERTY; } } else { throw new InternalError("Unknow property type '" + propertyType + "'"); } properties.put(nodePriv.getAttribute("name"), propertyId); } } out.write(properties.size()); for (Map.Entry<String, IdPropertyType> entry : properties.entrySet()) { entry.getValue().serialize(out); MToolKit.writeString(out, entry.getKey()); } MToolKit.writeString(out, node.getAttribute("art-url")); MToolKit.writeString(out, node.getAttribute("back-picture")); MToolKit.writeString(out, node.getAttribute("damage-picture")); MToolKit.writeString(out, (String) node.get("licence").get(0)); // Manas final Node manas = node.get("mana-symbols"); // Colored manas final Node colored = manas.get("colored"); MToolKit.writeString(out, colored.getAttribute("url")); MToolKit.writeString(out, colored.getAttribute("big-url")); for (java.lang.Object obj : colored) { if (obj instanceof Node) { Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); MToolKit.writeString(out, nodePriv.getAttribute("big-picture")); } } // Colorless manas final Node colorless = manas.get("colorless"); MToolKit.writeString(out, colorless.getAttribute("url")); MToolKit.writeString(out, colorless.getAttribute("big-url")); MToolKit.writeString(out, colorless.getAttribute("unknown")); out.write(colorless.getNbNodes()); for (java.lang.Object obj : colorless) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(Integer.parseInt(nodePriv.getAttribute("amount"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // Hybrid manas final Node hybrid = manas.get("hybrid"); MToolKit.writeString(out, hybrid.getAttribute("url")); for (Object obj : hybrid) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // phyrexian manas final Node phyrexian = manas.get("phyrexian"); MToolKit.writeString(out, phyrexian.getAttribute("url")); for (Object obj : phyrexian) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // Prepare the shortcut to card's bytes offset final long shortcutCardBytes = fileOut.getChannel().position(); MToolKit.writeInt24(out, 0); // Write the user defined deck constraints final Set<String> definedConstraints = new HashSet<String>(); final Node deckConstraintRoot = XmlTools.getExternalizableNode(node, "deck-constraints"); final List<Node> deckConstraints = deckConstraintRoot.getNodes("deck-constraint"); XmlTools.writeAttrOptions(deckConstraintRoot, "deckbuilder-min-property", out); XmlTools.writeAttrOptions(deckConstraintRoot, "deckbuilder-max-property", out); XmlTools.writeAttrOptions(deckConstraintRoot, "master", out); out.write(deckConstraints.size()); for (Node deckConstraint : deckConstraints) { // Write the constraint key name String deckName = deckConstraint.getAttribute("name"); MToolKit.writeString(out, deckName); // Write extend String extend = deckConstraint.getAttribute("extends"); MToolKit.writeString(out, extend); if (extend != null && extend.length() > 0 && !definedConstraints.contains(extend)) { throw new RuntimeException("'" + deckName + "' is supposed extending '" + extend + "' but has not been found. Note that declaration order is important."); } // Write the constraint XmlTools.defaultOnMeTag = false; XmlTest.getTest("test").buildMdb(deckConstraint, out); definedConstraints.add(deckName); } // END OF HEADER // additional zones final List<XmlParser.Node> additionalZones = node.get("layouts").get("zones").get("additional-zones") .getNodes("additional-zone"); out.write(additionalZones.size()); int zoneId = IdZones.FIRST_ADDITIONAL_ZONE; for (XmlParser.Node additionalZone : additionalZones) { final String zoneName = additionalZone.getAttribute("name"); if (zoneId > IdZones.LAST_ADDITIONAL_ZONE) { throw new RuntimeException( "Cannot add more additional-zone (" + zoneName + "), increase core limitation"); } XmlTools.zones.put(zoneName, zoneId++); MToolKit.writeString(out, zoneName); MToolKit.writeString(out, additionalZone.getAttribute("layout-class")); MToolKit.writeString(out, additionalZone.getAttribute("constraint-you")); MToolKit.writeString(out, additionalZone.getAttribute("constraint-opponent")); } // Initial zone id out.write(XmlTools.getZone(node.get("layouts").get("zones").getAttribute("default-zone"))); // the references final Node references = XmlTools.getExternalizableNode(node, "references"); // the tests references System.out.println("\tshared tests..."); XmlTools.defaultOnMeTag = true; final Node tests = references.get("tests"); if (tests == null) { out.write(0); } else { out.write(tests.getNbNodes()); for (java.lang.Object obj : tests) { if (obj instanceof Node) { String ref = ((Node) obj).getAttribute("reference-name").toString(); referencedTest.put(ref, (Node) obj); MToolKit.writeString(out, ref); for (java.lang.Object objTest : (Node) obj) { if (objTest instanceof Node) { final Node node1 = (Node) objTest; try { XmlTest.getTest(node1.getTag()).buildMdb(node1, out); } catch (Throwable ie) { XmlConfiguration.error("In referenced test '" + ref + "' : " + ie.getMessage() + ". Context=" + objTest); } break; } } } } } // the action references (not included into MDB) final Node actions = references.get("actions"); System.out.print("\tactions : references (inlined in MDB)"); if (actions != null) { for (java.lang.Object obj : actions) { if (obj instanceof Node) { final String ref = ((Node) obj).getAttribute("reference-name"); final String globalName = ((Node) obj).getAttribute("name"); // do not accept macro? if ("false".equals(((Node) obj).getAttribute("macro"))) { referencedNonMacroActions.add(ref); } final List<Node> actionList = new ArrayList<Node>(); boolean firstIsDone = false; for (java.lang.Object actionI : (Node) obj) { if (actionI instanceof Node) { final Node action = (Node) actionI; // add action to the action list and replace the name of // sub-actions if (action.getAttribute("name") == null) { if (globalName != null) { if (firstIsDone) { action.addAttribute(new XmlParser.Attribute("name", "%" + globalName)); } else { action.addAttribute(new XmlParser.Attribute("name", globalName)); firstIsDone = true; } } else if (firstIsDone) { action.addAttribute(new XmlParser.Attribute("name", "%" + ref)); } else { action.addAttribute(new XmlParser.Attribute("name", ref)); firstIsDone = true; } } else if (!firstIsDone) { firstIsDone = true; } actionList.add((Node) actionI); } } // add this reference referencedActions.put(ref, actionList); } } } // the attachment references (not included into MDB) final Node attachments = references.get("attachments"); System.out.print(", attachments"); if (attachments != null) { for (java.lang.Object obj : attachments) { if (obj instanceof Node) { final String ref = ((Node) obj).getAttribute("reference-name"); // do not accept macro? if ("false".equals(((Node) obj).getAttribute("macro"))) { referencedNonMacroAttachments.add(ref); } // add this reference referencedAttachments.put(ref, (Node) obj); } } } // action pictures final Node actionsPictures = node.get("action-pictures"); System.out.print(", pictures"); if (actionsPictures == null) { out.write(0); out.write('\0'); } else { MToolKit.writeString(out, actionsPictures.getAttribute("url")); out.write(actionsPictures.getNbNodes()); for (java.lang.Object obj : actionsPictures) { if (obj instanceof Node) { final Node actionPicture = (Node) obj; MToolKit.writeString(out, actionPicture.getAttribute("name")); MToolKit.writeString(out, actionPicture.getAttribute("picture")); } } } // constraints on abilities linked to action final Node constraints = node.get("action-constraints"); System.out.println(", constraints"); if (constraints == null) { out.write(0); } else { out.write(constraints.getNbNodes()); for (java.lang.Object obj : constraints) { if (obj instanceof Node) { final Node constraint = (Node) obj; for (java.lang.Object objA : constraint.get("actions")) { if (objA instanceof Node) { XmlAction.getAction(((Node) objA).getTag()).buildMdb((Node) objA, out); break; } } if ("or".equals(constraint.getAttribute("operation"))) { IdOperation.OR.serialize(out); } else { IdOperation.AND.serialize(out); } XmlTest.getTest("test").buildMdb(constraint.get("test"), out); } } } // objects defined in this TBS System.out.println("\tobjects..."); final List<Node> objects = node.get("objects").getNodes("object"); out.write(objects.size()); for (Node object : objects) { // write object final XmlParser.Attribute objectName = new XmlParser.Attribute("name", object.getAttribute("name")); boolean onePresent = false; for (java.lang.Object modifierTmp : object) { if (modifierTmp instanceof Node) { // write the 'has-next' flag if (onePresent) { out.write(1); } // write the object-modifier final Node modifier = (Node) modifierTmp; modifier.addAttribute(objectName); XmlModifier.getModifier(modifier.getTag()).buildMdb(modifier, out); // Write the 'paint' flag if (onePresent) { out.write(0); } else { out.write(1); } onePresent = true; } } if (!onePresent) { // no modifier associated to this object, we write a virtual ONE ModifierType.REGISTER_MODIFIER.serialize(out); XmlModifier.buildMdbModifier(object, out); // Write the modified register index && value XmlTools.writeConstant(out, 0); XmlTools.writeConstant(out, 0); IdOperation.ADD.serialize(out); // Write the 'paint' flag out.write(1); } // Write the 'has-next' flag out.write(0); } // the abilities references System.out.println("\tshared abilities..."); Node abilities = references.get("abilities"); out.write(abilities.getNbNodes()); macroActions.push(null); for (Node ability : abilities.getNodes("ability")) { String ref = ability.getAttribute("reference-name").toString(); referencedAbilities.put(ref, ability); MToolKit.writeString(out, ref); try { Node node1 = (Node) ability.get(1); XmlTbs.getTbsComponent(node1.getTag()).buildMdb(node1, out); } catch (Throwable ie) { XmlConfiguration.error("Error In referenced ability '" + ref + "' : " + ie.getMessage() + "," + ie + ". Context=" + ability); } } macroActions.pop(); // damage types name System.out.println("\tdamage types..."); Collections.sort(XmlConfiguration.EXPORTED_DAMAGE_TYPES); int count = XmlConfiguration.EXPORTED_DAMAGE_TYPES.size(); out.write(count); for (int i = 0; i < count; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_DAMAGE_TYPES.get(i); MToolKit.writeString(out, pair.text); MToolKit.writeInt16(out, pair.value); } /** * <ul> * CARD'S PART : * <li>state pictures * <li>tooltip filters * <li>exported types name * <li>exported sorted properties name * <li>implemented cards * </ul> */ // state pictures System.out.println("\tstates"); final Node states = node.get("state-pictures"); if (states == null) { out.write(0); } else { out.write(states.getNbNodes()); for (java.lang.Object obj : states) { if (obj instanceof Node) { final Node ns = (Node) obj; MToolKit.writeString(out, ns.getAttribute("picture")); MToolKit.writeString(out, ns.getAttribute("name")); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("state"))); out.write(XmlTools.getInt(ns.getAttribute("index"))); final int x = XmlTools.getInt(ns.getAttribute("x")); final int y = XmlTools.getInt(ns.getAttribute("y")); if (MToolKit.getConstant(x) == -1 && MToolKit.getConstant(y) != -1 || MToolKit.getConstant(x) != -1 && MToolKit.getConstant(y) == -1) { XmlConfiguration.error( "In state-picture '-1' value is allowed if and only if x AND y have this value."); } MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("x"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("y"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("width"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("height"))); XmlTest.getTest("test").buildMdb(node.get("display-test"), out); } } } // tooltip filters System.out.println("\ttooltip filters..."); final Node ttFilters = node.get("tooltip-filters"); XmlTools.defaultOnMeTag = false; if (ttFilters == null) { out.write(0); } else { out.write(ttFilters.getNbNodes()); for (java.lang.Object obj : ttFilters) { if (obj instanceof Node) { buildMdbTooltipFilter((Node) obj, out); } } } // exported types name System.out.println("\texported type..."); Collections.sort(XmlConfiguration.EXPORTED_TYPES); int nbTypes = XmlConfiguration.EXPORTED_TYPES.size(); out.write(nbTypes); for (int i = 0; i < nbTypes; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_TYPES.get(i); MToolKit.writeString(out, pair.text); MToolKit.writeInt16(out, pair.value); } // exported sorted properties name and associated pictures System.out.println("\tproperties..."); Collections.sort(XmlConfiguration.EXPORTED_PROPERTIES); final int nbProperties = XmlConfiguration.EXPORTED_PROPERTIES.size(); MToolKit.writeInt16(out, nbProperties); for (int i = 0; i < nbProperties; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_PROPERTIES.get(i); MToolKit.writeInt16(out, pair.value); MToolKit.writeString(out, pair.text); } MToolKit.writeInt16(out, XmlConfiguration.PROPERTY_PICTURES.size()); for (Map.Entry<Integer, String> entry : XmlConfiguration.PROPERTY_PICTURES.entrySet()) { MToolKit.writeInt16(out, entry.getKey()); MToolKit.writeString(out, entry.getValue()); } /** * <ul> * STACK MANAGER'S PART : * <li>first player registers * <li>second player registers * <li>abortion zone * </ul> */ // player registers System.out.println("\tinitial registers..."); Node registers = node.get("registers-first-player"); final byte[] registersBytes = new byte[IdTokens.PLAYER_REGISTER_SIZE]; if (registers != null) { final List<Node> list = registers.getNodes("register"); for (Node register : list) { registersBytes[XmlTools.getInt(register.getAttribute("index"))] = (byte) XmlTools .getInt(register.getAttribute("value")); } } out.write(registersBytes); registers = node.get("registers-second-player"); final byte[] registersBytes2 = new byte[IdTokens.PLAYER_REGISTER_SIZE]; if (registers != null) { final List<Node> list = registers.getNodes("register"); for (Node register : list) { registersBytes2[XmlTools.getInt(register.getAttribute("index"))] = (byte) XmlTools .getInt(register.getAttribute("value")); } } out.write(registersBytes2); /* * TODO abortion zone */ final Node refAbilities = node.get("abilities"); out.write(XmlTools.getZone(refAbilities.getAttribute("abortionzone"))); // additional costs System.out.println("\tadditional-costs..."); final List<Node> additionalCosts = node.get("additional-costs").getNodes("additional-cost"); out.write(additionalCosts.size()); for (Node additionalCost : additionalCosts) { XmlTest.getTest("test").buildMdb(additionalCost.get("test"), out); XmlTbs.writeActionList(additionalCost.get("cost"), out); } /** * <ul> * EVENT MANAGER'S PART : * <li>phases * <li>turn-structure * <li>first phase index * </ul> */ // phases System.out.println("\tphases..."); final Node phases = node.get("phases"); out.write(phases.getNbNodes()); for (java.lang.Object obj : phases) { if (obj instanceof Node) { buildMdbPhaseType((Node) obj, out); } } // turn structure final String list = phases.getAttribute("turn-structure"); System.out.println("\tturn structure..."); final String[] arrayid = list.split(" "); out.write(arrayid.length); for (String id : arrayid) { out.write(XmlTools.getAliasValue(id)); } // first phase index for first turn out.write(Integer.parseInt(phases.getAttribute("start"))); // state based abilities System.out.println("\trule abilities..."); out.write(refAbilities.getNbNodes()); for (java.lang.Object obj : refAbilities) { if (obj instanceof Node) { try { XmlTbs.getTbsComponent(((Node) obj).getTag()).buildMdb((Node) obj, out); } catch (Throwable ie) { XmlConfiguration.error("Error in system ability '" + ((Node) obj).getAttribute("name") + "' : " + ie.getMessage() + ". Context=" + obj); break; } } } // static-modifiers System.out.println("\tstatic-modifiers..."); final Node modifiers = node.get("static-modifiers"); if (modifiers == null) { out.write(0); } else { out.write(modifiers.getNbNodes()); for (java.lang.Object obj : modifiers) { if (obj instanceof Node) { XmlModifier.getModifier("static-modifier").buildMdb((Node) obj, out); } } } // layouts System.out.println("\tlayouts..."); final Node layouts = node.get("layouts"); // initialize task pane layout writeTaskPaneElement(layouts.get("common-panel").get("card-details").get("properties"), out); // Sector of play zone for layouts List<Node> sectors = layouts.get("zones").get("play").getNodes("sector"); out.write(sectors.size()); for (XmlParser.Node sector : sectors) { XmlTest.getTest("test").buildMdb(sector, out); MToolKit.writeString(out, sector.getAttribute("constraint")); } // Update the shortcut to the first bytes of cards final long cardBytesPosition = fileOut.getChannel().position(); fileOut.getChannel().position(shortcutCardBytes); MToolKit.writeInt24(out, (int) cardBytesPosition); fileOut.getChannel().position(cardBytesPosition); // cards bytes + names resolveReferences = true; System.out.println("Processing cards..."); String xmlFile = node.getAttribute("xmlFile"); try { final String baseName = FilenameUtils.getBaseName(xmlFile); XmlTbs.updateMdb(baseName, out); } catch (Throwable e2) { XmlConfiguration.error("Error found in cards parsing of rule '" + xmlFile + "' : " + e2.getMessage()); } System.out.println(node.getAttribute("name") + " rules finished"); return 0; }
From source file:com.zoffcc.applications.zanavi.Navit.java
private void import_map_points_from_sdcard() { String orig_file = NAVIT_DATA_SHARE_DIR + Navit_DEST_FILENAME; String dest_file_dir = CFG_FILENAME_PATH + "../export/"; try {//from w ww . jav a 2 s .com File source = new File(dest_file_dir + Navit_DEST_FILENAME); File destination = new File(orig_file); if (source.exists()) { FileInputStream fi = new FileInputStream(source); FileOutputStream fo = new FileOutputStream(destination); FileChannel src = fi.getChannel(); FileChannel dst = fo.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); fi.close(); fo.close(); } } catch (Exception e) { e.printStackTrace(); } read_map_points(); }