private Note updateNoteResourcesByHash(final Note note, final Map<String, Resource> oldNewResourcesMap)
			throws XMLStreamException, NoSuchAlgorithmException {

		long start = System.currentTimeMillis();
		log.finer("Update ENML content with Resource mapping of Note " + note.getGuid());

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XMLEventReader reader = inputFactory.createXMLEventReader(new ByteArrayInputStream(note.getContent().getBytes(
				Charset.forName(CHARSET))));

		XMLEventWriter writer = outputFactory.createXMLEventWriter(baos);

		List<String> hashToDelete = new ArrayList<String>();

		while (reader.hasNext()) {
			XMLEvent event = (XMLEvent) reader.next();
			if (event.getEventType() == XMLEvent.START_ELEMENT) {
				StartElement startElement = event.asStartElement();
				if (startElement.getName().getLocalPart().equals(MEDIA)) {
					for (@SuppressWarnings("unchecked")
					Iterator<Attribute> iterator = startElement.getAttributes(); iterator.hasNext();) {
						Attribute attr = iterator.next();
						if (attr.getName().getLocalPart().equals(HASH)) {
							// If the resource has to be updated (is in the map)
							if (oldNewResourcesMap.containsKey(attr.getValue())) {
								Resource toUpdate = oldNewResourcesMap.get(attr.getValue());
								List<Attribute> attributes = new ArrayList<Attribute>();
								// Make sure the Resource Data is valid with proper hash and length
								toUpdate.setData(createData(toUpdate.getData().getBody()));
								attributes.add(eventFactory.createAttribute(HASH,
										Utils.bytesToHex(toUpdate.getData().getBodyHash())));
								attributes.add(eventFactory.createAttribute(TYPE, toUpdate.getMime()));
								for (@SuppressWarnings("unchecked")
								Iterator<Attribute> iterator2 = startElement.getAttributes(); iterator2.hasNext();) {
									Attribute attribute = iterator2.next();
									if (!attribute.getName().getLocalPart().equals(HASH)
											&& !attribute.getName().getLocalPart().equals(TYPE)) {
										attributes.add(attribute);
									}
								}
								hashToDelete.add(attr.getValue());
								// Add the resource to the note's resources if not already there
								addResourceObjectToNote(note, toUpdate);
								writer.add(eventFactory.createStartElement("", "", MEDIA, attributes.iterator(), null));
							} else {
								writer.add(event);
							}
						}
					}
				} else {
					writer.add(event);
				}
			} else {
				writer.add(event);
			}
		}
		// Remove the original resources after they have been updated
		removeResourceObjectFromNote(note, hashToDelete);

		note.setContent(new String(baos.toByteArray(), Charset.forName(CHARSET)));
		log.fine("Note ENML content of " + note.getGuid() + " has been updated with resource mapping in "
				+ Utils.getDurationBreakdown(System.currentTimeMillis() - start));
		return note;
	}