List of usage examples for org.w3c.dom Element setTextContent
public void setTextContent(String textContent) throws DOMException;
From source file:com.moviejukebox.writer.MovieJukeboxXMLWriter.java
/** * Create an element with the movie details in it * * @param doc/*w w w.j a v a 2s .com*/ * @param movie * @param library * @return */ @SuppressWarnings("deprecation") private Element writeMovie(Document doc, Movie movie, Library library) { Element eMovie = doc.createElement(MOVIE); // holds the child attributes for reuse Map<String, String> childAttributes = new LinkedHashMap<>(); eMovie.setAttribute("isExtra", Boolean.toString(movie.isExtra())); eMovie.setAttribute("isSet", Boolean.toString(movie.isSetMaster())); if (movie.isSetMaster()) { eMovie.setAttribute("setSize", Integer.toString(movie.getSetSize())); } eMovie.setAttribute("isTV", Boolean.toString(movie.isTVShow())); for (Map.Entry<String, String> e : movie.getIdMap().entrySet()) { DOMHelper.appendChild(doc, eMovie, "id", e.getValue(), MOVIEDB, e.getKey()); } DOMHelper.appendChild(doc, eMovie, "mjbVersion", GitRepositoryState.getVersion()); DOMHelper.appendChild(doc, eMovie, "mjbGitSHA", GIT.getCommitId()); DOMHelper.appendChild(doc, eMovie, "xmlGenerationDate", DateTimeTools.convertDateToString(new Date(), DateTimeTools.getDateFormatLongString())); DOMHelper.appendChild(doc, eMovie, "baseFilenameBase", movie.getBaseFilename()); DOMHelper.appendChild(doc, eMovie, BASE_FILENAME, movie.getBaseName()); if ((TITLE_SORT_TYPE == TitleSortType.ADOPT_ORIGINAL) && (StringTools.isValidString(movie.getOriginalTitle()))) { DOMHelper.appendChild(doc, eMovie, TITLE, movie.getOriginalTitle(), SOURCE, movie.getOverrideSource(OverrideFlag.TITLE)); } else { DOMHelper.appendChild(doc, eMovie, TITLE, movie.getTitle(), SOURCE, movie.getOverrideSource(OverrideFlag.TITLE)); } DOMHelper.appendChild(doc, eMovie, SORT_TITLE, movie.getTitleSort()); DOMHelper.appendChild(doc, eMovie, ORIGINAL_TITLE, movie.getOriginalTitle(), SOURCE, movie.getOverrideSource(OverrideFlag.ORIGINALTITLE)); childAttributes.clear(); childAttributes.put("Year", Library.getYearCategory(movie.getYear())); childAttributes.put(SOURCE, movie.getOverrideSource(OverrideFlag.YEAR)); DOMHelper.appendChild(doc, eMovie, YEAR, movie.getYear(), childAttributes); DOMHelper.appendChild(doc, eMovie, "releaseDate", movie.getReleaseDate(), SOURCE, movie.getOverrideSource(OverrideFlag.RELEASEDATE)); DOMHelper.appendChild(doc, eMovie, "showStatus", movie.getShowStatus()); // This is the main rating DOMHelper.appendChild(doc, eMovie, RATING, Integer.toString(movie.getRating())); // This is the list of ratings Element eRatings = doc.createElement("ratings"); for (String site : movie.getRatings().keySet()) { DOMHelper.appendChild(doc, eRatings, RATING, Integer.toString(movie.getRating(site)), MOVIEDB, site); } eMovie.appendChild(eRatings); DOMHelper.appendChild(doc, eMovie, "watched", Boolean.toString(movie.isWatched())); DOMHelper.appendChild(doc, eMovie, "watchedNFO", Boolean.toString(movie.isWatchedNFO())); DOMHelper.appendChild(doc, eMovie, "watchedFile", Boolean.toString(movie.isWatchedFile())); if (movie.isWatched()) { DOMHelper.appendChild(doc, eMovie, "watchedDate", getWatchedDateString(movie.getWatchedDate())); } DOMHelper.appendChild(doc, eMovie, "top250", Integer.toString(movie.getTop250()), SOURCE, movie.getOverrideSource(OverrideFlag.TOP250)); DOMHelper.appendChild(doc, eMovie, DETAILS, HTMLTools.encodeUrl(movie.getBaseName()) + EXT_HTML); DOMHelper.appendChild(doc, eMovie, "posterURL", HTMLTools.encodeUrl(movie.getPosterURL())); DOMHelper.appendChild(doc, eMovie, "posterFile", HTMLTools.encodeUrl(movie.getPosterFilename())); DOMHelper.appendChild(doc, eMovie, "fanartURL", HTMLTools.encodeUrl(movie.getFanartURL())); DOMHelper.appendChild(doc, eMovie, "fanartFile", HTMLTools.encodeUrl(movie.getFanartFilename())); DOMHelper.appendChild(doc, eMovie, "detailPosterFile", HTMLTools.encodeUrl(movie.getDetailPosterFilename())); DOMHelper.appendChild(doc, eMovie, "thumbnail", HTMLTools.encodeUrl(movie.getThumbnailFilename())); DOMHelper.appendChild(doc, eMovie, "bannerURL", HTMLTools.encodeUrl(movie.getBannerURL())); DOMHelper.appendChild(doc, eMovie, "bannerFile", HTMLTools.encodeUrl(movie.getBannerFilename())); DOMHelper.appendChild(doc, eMovie, "wideBannerFile", HTMLTools.encodeUrl(movie.getWideBannerFilename())); DOMHelper.appendChild(doc, eMovie, "clearLogoURL", HTMLTools.encodeUrl(movie.getClearLogoURL())); DOMHelper.appendChild(doc, eMovie, "clearLogoFile", HTMLTools.encodeUrl(movie.getClearLogoFilename())); DOMHelper.appendChild(doc, eMovie, "clearArtURL", HTMLTools.encodeUrl(movie.getClearArtURL())); DOMHelper.appendChild(doc, eMovie, "clearArtFile", HTMLTools.encodeUrl(movie.getClearArtFilename())); DOMHelper.appendChild(doc, eMovie, "tvThumbURL", HTMLTools.encodeUrl(movie.getTvThumbURL())); DOMHelper.appendChild(doc, eMovie, "tvThumbFile", HTMLTools.encodeUrl(movie.getTvThumbFilename())); DOMHelper.appendChild(doc, eMovie, "seasonThumbURL", HTMLTools.encodeUrl(movie.getSeasonThumbURL())); DOMHelper.appendChild(doc, eMovie, "seasonThumbFile", HTMLTools.encodeUrl(movie.getSeasonThumbFilename())); DOMHelper.appendChild(doc, eMovie, "movieDiscURL", HTMLTools.encodeUrl(movie.getMovieDiscURL())); DOMHelper.appendChild(doc, eMovie, "movieDiscFile", HTMLTools.encodeUrl(movie.getMovieDiscFilename())); DOMHelper.appendChild(doc, eMovie, "plot", movie.getPlot(), SOURCE, movie.getOverrideSource(OverrideFlag.PLOT)); DOMHelper.appendChild(doc, eMovie, "outline", movie.getOutline(), SOURCE, movie.getOverrideSource(OverrideFlag.OUTLINE)); DOMHelper.appendChild(doc, eMovie, "quote", movie.getQuote(), SOURCE, movie.getOverrideSource(OverrideFlag.QUOTE)); DOMHelper.appendChild(doc, eMovie, "tagline", movie.getTagline(), SOURCE, movie.getOverrideSource(OverrideFlag.TAGLINE)); childAttributes.clear(); String countryIndex = createIndexAttribute(library, Library.INDEX_COUNTRY, movie.getCountriesAsString()); if (countryIndex != null) { childAttributes.put(INDEX, countryIndex); } childAttributes.put(SOURCE, movie.getOverrideSource(OverrideFlag.COUNTRY)); DOMHelper.appendChild(doc, eMovie, COUNTRY, movie.getCountriesAsString(), childAttributes); if (XML_COMPATIBLE) { Element eCountry = doc.createElement("countries"); int cnt = 0; for (String country : movie.getCountries()) { writeIndexedElement(doc, eCountry, "land", country, createIndexAttribute(library, Library.INDEX_COUNTRY, country)); cnt++; } eCountry.setAttribute(COUNT, String.valueOf(cnt)); eMovie.appendChild(eCountry); } DOMHelper.appendChild(doc, eMovie, "company", movie.getCompany(), SOURCE, movie.getOverrideSource(OverrideFlag.COMPANY)); if (XML_COMPATIBLE) { Element eCompany = doc.createElement("companies"); int cnt = 0; for (String company : movie.getCompany().split(Movie.SPACE_SLASH_SPACE)) { DOMHelper.appendChild(doc, eCompany, "credit", company); cnt++; } eCompany.setAttribute(COUNT, String.valueOf(cnt)); eMovie.appendChild(eCompany); } DOMHelper.appendChild(doc, eMovie, "runtime", movie.getRuntime(), SOURCE, movie.getOverrideSource(OverrideFlag.RUNTIME)); DOMHelper.appendChild(doc, eMovie, "certification", Library.getIndexingCertification(movie.getCertification()), SOURCE, movie.getOverrideSource(OverrideFlag.CERTIFICATION)); DOMHelper.appendChild(doc, eMovie, SEASON, Integer.toString(movie.getSeason())); DOMHelper.appendChild(doc, eMovie, LANGUAGE, movie.getLanguage(), SOURCE, movie.getOverrideSource(OverrideFlag.LANGUAGE)); if (XML_COMPATIBLE) { Element eLanguage = doc.createElement("languages"); int cnt = 0; for (String language : movie.getLanguage().split(Movie.SPACE_SLASH_SPACE)) { DOMHelper.appendChild(doc, eLanguage, "lang", language); cnt++; } eLanguage.setAttribute(COUNT, String.valueOf(cnt)); eMovie.appendChild(eLanguage); } DOMHelper.appendChild(doc, eMovie, "subtitles", movie.getSubtitles()); if (XML_COMPATIBLE) { Element eSubtitle = doc.createElement("subs"); int cnt = 0; for (String subtitle : SubtitleTools.getSubtitles(movie)) { DOMHelper.appendChild(doc, eSubtitle, "subtitle", subtitle); cnt++; } eSubtitle.setAttribute(COUNT, String.valueOf(cnt)); eMovie.appendChild(eSubtitle); } DOMHelper.appendChild(doc, eMovie, "trailerExchange", movie.isTrailerExchange() ? YES : "NO"); if (movie.getTrailerLastScan() == 0) { DOMHelper.appendChild(doc, eMovie, TRAILER_LAST_SCAN, Movie.UNKNOWN); } else { try { DateTime dt = new DateTime(movie.getTrailerLastScan()); DOMHelper.appendChild(doc, eMovie, TRAILER_LAST_SCAN, DateTimeTools.convertDateToString(dt)); } catch (Exception error) { DOMHelper.appendChild(doc, eMovie, TRAILER_LAST_SCAN, Movie.UNKNOWN); } } DOMHelper.appendChild(doc, eMovie, "container", movie.getContainer(), SOURCE, movie.getOverrideSource(OverrideFlag.CONTAINER)); DOMHelper.appendChild(doc, eMovie, "videoCodec", movie.getVideoCodec()); DOMHelper.appendChild(doc, eMovie, "audioCodec", movie.getAudioCodec()); // Write codec information eMovie.appendChild(createCodecsElement(doc, movie.getCodecs())); DOMHelper.appendChild(doc, eMovie, "audioChannels", movie.getAudioChannels()); DOMHelper.appendChild(doc, eMovie, "resolution", movie.getResolution(), SOURCE, movie.getOverrideSource(OverrideFlag.RESOLUTION)); // If the source is unknown, use the default source if (StringTools.isNotValidString(movie.getVideoSource())) { DOMHelper.appendChild(doc, eMovie, "videoSource", DEFAULT_SOURCE, SOURCE, Movie.UNKNOWN); } else { DOMHelper.appendChild(doc, eMovie, "videoSource", movie.getVideoSource(), SOURCE, movie.getOverrideSource(OverrideFlag.VIDEOSOURCE)); } DOMHelper.appendChild(doc, eMovie, "videoOutput", movie.getVideoOutput(), SOURCE, movie.getOverrideSource(OverrideFlag.VIDEOOUTPUT)); DOMHelper.appendChild(doc, eMovie, "aspect", movie.getAspectRatio(), SOURCE, movie.getOverrideSource(OverrideFlag.ASPECTRATIO)); DOMHelper.appendChild(doc, eMovie, "fps", Float.toString(movie.getFps()), SOURCE, movie.getOverrideSource(OverrideFlag.FPS)); if (movie.getFileDate() == null) { DOMHelper.appendChild(doc, eMovie, "fileDate", Movie.UNKNOWN); } else { // Try to catch any date re-formatting errors try { DOMHelper.appendChild(doc, eMovie, "fileDate", DateTimeTools.convertDateToString(movie.getFileDate())); } catch (ArrayIndexOutOfBoundsException error) { DOMHelper.appendChild(doc, eMovie, "fileDate", Movie.UNKNOWN); } } DOMHelper.appendChild(doc, eMovie, "fileSize", movie.getFileSizeString()); DOMHelper.appendChild(doc, eMovie, "first", HTMLTools.encodeUrl(movie.getFirst())); DOMHelper.appendChild(doc, eMovie, "previous", HTMLTools.encodeUrl(movie.getPrevious())); DOMHelper.appendChild(doc, eMovie, "next", HTMLTools.encodeUrl(movie.getNext())); DOMHelper.appendChild(doc, eMovie, "last", HTMLTools.encodeUrl(movie.getLast())); DOMHelper.appendChild(doc, eMovie, "libraryDescription", movie.getLibraryDescription()); DOMHelper.appendChild(doc, eMovie, "prebuf", Long.toString(movie.getPrebuf())); if (!movie.getGenres().isEmpty()) { Element eGenres = doc.createElement("genres"); eGenres.setAttribute(COUNT, String.valueOf(movie.getGenres().size())); eGenres.setAttribute(SOURCE, movie.getOverrideSource(OverrideFlag.GENRES)); for (String genre : movie.getGenres()) { writeIndexedElement(doc, eGenres, "genre", genre, createIndexAttribute(library, Library.INDEX_GENRES, Library.getIndexingGenre(genre))); } eMovie.appendChild(eGenres); } Collection<String> items = movie.getSetsKeys(); if (!items.isEmpty()) { Element eSets = doc.createElement("sets"); eSets.setAttribute(COUNT, String.valueOf(items.size())); for (String item : items) { Element eSetItem = doc.createElement("set"); Integer order = movie.getSetOrder(item); if (null != order) { eSetItem.setAttribute(ORDER, String.valueOf(order)); } String index = createIndexAttribute(library, Library.INDEX_SET, item); if (null != index) { eSetItem.setAttribute(INDEX, index); } eSetItem.setTextContent(item); eSets.appendChild(eSetItem); } eMovie.appendChild(eSets); } writeIndexedElement(doc, eMovie, "director", movie.getDirector(), createIndexAttribute(library, Library.INDEX_DIRECTOR, movie.getDirector())); Element eSet; eSet = generateElementSet(doc, "directors", "director", movie.getDirectors(), library, Library.INDEX_DIRECTOR, movie.getOverrideSource(OverrideFlag.DIRECTORS)); if (eSet != null) { eMovie.appendChild(eSet); } eSet = generateElementSet(doc, "writers", "writer", movie.getWriters(), library, Library.INDEX_WRITER, movie.getOverrideSource(OverrideFlag.WRITERS)); if (eSet != null) { eMovie.appendChild(eSet); } eSet = generateElementSet(doc, "cast", "actor", movie.getCast(), library, Library.INDEX_CAST, movie.getOverrideSource(OverrideFlag.ACTORS)); if (eSet != null) { eMovie.appendChild(eSet); } // Issue 1901: Awards if (ENABLE_AWARDS) { Collection<AwardEvent> awards = movie.getAwards(); if (awards != null && !awards.isEmpty()) { Element eAwards = doc.createElement("awards"); eAwards.setAttribute(COUNT, String.valueOf(awards.size())); for (AwardEvent event : awards) { Element eEvent = doc.createElement("event"); eEvent.setAttribute(NAME, event.getName()); eEvent.setAttribute(COUNT, String.valueOf(event.getAwards().size())); for (Award award : event.getAwards()) { Element eAwardItem = doc.createElement("award"); eAwardItem.setAttribute(NAME, award.getName()); eAwardItem.setAttribute(WON, Integer.toString(award.getWon())); eAwardItem.setAttribute("nominated", Integer.toString(award.getNominated())); eAwardItem.setAttribute(YEAR, Integer.toString(award.getYear())); if (award.getWons() != null && !award.getWons().isEmpty()) { eAwardItem.setAttribute("wons", StringUtils.join(award.getWons(), Movie.SPACE_SLASH_SPACE)); if (XML_COMPATIBLE) { for (String won : award.getWons()) { DOMHelper.appendChild(doc, eAwardItem, WON, won); } } } if (award.getNominations() != null && !award.getNominations().isEmpty()) { eAwardItem.setAttribute("nominations", StringUtils.join(award.getNominations(), Movie.SPACE_SLASH_SPACE)); if (XML_COMPATIBLE) { for (String nomination : award.getNominations()) { DOMHelper.appendChild(doc, eAwardItem, "nomination", nomination); } } } if (!XML_COMPATIBLE) { eAwardItem.setTextContent(award.getName()); } eEvent.appendChild(eAwardItem); } eAwards.appendChild(eEvent); } eMovie.appendChild(eAwards); } } // Issue 1897: Cast enhancement if (ENABLE_PEOPLE) { Collection<Filmography> people = movie.getPeople(); if (people != null && !people.isEmpty()) { Element ePeople = doc.createElement("people"); ePeople.setAttribute(COUNT, String.valueOf(people.size())); for (Filmography person : people) { Element ePerson = doc.createElement("person"); ePerson.setAttribute(NAME, person.getName()); ePerson.setAttribute("doublage", person.getDoublage()); ePerson.setAttribute(TITLE, person.getTitle()); ePerson.setAttribute(CHARACTER, person.getCharacter()); ePerson.setAttribute(JOB, person.getJob()); ePerson.setAttribute("id", person.getId()); for (Map.Entry<String, String> personID : person.getIdMap().entrySet()) { if (!personID.getKey().equals(ImdbPlugin.IMDB_PLUGIN_ID)) { ePerson.setAttribute(ID + personID.getKey(), personID.getValue()); } } ePerson.setAttribute(DEPARTMENT, person.getDepartment()); ePerson.setAttribute(URL, person.getUrl()); ePerson.setAttribute(ORDER, Integer.toString(person.getOrder())); ePerson.setAttribute("cast_id", Integer.toString(person.getCastId())); ePerson.setAttribute("photoFile", person.getPhotoFilename()); String inx = createIndexAttribute(library, Library.INDEX_PERSON, person.getName()); if (inx != null) { ePerson.setAttribute(INDEX, inx); } ePerson.setAttribute(SOURCE, person.getSource()); ePerson.setTextContent(person.getFilename()); ePeople.appendChild(ePerson); } eMovie.appendChild(ePeople); } } // Issue 2012: Financial information about movie if (ENABLE_BUSINESS) { Element eBusiness = doc.createElement("business"); eBusiness.setAttribute("budget", movie.getBudget()); for (Map.Entry<String, String> gross : movie.getGross().entrySet()) { DOMHelper.appendChild(doc, eBusiness, "gross", gross.getValue(), COUNTRY, gross.getKey()); } for (Map.Entry<String, String> openweek : movie.getOpenWeek().entrySet()) { DOMHelper.appendChild(doc, eBusiness, "openweek", openweek.getValue(), COUNTRY, openweek.getKey()); } eMovie.appendChild(eBusiness); } // Issue 2013: Add trivia if (ENABLE_TRIVIA) { Element eTrivia = doc.createElement("didyouknow"); eTrivia.setAttribute(COUNT, String.valueOf(movie.getDidYouKnow().size())); for (String trivia : movie.getDidYouKnow()) { DOMHelper.appendChild(doc, eTrivia, "trivia", trivia); } eMovie.appendChild(eTrivia); } // Write the indexes that the movie belongs to Element eIndexes = doc.createElement("indexes"); String originalName; for (Entry<String, String> index : movie.getIndexes().entrySet()) { Element eIndexEntry = doc.createElement(INDEX); eIndexEntry.setAttribute("type", index.getKey()); originalName = Library.getOriginalCategory(index.getKey(), Boolean.TRUE); eIndexEntry.setAttribute(ORIGINAL_NAME, originalName); eIndexEntry.setAttribute("encoded", FileTools.makeSafeFilename(index.getValue())); eIndexEntry.setTextContent(index.getValue()); eIndexes.appendChild(eIndexEntry); } eMovie.appendChild(eIndexes); // Write details about the files Element eFiles = doc.createElement("files"); for (MovieFile mf : movie.getFiles()) { Element eFileItem = doc.createElement("file"); eFileItem.setAttribute(SEASON, Integer.toString(mf.getSeason())); eFileItem.setAttribute("firstPart", Integer.toString(mf.getFirstPart())); eFileItem.setAttribute("lastPart", Integer.toString(mf.getLastPart())); eFileItem.setAttribute(TITLE, mf.getTitle()); eFileItem.setAttribute("subtitlesExchange", mf.isSubtitlesExchange() ? YES : "NO"); // Fixes an issue with null file lengths try { if (mf.getFile() == null) { eFileItem.setAttribute("size", "0"); } else { eFileItem.setAttribute("size", Long.toString(mf.getSize())); } } catch (DOMException ex) { LOG.debug("File length error for file {}", mf.getFilename(), ex); eFileItem.setAttribute("size", "0"); } // Playlink values; can be empty, but not null for (Map.Entry<String, String> e : mf.getPlayLink().entrySet()) { eFileItem.setAttribute(e.getKey().toLowerCase(), e.getValue()); } eFileItem.setAttribute("watched", mf.isWatched() ? TRUE : FALSE); if (mf.getFile() != null) { DOMHelper.appendChild(doc, eFileItem, "fileLocation", mf.getFile().getAbsolutePath()); } // Write the fileURL String filename = mf.getFilename(); // Issue 1237: Add "VIDEO_TS.IFO" for PlayOnHD VIDEO_TS path names if (IS_PLAYON_HD && filename.toUpperCase().endsWith("VIDEO_TS")) { filename = filename + "/VIDEO_TS.IFO"; } // If attribute was set, save it back out. String archiveName = mf.getArchiveName(); if (StringTools.isValidString(archiveName)) { LOG.debug("getArchivename is '{}' for {} length {}", archiveName, mf.getFilename(), archiveName.length()); } if (StringTools.isValidString(archiveName)) { DOMHelper.appendChild(doc, eFileItem, "fileArchiveName", archiveName); // If they want full URL, do so if (IS_EXTENDED_URL && !filename.endsWith(archiveName)) { filename = filename + "/" + archiveName; } } DOMHelper.appendChild(doc, eFileItem, "fileURL", filename); for (int part = mf.getFirstPart(); part <= mf.getLastPart(); ++part) { childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); childAttributes.put(SOURCE, mf.getOverrideSource(OverrideFlag.EPISODE_TITLE)); DOMHelper.appendChild(doc, eFileItem, "fileTitle", mf.getTitle(part), childAttributes); // Only write out these for TV Shows if (movie.isTVShow()) { childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); childAttributes.put("afterSeason", mf.getAirsAfterSeason(part)); childAttributes.put("beforeSeason", mf.getAirsBeforeSeason(part)); childAttributes.put("beforeEpisode", mf.getAirsBeforeEpisode(part)); DOMHelper.appendChild(doc, eFileItem, "airsInfo", String.valueOf(part), childAttributes); childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); childAttributes.put(SOURCE, mf.getOverrideSource(OverrideFlag.EPISODE_FIRST_AIRED)); DOMHelper.appendChild(doc, eFileItem, "firstAired", mf.getFirstAired(part), childAttributes); } if (mf.getWatchedDate() > 0) { DOMHelper.appendChild(doc, eFileItem, "watchedDate", getWatchedDateString(mf.getWatchedDate())); } if (includeEpisodePlots) { childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); // use file title if plot is invalid String filePlot = mf.getPlot(part); final String filePlotSource; if (movie.isTVShow() && StringTools.isNotValidString(filePlot)) { filePlot = mf.getTitle(part); filePlotSource = Movie.UNKNOWN; } else { filePlotSource = mf.getOverrideSource(OverrideFlag.EPISODE_PLOT); } if (episodePlotSize > 0) { filePlot = StringTools.trimToLength(filePlot, episodePlotSize); } childAttributes.put(SOURCE, filePlotSource); DOMHelper.appendChild(doc, eFileItem, "filePlot", filePlot, childAttributes); } if (includeEpisodeRating) { childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); childAttributes.put(SOURCE, mf.getOverrideSource(OverrideFlag.EPISODE_RATING)); DOMHelper.appendChild(doc, eFileItem, "fileRating", mf.getRating(part), childAttributes); } if (includeVideoImages) { DOMHelper.appendChild(doc, eFileItem, "fileImageURL", HTMLTools.encodeUrl(mf.getVideoImageURL(part)), PART, String.valueOf(part)); DOMHelper.appendChild(doc, eFileItem, "fileImageFile", HTMLTools.encodeUrl(mf.getVideoImageFilename(part)), PART, String.valueOf(part)); } // Episode IDs if (mf.getIds(part) != null && !mf.getIds(part).isEmpty()) { for (Entry<String, String> entry : mf.getIds(part).entrySet()) { childAttributes.clear(); childAttributes.put(PART, Integer.toString(part)); childAttributes.put(SOURCE, entry.getKey()); DOMHelper.appendChild(doc, eFileItem, "fileId", entry.getValue(), childAttributes); } } } if (mf.getAttachments() != null && !mf.getAttachments().isEmpty()) { Element eAttachments = doc.createElement("attachments"); for (Attachment att : mf.getAttachments()) { Element eAttachment = doc.createElement("attachment"); eAttachment.setAttribute("type", att.getType().toString()); DOMHelper.appendChild(doc, eAttachment, "attachmentId", String.valueOf(att.getAttachmentId())); DOMHelper.appendChild(doc, eAttachment, "contentType", att.getContentType().toString()); DOMHelper.appendChild(doc, eAttachment, "mimeType", att.getMimeType()); DOMHelper.appendChild(doc, eAttachment, "part", String.valueOf(att.getPart())); eAttachments.appendChild(eAttachment); } eFileItem.appendChild(eAttachments); } eFiles.appendChild(eFileItem); } eMovie.appendChild(eFiles); Collection<ExtraFile> extraFiles = movie.getExtraFiles(); if (extraFiles != null && !extraFiles.isEmpty()) { Element eExtras = doc.createElement("extras"); for (ExtraFile ef : extraFiles) { Element eExtraItem = doc.createElement("extra"); eExtraItem.setAttribute(TITLE, ef.getTitle()); if (ef.getPlayLink() != null) { // Playlink values for (Map.Entry<String, String> e : ef.getPlayLink().entrySet()) { eExtraItem.setAttribute(e.getKey().toLowerCase(), e.getValue()); } } eExtraItem.setTextContent(ef.getFilename()); // should already be URL-encoded eExtras.appendChild(eExtraItem); } eMovie.appendChild(eExtras); } return eMovie; }
From source file:org.alfresco.web.config.forms.FormConfigRuntime.java
/** * @param properties/*w w w. j a v a2s .com*/ * @return */ public boolean syncGlobalConfigs(HashMap<String, Object> properties) { boolean status = false; Element formsElem = XmlUtils.findFirstElement("config[not(@evaluator) and not(@condition)]/forms", (Element) configDocument.getFirstChild()); if (formsElem == null) { formsElem = setGlobalConfigFormsElement(); status = true; } String configType = (String) properties.get("config-type"); if (configType != null) { if (configType.equals("default-control")) { String typeName = (String) properties.get("type-name"); String newTypeName = (properties.containsKey("new-type-name")) ? (String) properties.get("new-type-name") : null; Element defaultControlsElem = XmlUtils.findFirstElement("default-controls", formsElem); if (defaultControlsElem == null) { defaultControlsElem = configDocument.createElement("default-controls"); appendChild(formsElem, defaultControlsElem); status = true; } if (typeName != null) { Element typeControlElem = XmlUtils.findFirstElement("type[@name='" + typeName + "']", defaultControlsElem); if (newTypeName != null && !typeName.equals(newTypeName)) { if (typeControlElem != null) { //typeControlElem.getParentNode().removeChild(typeControlElem); removeChild(typeControlElem); typeControlElem = null; status = true; } typeName = newTypeName; } Control control = (Control) properties.get("control"); if (typeControlElem == null) { typeControlElem = configDocument.createElement("type"); manageAttribute(typeControlElem, "name", typeName); manageAttribute(typeControlElem, "template", control.getTemplate()); appendChild(defaultControlsElem, typeControlElem); status = true; } if (control.getParams() != null) { boolean parametersChanged = false; ControlParam[] controlParameters = control.getParams(); if (typeControlElem.getChildNodes().getLength() != controlParameters.length) { parametersChanged = true; } else { for (ControlParam controlParam : controlParameters) { String parameterValue = controlParam.getValue(); Element parameterElem = XmlUtils.findFirstElement( "control-param[@name='" + controlParam.getName() + "']", defaultControlsElem); if (parameterElem == null) { parametersChanged = true; } else if (!parameterElem.getTextContent().equals(parameterValue)) { parametersChanged = true; } } } if (parametersChanged) { while (typeControlElem.getChildNodes().getLength() > 0) { removeChild(typeControlElem.getFirstChild()); } for (ControlParam controlParam : controlParameters) { String parameterValue = controlParam.getValue(); Element parameterElem = XmlUtils.findFirstElement( "control-param[@name='" + controlParam.getName() + "']", defaultControlsElem); if (parameterElem == null) { parameterElem = configDocument.createElement("control-param"); manageAttribute(parameterElem, "name", controlParam.getName()); status = true; } if (!parameterElem.getTextContent().equals(parameterValue)) { parameterElem.setTextContent(parameterValue); status = true; } if (parameterElem != null) { appendChild(typeControlElem, parameterElem); } } } } } } else if (configType.equals("constraint-handler")) { String typeName = (String) properties.get("constraint-type-name"); String newTypeName = (properties.containsKey("new-constraint-type-name")) ? (String) properties.get("new-constraint-type-name") : null; Element constraintHandlersElem = XmlUtils.findFirstElement("constraint-handlers", formsElem); if (constraintHandlersElem == null) { constraintHandlersElem = configDocument.createElement("constraint-handlers"); appendChild(formsElem, constraintHandlersElem); status = true; } if (typeName != null) { Element constraintHandlerElem = XmlUtils .findFirstElement("constraint[@type='" + typeName + "']", constraintHandlersElem); if (newTypeName != null && !typeName.equals(newTypeName)) { if (constraintHandlerElem != null) { //constraintHandlerElem.getParentNode().removeChild(constraintHandlerElem); removeChild(constraintHandlerElem); constraintHandlerElem = null; status = true; } typeName = newTypeName; } ConstraintHandlerDefinition constraintHandler = (ConstraintHandlerDefinition) properties .get("constraint"); if (constraintHandlerElem == null) { constraintHandlerElem = configDocument.createElement("constraint"); manageAttribute(constraintHandlerElem, "type", typeName); appendChild(constraintHandlersElem, constraintHandlerElem); status = true; } if (manageAttribute(constraintHandlerElem, "validation-handler", constraintHandler.getValidationHandler())) { status = true; } if (manageAttribute(constraintHandlerElem, "event", constraintHandler.getEvent())) { status = true; } if (manageAttribute(constraintHandlerElem, "message", constraintHandler.getMessage())) { status = true; } if (manageAttribute(constraintHandlerElem, "message-id", constraintHandler.getMessageId())) { status = true; } } } else if (configType.equals("dependencies")) { Element dependenciesElem = XmlUtils.findFirstElement("dependencies", formsElem); if (dependenciesElem == null) { dependenciesElem = configDocument.createElement("dependencies"); appendChild(formsElem, dependenciesElem); status = true; } if (properties.containsKey("js")) { String dependency = (String) properties.get("js"); Element jsElement = XmlUtils.findFirstElement("js[@src='" + dependency + "']", dependenciesElem); if (jsElement == null) { jsElement = configDocument.createElement("js"); appendChild(dependenciesElem, jsElement); status = true; } if (properties.containsKey("new-js")) { String newDependency = (String) properties.get("new-js"); if (!dependency.equals(newDependency)) { dependency = newDependency; } } if (manageAttribute(jsElement, "src", dependency)) { status = true; } } if (properties.containsKey("css")) { String dependency = (String) properties.get("css"); Element cssElement = XmlUtils.findFirstElement("css[@src='" + dependency + "']", dependenciesElem); if (cssElement == null) { cssElement = configDocument.createElement("css"); appendChild(dependenciesElem, cssElement); status = true; } if (properties.containsKey("new-css")) { String newDependency = (String) properties.get("new-css"); if (!dependency.equals(newDependency)) { dependency = newDependency; } } if (manageAttribute(cssElement, "src", dependency)) { status = true; } } } } return status; }
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java
/** * Fill x forms attribute. Creates the attribute node and sets the value in the instance. * Priority order: value from the uri; if none, the attribute's default; if none, a default * value for the type is created.//w w w.ja v a2s. co m * * @param xformsDoc * the xforms document * @param containerElement * the container element * @param attrType * the attribute * @param attributes * the attributes * @param initParams * the init params * @param isServletRequest */ private void fillXFormsAttribute(Document xformsDoc, Element containerElement, AttributeType attrType, List<GenericAttribute> attributes, Map<String, String> initParams, boolean formIsReadOnly, boolean isServletRequest) { Element attrElt = xformsDoc.createElement(attrType.getName()); // the value to set eventually String textualValue = null; // there may be a default value String defaultValue = getDefault(attrType); // #999: enums may be dynamic so don't treat them all as static String staticEnumName = isDynamicEnum(attrType) ? null : attrType.getEnumQName(); GenericAttribute alfAttribute = findAttribute(attributes, attrType); String type = attrType.getType(); if (attrType.getName().equals(MsgId.INT_INSTANCE_SIDEID.getText())) { if (alfAttribute != null) { textualValue = alfAttribute.getValue().get(0).getValue(); } } else { if (alfAttribute == null) { String initialValue = safeMapGet(initParams, attrType.getName()); // setting the value from the uri if (StringUtils.trimToNull(initialValue) != null) { textualValue = convertAlfrescoAttributeToXforms(initialValue, type, staticEnumName, initParams); } else { // empty form (but we want to include default values) textualValue = createXFormsInitialValue(type, defaultValue, staticEnumName, initParams); } } else { textualValue = convertAlfrescoAttributeToXforms(alfAttribute.getValue(), type, staticEnumName, initParams); } } // we set the text content depending on the data type, with user format if applicable final boolean applyUserFormat = (isServletRequest == false) && (formIsReadOnly || isReadOnly(attrType)); if (type.equals("DateTime")) { String timeValue = getTimeFromDateTime(textualValue); String dateValue = getDateFromDateTime(textualValue); if (applyUserFormat) { dateValue = transformDateValueForDisplay(dateValue); timeValue = transformTimeValueForDisplay(timeValue); attrElt.setTextContent(dateValue + " " + timeValue); } else { Element dateField = xformsDoc.createElement("date"); dateField.setTextContent(dateValue); attrElt.appendChild(dateField); Element timeField = xformsDoc.createElement("time"); timeField.setTextContent(timeValue); attrElt.appendChild(timeField); } } else if (type.equals("Date")) { String dateValue = textualValue; if (applyUserFormat) { transformDateValueForDisplay(textualValue); } attrElt.setTextContent(dateValue); } else if (type.equals("Time")) { String timeValue = textualValue; if (applyUserFormat) { timeValue = transformTimeValueForDisplay(textualValue); } attrElt.setTextContent(timeValue); // } else if (isMultiple(attrType) && (attrType.getEnumQName() == null)) { // // ** #1420: support for text fields with 'multiple' property set to 'true' // Element input = // xformsDoc.createElement(MsgId.INT_INSTANCE_INPUT_MULT_INPUT.getText()); // attrElt.appendChild(input); // // // add legitimate multiple values // if (alfAttribute != null) { // for (ValueType valueType : alfAttribute.getValue()) { // Element item = getInputMultipleItemWithValue(xformsDoc, valueType.getValue()); // attrElt.appendChild(item); // } // } // // // add ghost // Element ghostItem = getInputMultipleItemWithValue(xformsDoc, ""); // attrElt.appendChild(ghostItem); // // ** #1420 } else { attrElt.setTextContent(textualValue); } if (isFileField(attrType)) { attrElt.setAttribute("file", ""); attrElt.setAttribute("type", ""); } containerElement.appendChild(attrElt); }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Gets the enum.// w w w . j a v a2 s.c om * * @param transaction * the transaction * @param type * the type * @param filterParent * the filter parent * @param filterData * the filter data * @param query * @return the enum * @throws ServletException */ public Node getDynamicEnum(AlfrescoTransaction transaction, String type, String filterParent, String filterData, String query, boolean limit) throws ServletException { Map<String, String> parameters = new TreeMap<String, String>(); String fp = StringUtils.trimToNull(filterParent); if (fp != null) { parameters.put("parent", fp); } String fd = StringUtils.trimToNull(filterData); if (fd != null) { parameters.put("context", fd); } String q = StringUtils.trimToNull(query); if (q != null) { parameters.put("query", q); } if (limit) { parameters.put("limit", "true"); } parameters.put("type", mappingAgent.getEnumTypeName(type)); Document reqDoc = requestDocumentFromAlfresco(transaction, parameters, MsgId.INT_WEBSCRIPT_OPCODE_ENUM); if (reqDoc == null) { throw new ServletException(MsgId.INT_MSG_ALFRESCO_SERVER_DOWN.getText()); } Element docElt = reqDoc.getDocumentElement(); Element queryElement = reqDoc.createElement("query"); queryElement.setTextContent(StringUtils.trimToEmpty(query)); docElt.appendChild(queryElement); docElt.appendChild(reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDID.getText())); docElt.appendChild(reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDLABEL.getText())); return reqDoc; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Returns a fake list built without contacting Alfresco. * /*from w ww.j av a 2 s .com*/ * @param alfrescoName * the datatype * @param size * the number of items in the list (will be overridden if search * mode) * @param searchModeStatus * "1" if the widget is a search instead of a filter * @return */ private Document requestDummyDocumentList(String alfrescoName, String size, String searchModeStatus) { Document doc = docBuilder.newDocument(); int nb = Integer.parseInt(size); if (nb == 0) { nb = 10; } if (StringUtils.equals(searchModeStatus, "1")) { // override nb = 0; } Element root = doc.createElement("results"); Element query = doc.createElement("query"); Element count = doc.createElement("count"); count.setTextContent("" + nb); Element maxResults = doc.createElement("maxResults"); maxResults.setTextContent("0"); Element returned = doc.createElement("returned"); returned.setTextContent("" + nb); Element filteredOut = doc.createElement("filteredOut"); filteredOut.setTextContent("0"); Element typeFound = doc.createElement("typeFound"); typeFound.setTextContent("simulated"); Element subquery = doc.createElement("query"); query.appendChild(count); query.appendChild(maxResults); query.appendChild(returned); query.appendChild(filteredOut); query.appendChild(typeFound); query.appendChild(subquery); root.appendChild(query); for (int i = 0; i < nb; i++) { Element item = doc.createElement(MsgId.INT_INSTANCE_SELECT_ITEM.getText()); Element id = doc.createElement(MsgId.INT_INSTANCE_SELECT_ID.getText()); id.setTextContent("" + i); Element label = doc.createElement(MsgId.INT_INSTANCE_SELECT_LABEL.getText()); label.setTextContent(alfrescoName + "_" + i); Element qname = doc.createElement(MsgId.INT_INSTANCE_SELECT_TYPE.getText()); qname.setTextContent("type_" + alfrescoName + "_" + i); item.appendChild(id); item.appendChild(label); item.appendChild(qname); root.appendChild(item); } doc.appendChild(root); return doc; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Gets the result set for the list action by calling the webscript. This * function is called//w w w . j ava2 s. c o m * when a form is loaded (to provide the initial item set), and each time a * search is launched, * whether by character input or by a "launch search" button. * * @param transaction * the transaction * @param bean * a bean for parameters, will allow us to extend the parameter * set without changing * the signature * @return the list document * @throws ServletException */ public Node getList(AlfrescoTransaction transaction, ListActionBean bean) throws ServletException { // The use of trimToEmpty is for backward compatibility. String dataType = bean.getDataType(); String query = bean.getQuery(); String maxResults = bean.getMaxResults(); String format = StringUtils.trimToEmpty(bean.getFormat()); String maxLength = bean.getMaxLength(); String identifier = StringUtils.trimToEmpty(bean.getIdentifier()); String filterAssoc = StringUtils.trimToEmpty(bean.getFilterAssoc()); String compositionStatus = StringUtils.trimToEmpty(bean.getCompositionStatus()); String searchModeStatus = StringUtils.trimToEmpty(bean.getSearchMode()); String luceneQuery = StringUtils.trimToEmpty(bean.getLuceneQuery()); String dataSourceURI = StringUtils.trimToNull(bean.getDataSourceURI()); Map<String, String> parameters = new TreeMap<String, String>(); String type = null; /* * maxSize fixe le nombre d'lements afficher dans le widget, par * dfaut, MAX_RESULTS. Ce * nbre sera rinitialis par le bouton 'Tout'. Valeurs possibles: * MAX_RESULTS ("50" ou * celle indique ds forms.properties) ou fix par la proprit 'field * size' dans le * modeleur. Dans ce cas, SELECTMAX conserve tjrs la valeur de field * size. */ String maxSize = mappingAgent.getFieldSizeForField(dataType, "" + getParamMaxResults(transaction.getInitParams()), transaction.getFormId()); type = (identifier == null ? mappingAgent.getClassTypeAlfrescoName(dataType) : dataType); // always provided in the URI parameters.put("type", type); parameters.put("format", format); // always provided in the URI parameters.put("maxLength", maxLength); parameters.put("identifier", identifier); parameters.put("filterAssoc", filterAssoc); // always provided in the URI. parameters.put("isComposition", compositionStatus); // always provided in the URI. parameters.put("isSearchMode", searchModeStatus); parameters.put("luceneQuery", luceneQuery); String q = StringUtils.trimToNull(query); if (q != null) { parameters.put("query", q); } if (StringUtils.trimToNull(maxResults) != null) { parameters.put("maxResults", maxResults); } else { parameters.put("maxResults", maxSize); } Document reqDoc; if (isInStandaloneMode()) { // NOTE: we use the maxLength for indicating the number of items in the list! reqDoc = requestDummyDocumentList(type, maxLength, searchModeStatus); } else { if (dataSourceURI == null) { reqDoc = requestDocumentFromAlfresco(transaction, parameters, MsgId.INT_WEBSCRIPT_OPCODE_LIST); } else { // do not use default Xform webscript uri reqDoc = requestDocumentFromAlfresco(transaction, parameters, MsgId.INT_WEBSCRIPT_OPCODE_LIST, dataSourceURI); } // ** #1234 if (reqDoc == null) { if (logger.isErrorEnabled()) { logger.error("The Alfresco server is unavailable. Returning a dummy list."); } // setStandaloneMode(true); reqDoc = requestDummyDocumentList(type, maxLength, searchModeStatus); } // ** #1234 } Element docElement = reqDoc.getDocumentElement(); docElement.appendChild(reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDID.getText())); docElement.appendChild(reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDLABEL.getText())); docElement.appendChild(reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDTYPE.getText())); Element maxResultsElement = reqDoc.createElement(MsgId.INT_INSTANCE_SELECTEDMAX.getText()); maxResultsElement.setTextContent(maxSize); docElement.appendChild(maxResultsElement); return reqDoc; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Extracts the id to be edited from an XForms instance. The DOM node * providing that id must be//from ww w . ja va 2s. c o m * reset (i.e. emptied) so that subsequent editions can happen correctly on * the same form. * * @param node * @return the id, or null (this latter case should not happen if the Edit * button's action of * setting the <edit id> in the instance is done correctly). */ public EditNodeBean getEditNodeAndReset(Node node) { Element rootElt = ((Document) node).getDocumentElement(); // find the edit id element Element editIdElt = DOMUtil.getElementInDescentByNameNonNull(rootElt, MsgId.INT_INSTANCE_SIDEEDIT.getText()); if (editIdElt != null) { String id = editIdElt.getTextContent(); editIdElt.setTextContent(null); // <- reset the id. MANDATORY. // get the data type // #1510 String dataType = null; try { Element parent = (Element) editIdElt.getParentNode(); Element typeElt = DOMUtil.getChild(parent, MsgId.INT_INSTANCE_SIDETYPE.getText()); if (typeElt != null) { dataType = typeElt.getTextContent(); } } catch (Exception e) { // nothing to do } if (logger.isDebugEnabled()) { logger.debug("Getting edit id, found: '" + id + "' with data type: '" + dataType + "'"); } return new EditNodeBean(id, dataType); } if (logger.isErrorEnabled()) { logger.error("No id found for node edition."); } return null; }
From source file:it.imtech.metadata.MetaUtility.java
private void create_uwmetadata_recursive(Document w, Element e, Map<Object, Metadata> submetadatas, HashMap<String, String> defValues, int pagenum, String collTitle, String panelname) throws Exception { try {//from w w w. java 2s.co m ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader); boolean classificationtag = false; String expression = "//*[local-name()='classification']"; XPath xpath = XPathFactory.newInstance().newXPath(); for (Map.Entry<Object, Metadata> field : submetadatas.entrySet()) { String oefospath = panelname + "----" + field.getValue().sequence; if (field.getValue().MID == 2) { this.objectTitle = field.getValue().value; } if (field.getValue().datatype.equals("Node")) { if (field.getValue().MID == 45 && this.oefos_path.get(oefospath) == null) { continue; } else if (field.getValue().MID == 45 && this.oefos_path.get(oefospath).size() < 1) { continue; } else { //Set classification tag NodeList nodeList = (NodeList) xpath.evaluate(expression, w, XPathConstants.NODESET); String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace); Element link = w.createElement(book + ":" + field.getValue().foxmlname); if (!field.getValue().sequence.equals("") && field.getValue().MID != 45) e.setAttribute("seq", field.getValue().sequence); if ((field.getValue().MID != 22 && field.getValue().MID != 45) || nodeList.getLength() <= 0) e.appendChild(link); else { if (field.getValue().MID == 45) { nodeList.item(0).appendChild(link); } } create_uwmetadata_recursive(w, link, field.getValue().submetadatas, defValues, pagenum, collTitle, panelname); } } else if (field.getValue().MID == 46) { //Set source tag if (this.oefos_path.get(oefospath).size() > 0) { String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace); Element link = w.createElement(book + ":" + field.getValue().foxmlname); String classiflink = this.selectedClassificationList .get(panelname + "---" + field.getValue().sequence); String CID = this.classificationIDS.get(classiflink); link.setTextContent(CID); e.appendChild(link); } } else if (field.getValue().MID == 47 && this.oefos_path.get(oefospath).size() > 0) { //Set taxonpaths tags for (Map.Entry<Integer, Integer> iField : this.oefos_path.get(oefospath).entrySet()) { String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace); Element link = w.createElement(book + ":" + field.getValue().foxmlname); link.setTextContent(Integer.toString(iField.getValue())); link.setAttribute("seq", Integer.toString(iField.getKey() - 1)); e.setAttribute("seq", field.getValue().sequence); e.appendChild(link); } } else if (field.getValue().editable.equals("Y")) { String value = ""; if (field.getValue().value != null) { if (field.getValue().MID == 2 && !collTitle.equals("")) value = collTitle; else { if (field.getValue().MID == 2 && pagenum > 0) { value = field.getValue().value + " - " + Utility.getBundleString("seite", bundle) + " " + Integer.toString(pagenum); } else { value = field.getValue().value; } } } else if (defValues != null) { if (defValues.containsKey(field.getValue().foxmlname)) { value = defValues.get(field.getValue().foxmlname); } else { value = "en"; } } if (value.length() > 0) { String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace); Element link = w.createElement(book + ":" + field.getValue().foxmlname); if (field.getValue().datatype.equals("LangString")) { link.setAttribute("language", field.getValue().language); } link.setTextContent(value); if (!field.getValue().sequence.equals("")) e.setAttribute("seq", field.getValue().sequence); e.appendChild(link); if (field.getValue().datatype.equals("CharacterString") && field.getValue().MID == 63) { bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader); //String text = ; //String title= ; ConfirmDialog confirm = new ConfirmDialog(BookImporter.getInstance(), true, Utility.getBundleString("singlemetadata1title", bundle), Utility.getBundleString("singlemetadata1", bundle), Utility.getBundleString("confirm", bundle), Utility.getBundleString("annulla", bundle)); Element type = w.createElement(book + ":type"); type.setTextContent("institution"); e.appendChild(type); } } } else if (field.getValue().editable.equals("N") && defValues != null) { String value = null; if (field.getValue().foxmlname.equals("location")) { value = SelectedServer.getInstance(null).getPhaidraURL() + "/" + defValues.get("identifier"); value = defValues.get("identifier"); } else { value = defValues.get(field.getValue().foxmlname); } String book = Utility.getValueFromKey(metadata_namespaces, field.getValue().foxmlnamespace); Element link = w.createElement(book + ":" + field.getValue().foxmlname); link.setTextContent(value); e.appendChild(link); } } } catch (Exception ex) { ResourceBundle bundle = ResourceBundle.getBundle(Globals.RESOURCES, Globals.CURRENT_LOCALE, Globals.loader); throw new Exception(Utility.getBundleString("error7", bundle) + ": " + ex.getMessage()); } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Creates a new element node for the provided document. * //w ww. j a va 2 s . c o m * @param doc * The document for that the node shall be created. * @param namespaceUri * The name space uri of the node to create. This may be null. * @param prefix * The prefix to use. * @param tagName * The tag name of the node. * @param textContent * The text content of the node. This may be null. * @return Returns the created node. * @throws Exception * Thrown if anything fails. */ public static Element createElementNode(final Document doc, final String namespaceUri, final String prefix, final String tagName, final String textContent) throws Exception { Element newNode = doc.createElementNS(namespaceUri, tagName); newNode.setPrefix(prefix); if (textContent != null) { newNode.setTextContent(textContent); } return newNode; }
From source file:eu.semaine.util.XMLTool.java
/** * Create an XML document from the given XPath expression. * The given string is interpreted as a limited subset of XPath expressions and split into parts. * Each part except the last one is expected to follow precisely the following form: * <code>"/" ( prefix ":" ) ? localname ( "[" "@" attName "=" "'" attValue "'" "]" ) ?</code> * The last part must be either/*from ww w .j ava2s.co m*/ * <code> "/" "text()"</code> * or * </code> "/" "@" attributeName </code>. * @param xpathExpression an xpath expression from which the given document can be created. must not be null. * @param value the value to insert at the location identified by the xpath expression. if this is null, the empty string is added. * @param namespaceContext the namespace context to use for resolving namespace prefixes. * If this is null, the namespace context returned by {@link #getDefaultNamespaceContext()} will be used. * @param document if not null, the xpath expression + value pair will be added to the document. * If null, a new document will be created from the xpathExpression and value pair. * @return a document containing the given information * @throws NullPointerException if xpathExpression is null. * @throws IllegalArgumentException if the xpath expression is not valid, or if the xpath expression is incompatible with the given document (e.g., different root node) */ public static Document xpath2doc(String xpathExpression, String value, NamespaceContext namespaceContext, Document document) throws NullPointerException, IllegalArgumentException { if (xpathExpression == null) { throw new NullPointerException("null argument"); } if (value == null) { value = ""; } if (namespaceContext == null) { namespaceContext = getDefaultNamespaceContext(); } String[][] parts = splitXPathIntoParts(xpathExpression); Element currentElt = null; for (int i = 0; i < parts.length - 1; i++) { String[] part = parts[i]; assert part != null; assert part.length == 4; String prefix = part[0]; String localName = part[1]; String attName = part[2]; String attValue = part[3]; String namespaceURI = prefix != null ? namespaceContext.getNamespaceURI(prefix) : null; if (prefix != null && namespaceURI.equals("")) { throw new IllegalArgumentException("Unknown prefix: " + prefix); } // Now traverse to or create element defined by prefix, localName and namespaceURI if (currentElt == null) { // at top level if (document == null) { // create a new document try { document = XMLTool.newDocument(localName, namespaceURI); } catch (DOMException de) { throw new IllegalArgumentException("Cannot create document for localname '" + localName + "' and namespaceURI '" + namespaceURI + "'", de); } currentElt = document.getDocumentElement(); currentElt.setPrefix(prefix); } else { currentElt = document.getDocumentElement(); if (!currentElt.getLocalName().equals(localName)) { throw new IllegalArgumentException( "Incompatible root node specification: expression requests '" + localName + "', but document already has '" + currentElt.getLocalName() + "'!"); } String currentNamespaceURI = currentElt.getNamespaceURI(); if (!(currentNamespaceURI == null && namespaceURI == null || currentNamespaceURI != null && currentNamespaceURI.equals(namespaceURI))) { throw new IllegalArgumentException( "Incompatible root namespace specification: expression requests '" + namespaceURI + "', but document already has '" + currentNamespaceURI + "'!"); } } } else { // somewhere in the tree // First check if the requested child already exists List<Element> sameNameChildren = XMLTool.getChildrenByLocalNameNS(currentElt, localName, namespaceURI); boolean found = false; if (attName == null) { if (sameNameChildren.size() > 0) { currentElt = sameNameChildren.get(0); found = true; } } else { for (Element c : sameNameChildren) { if (c.hasAttribute(attName)) { if (attValue == null || attValue.equals(c.getAttribute(attName))) { currentElt = c; found = true; break; } } } } if (!found) { // need to create it currentElt = XMLTool.appendChildElement(currentElt, localName, namespaceURI); if (prefix != null) currentElt.setPrefix(prefix); if (attName != null) { currentElt.setAttribute(attName, attValue != null ? attValue : ""); } } } } if (currentElt == null) { throw new IllegalArgumentException( "No elements or no final part created from XPath expression '" + xpathExpression + "'"); } String[] lastPart = parts[parts.length - 1]; assert lastPart.length <= 1; if (lastPart.length == 0) { // text content of the given node currentElt.setTextContent(value); } else { String attName = lastPart[0]; currentElt.setAttribute(attName, value); } return document; }