Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element getAttribute.

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

Usage

From source file:org.esa.snap.datamodel.metadata.AbstractMetadataIO.java

License:Open Source License

private static void parseTiePointGrids(final Product product, final Element tpgElem) throws IOException {
    final List tpgElements = tpgElem.getContent();
    for (Object o : tpgElements) {
        if (!(o instanceof Element))
            continue;

        final Element elem = (Element) o;
        final String name = elem.getName();
        final List content = elem.getContent();
        final List<Float> valueList = new ArrayList<>();
        int columnCount = 0;
        int rowCount = 0;
        for (Object row : content) {
            if (!(row instanceof Element))
                continue;
            final Element rowElem = (Element) row;
            final Attribute value = rowElem.getAttribute("value");

            int columns = parseTiePointGirdRow(value.getValue(), valueList);
            if (columnCount == 0)
                columnCount = columns;//from w  ww  .ja v  a 2  s .co m
            else if (columnCount != columns)
                throw new IOException(
                        "Metadata for tie-point-grid " + name + " has incorrect number of columns");
            ++rowCount;
        }

        addTiePointGrid(product, name, valueList, columnCount, rowCount);
    }

    // update GeoCoding
    setGeoCoding(product);
}

From source file:org.esa.snap.db.DBQuery.java

License:Open Source License

private static GregorianCalendar getCalendarDate(final Element elem) {
    final Attribute y = elem.getAttribute("year");
    final Attribute m = elem.getAttribute("month");
    final Attribute d = elem.getAttribute("day");
    if (y != null && m != null && d != null) {
        return new GregorianCalendar(Integer.parseInt(y.getValue()), Integer.parseInt(m.getValue()),
                Integer.parseInt(d.getValue()));
    }/*from w  w w.  ja  va2  s  .  co  m*/
    return null;
}

From source file:org.esa.snap.framework.dataop.downloadable.ftpUtils.java

License:Open Source License

public static Map<String, Long> readRemoteFileList(final ftpUtils ftp, final String server,
        final String remotePath) {

    boolean useCachedListing = true;
    final String tmpDirUrl = SystemUtils.getApplicationDataDir().getAbsolutePath();
    final File listingFile = new File(tmpDirUrl + "//" + server + ".listing.xml");
    if (!listingFile.exists())
        useCachedListing = false;//  w  w  w . j  a va2s  .  co m

    final Map<String, Long> fileSizeMap = new HashMap<>(900);

    if (useCachedListing) {
        Document doc = null;
        try {
            doc = XMLSupport.LoadXML(listingFile.getAbsolutePath());
        } catch (IOException e) {
            useCachedListing = false;
        }

        if (useCachedListing) {
            final Element root = doc.getRootElement();
            boolean listingFound = false;

            final List children1 = root.getContent();
            for (Object c1 : children1) {
                if (!(c1 instanceof Element))
                    continue;
                final Element remotePathElem = (Element) c1;
                final Attribute pathAttrib = remotePathElem.getAttribute("path");
                if (pathAttrib != null && pathAttrib.getValue().equalsIgnoreCase(remotePath)) {
                    listingFound = true;
                    final List children2 = remotePathElem.getContent();
                    for (Object c2 : children2) {
                        if (!(c2 instanceof Element))
                            continue;
                        final Element fileElem = (Element) c2;
                        final Attribute attrib = fileElem.getAttribute("size");
                        if (attrib != null) {
                            try {
                                fileSizeMap.put(fileElem.getName(), attrib.getLongValue());
                            } catch (Exception e) {
                                //
                            }
                        }
                    }
                }
            }
            if (!listingFound)
                useCachedListing = false;
        }
    }
    if (!useCachedListing) {
        try {
            final FTPFile[] remoteFileList = ftp.getRemoteFileList(remotePath);
            if (remoteFileList != null) {
                writeRemoteFileList(remoteFileList, server, remotePath, listingFile);

                for (FTPFile ftpFile : remoteFileList) {
                    fileSizeMap.put(ftpFile.getName(), ftpFile.getSize());
                }
            }
        } catch (Exception e) {
            System.out.println("Unable to get remote file list " + e.getMessage());
        }
    }

    return fileSizeMap;
}

From source file:org.esa.snap.productlibrary.rcp.toolviews.AOIMonitoring.model.AOI.java

License:Open Source License

private boolean load(final File file) {
    Document doc;/*from  www. j a va2s.c  o m*/
    try {
        doc = XMLSupport.LoadXML(file.getAbsolutePath());

        final Element root = doc.getRootElement();
        final Attribute nameAttrib = root.getAttribute("name");
        if (nameAttrib != null)
            this.name = nameAttrib.getValue();

        final List<GeoPos> geoPosList = new ArrayList<GeoPos>();

        final List<Content> children = root.getContent();
        for (Object aChild : children) {
            if (aChild instanceof Element) {
                final Element child = (Element) aChild;
                if (child.getName().equals("param")) {
                    inputFolder = XMLSupport.getAttrib(child, "inputFolder");
                    outputFolder = XMLSupport.getAttrib(child, "outputFolder");
                    processingGraph = XMLSupport.getAttrib(child, "graph");
                    lastProcessed = XMLSupport.getAttrib(child, "lastProcessed");
                    final Attribute findSlavesAttrib = child.getAttribute("findSlaves");
                    if (findSlavesAttrib != null)
                        findSlaves = Boolean.parseBoolean(findSlavesAttrib.getValue());
                    final Attribute maxSlavesAttrib = child.getAttribute("maxSlaves");
                    if (maxSlavesAttrib != null)
                        maxSlaves = Integer.parseInt(maxSlavesAttrib.getValue());
                } else if (child.getName().equals("points")) {
                    final List<Content> pntsList = child.getContent();
                    for (Object o : pntsList) {
                        if (o instanceof Element) {
                            final Element pntElem = (Element) o;
                            final String latStr = XMLSupport.getAttrib(pntElem, "lat");
                            final String lonStr = XMLSupport.getAttrib(pntElem, "lon");
                            if (!latStr.isEmpty() && !lonStr.isEmpty()) {
                                final float lat = Float.parseFloat(latStr);
                                final float lon = Float.parseFloat(lonStr);
                                geoPosList.add(new GeoPos(lat, lon));
                            }
                        }
                    }
                } else if (child.getName().equals(DBQuery.DB_QUERY)) {
                    slaveDBQuery = new DBQuery();
                    //todo slaveDBQuery.fromXML(child);
                }
            }
        }

        aoiPoints = geoPosList.toArray(new GeoPos[geoPosList.size()]);
    } catch (IOException e) {
        SnapApp.getDefault().handleError("Unable to load AOI", e);
        return false;
    }
    return true;
}

From source file:org.esa.snap.util.ftpUtils.java

License:Open Source License

public static Map<String, Long> readRemoteFileList(final ftpUtils ftp, final String server,
        final String remotePath) {

    boolean useCachedListing = true;
    final String tmpDirUrl = ResourceUtils.getApplicationUserTempDataDir().getAbsolutePath();
    final File listingFile = new File(tmpDirUrl + "//" + server + ".listing.xml");
    if (!listingFile.exists())
        useCachedListing = false;/*from  w  ww .  j  a v a 2  s.  c o m*/

    final Map<String, Long> fileSizeMap = new HashMap<>(900);

    if (useCachedListing) {
        Document doc = null;
        try {
            doc = XMLSupport.LoadXML(listingFile.getAbsolutePath());
        } catch (IOException e) {
            useCachedListing = false;
        }

        if (useCachedListing) {
            final Element root = doc.getRootElement();
            boolean listingFound = false;

            final List children1 = root.getContent();
            for (Object c1 : children1) {
                if (!(c1 instanceof Element))
                    continue;
                final Element remotePathElem = (Element) c1;
                final Attribute pathAttrib = remotePathElem.getAttribute("path");
                if (pathAttrib != null && pathAttrib.getValue().equalsIgnoreCase(remotePath)) {
                    listingFound = true;
                    final List children2 = remotePathElem.getContent();
                    for (Object c2 : children2) {
                        if (!(c2 instanceof Element))
                            continue;
                        final Element fileElem = (Element) c2;
                        final Attribute attrib = fileElem.getAttribute("size");
                        if (attrib != null) {
                            try {
                                fileSizeMap.put(fileElem.getName(), attrib.getLongValue());
                            } catch (Exception e) {
                                //
                            }
                        }
                    }
                }
            }
            if (!listingFound)
                useCachedListing = false;
        }
    }
    if (!useCachedListing) {
        try {
            final FTPFile[] remoteFileList = ftp.getRemoteFileList(remotePath);

            writeRemoteFileList(remoteFileList, server, remotePath, listingFile);

            for (FTPFile ftpFile : remoteFileList) {
                fileSizeMap.put(ftpFile.getName(), ftpFile.getSize());
            }
        } catch (Exception e) {
            System.out.println("Unable to get remote file list " + e.getMessage());
        }
    }

    return fileSizeMap;
}

From source file:org.fnppl.opensdx.common.Util.java

License:Open Source License

/**
 * check if the languagecode is part of the openSDX_languages.xsd 
 * (keep in mind that this is case sensitive)
 * @param languagecode language to check
 * @return true if valid else false//w  ww  .  j a v  a  2s. c o  m
 * @author Michael Witt <m.witt@finetunes.net>
 * @throws Exception 
 */
public static boolean languageCodeExistsInXSD(String languagecode) throws Exception {
    if (languages == null) {

        org.jdom2.input.SAXBuilder sax = new org.jdom2.input.SAXBuilder();
        org.jdom2.filter.ElementFilter filter = new org.jdom2.filter.ElementFilter("enumeration");
        org.jdom2.Document doc = sax.build(org.fnppl.opensdx.dmi.FeedValidator.class.getResourceAsStream(
                "resources/" + org.fnppl.opensdx.dmi.FeedValidator.RESSOURCE_OSDX_0_0_1_LANGUAGES));

        languages = new HashSet<String>();
        for (org.jdom2.Element e : doc.getRootElement().getDescendants(filter)) {
            languages.add(e.getAttribute("value").getValue());
        }
    }

    return languages.contains(languagecode);
}

From source file:org.fnppl.opensdx.dmi.wayin.PieToOpenSDXImporter.java

License:Open Source License

private Feed getImportFeed() {
    // do the import
    Feed feed = null;//from www .  j a v a2s .  co m

    try {
        // (1) get XML-Data from import document
        Document impDoc = Document.fromFile(this.importFile);
        Element root = impDoc.getRootElement();

        //(1.1) sets the activen namespace for this root element to avoid parameter overhead for all Element getters.
        root.setActiveNamespace(root.getNamespace());

        // (2) get FeedInfo from import and create feedid and new FeedInfo for openSDX
        String feedid = UUID.randomUUID().toString();
        Calendar cal = Calendar.getInstance();

        long creationdatetime = cal.getTimeInMillis();
        long effectivedatetime = cal.getTimeInMillis();

        String lic = root.getChildTextNN("provider");
        if (lic.length() == 0)
            lic = "[NOT SET]";

        ContractPartner sender = ContractPartner.make(ContractPartner.ROLE_SENDER, lic, "1");
        ContractPartner licensor = ContractPartner.make(ContractPartner.ROLE_LICENSOR, lic, "1");
        ContractPartner licensee = ContractPartner.make(ContractPartner.ROLE_LICENSEE, "1", "1");

        FeedInfo feedinfo = FeedInfo.make(onlytest, feedid, creationdatetime, effectivedatetime, sender,
                licensor, licensee);

        // (3) create new feed with feedinfo
        feed = Feed.make(feedinfo);

        // path to importfile
        String path = this.importFile.getParent() + File.separator;

        Element album = root.getChild("album");

        // Information
        String streetReleaseDate = album.getChildTextNN("original_release_date");
        if (streetReleaseDate.length() > 0) {
            cal.setTime(ymd.parse(streetReleaseDate));
        } else {
            // MUST: when not provided then today
            cal.setTime(new Date());
        }

        // streetRelease = physicalRelease (?)
        long srd = cal.getTimeInMillis();
        long prd = cal.getTimeInMillis();

        BundleInformation info = BundleInformation.make(srd, prd);

        // language
        if (root.getChild("language") != null && root.getChildTextNN("language").length() > 0) {
            info.main_language(root.getChildText("language").substring(0, 2));
        }

        // IDs of bundle -> more (?)
        IDs bundleids = IDs.make();
        if (album.getChild("upc") != null)
            bundleids.upc(album.getChildTextNN("upc"));

        // displayname
        String displayname = album.getChildTextNN("title");

        // display_artistname
        String display_artistname = null; //album.getChildTextNN("album_display_artist");
        //Get first performer
        Vector<Element> contributors = album.getChild("artists").getChildren("artist");
        for (Iterator<Element> itContributors = contributors.iterator(); itContributors.hasNext();) {
            Element contributor = itContributors.next();
            if (contributor.getChild("roles") != null
                    && contributor.getChild("roles").getChild("role") != null) {
                String role = contributor.getChild("roles").getChildTextNN("role").trim().toLowerCase();
                if (role.equals("performer") && "true".equals(contributor.getChildText("primary"))) {
                    display_artistname = contributor.getChildTextNN("artist_name");
                    break;
                }
            }
        }

        // license basis
        Territorial territorial = Territorial.make();

        // Release
        LicenseBasis license_basis = LicenseBasis.make(territorial, srd, prd);

        // license specifics -> empty!
        LicenseSpecifics license_specifics = LicenseSpecifics.make();

        // receiver -> "MUST" -> empty!
        Receiver rec = Receiver.make(Receiver.TRANSFER_TYPE_OSDX_FILESERVER);
        rec.servername("servername");
        rec.serveripv4("0.0.0.0");
        rec.authtype("login");
        rec.username("testuser");
        feedinfo.receiver(rec);

        // Album Territories, Streaming and Download
        HashMap<String, Element> albumTerritories = new HashMap<String, Element>(); //Global album territories to match with Pies track territories
        boolean downloadAllowed = false;
        boolean streamingAllowed = false;

        //calculate major streaming & sales date
        HashMap<String, String> majorDates = calculateDateMajorities(
                album.getChild("products").getChildren("product").iterator());

        Element albumProducts = album.getChild("products");
        if (albumProducts != null) {
            Vector<Element> products = albumProducts.getChildren("product");
            if (products != null && products.size() > 0) {
                for (Element p : products) {
                    albumTerritories.put(p.getChildTextNN("territory"), p); //Puts the current territory for later track territory comparison
                    String territory = p.getChildText("territory");
                    if (forceImport) {
                        //no rules necessary, just import. Download and streaming allowed = true, streaming start & enddate are the regular releasedate
                        downloadAllowed = true;
                        streamingAllowed = true;
                        territorial.allow(territory);
                    } else {
                        downloadAllowed |= p.getChildBoolean("cleared_for_sale", false);
                        streamingAllowed |= p.getChildBoolean("cleared_for_stream", false);
                        if (p.getChildBoolean("cleared_for_sale", false)
                                || p.getChildBoolean("cleared_for_stream", false)) {
                            territorial.allow(territory);
                            //rules in case <sales_start_date> != <stream_start_date>
                            if (!p.getChildTextNN("sales_start_date")
                                    .equals(p.getChildTextNN("stream_start_date"))) {
                                //add rule
                                LicenseRule rule = LicenseRule.make(1, "streaming_allowed", "equals", "true");
                                rule.addThenProclaim("timeframe_from", p.getChildTextNN("sales_start_date"));
                                license_specifics.addRule(rule);
                            }

                            if (!p.getChildTextNN("sales_start_date").equals(majorDates.get("sales"))) {
                                //add rule for sales
                                LicenseRule rule = LicenseRule.make(2, "territory", "equals", territory);
                                rule.addThenProclaim("timeframe_from", majorDates.get("sales"));
                                license_specifics.addRule(rule);
                            }

                            if (!p.getChildTextNN("stream_start_date").equals(majorDates.get("stream"))) {
                                //add rule for streaming
                                LicenseRule rule = LicenseRule.make(3, "territory", "equals", territory);
                                rule.addThenProclaim("streaming_timeframe_from", majorDates.get("stream"));
                                license_specifics.addRule(rule);
                            }
                        } else {
                            territorial.disallow(territory);
                        }
                    }
                }
            }
        }

        //allow download and streaming based on territories.
        license_basis.download_allowed(downloadAllowed);
        license_basis.streaming_allowed(streamingAllowed);

        Bundle bundle = Bundle.make(bundleids, displayname, displayname, "", display_artistname, info,
                license_basis, license_specifics);

        // add contributor label
        Contributor con = Contributor.make(album.getChildTextNN("label_name"), Contributor.TYPE_LABEL,
                IDs.make());
        bundle.addContributor(con);

        // add contributor display_artist
        con = Contributor.make(display_artistname, Contributor.TYPE_DISPLAY_ARTIST, IDs.make());
        bundle.addContributor(con);

        contributors = album.getChild("artists").getChildren("artist");
        for (Iterator<Element> itContributors = contributors.iterator(); itContributors.hasNext();) {
            Element contributor = itContributors.next();

            if (contributor.getChild("roles") != null
                    && contributor.getChild("roles").getChild("role") != null) {
                String role = contributor.getChild("roles").getChildTextNN("role").trim().toLowerCase();
                if (role.equals("performer")) {
                    con = Contributor.make(contributor.getChildTextNN("artist_name"),
                            Contributor.TYPE_PERFORMER, IDs.make());
                } else if (role.equals("featuring")) {
                    con = Contributor.make(contributor.getChildTextNN("artist_name"),
                            Contributor.TYPE_FEATURING, IDs.make());
                } else if (role.equals("composer")) {
                    con = Contributor.make(contributor.getChildTextNN("artist_name"), Contributor.TYPE_COMPOSER,
                            IDs.make());
                } else if (role.equals("producer")) {
                    con = Contributor.make(contributor.getChildTextNN("artist_name"), Contributor.TYPE_PRODUCER,
                            IDs.make());
                }

                // Maybe more roles? Insert!

                bundle.addContributor(con);
            } else {
                con = Contributor.make(contributor.getChildTextNN("artist_name"), Contributor.TYPE_PERFORMER,
                        IDs.make());
                bundle.addContributor(con);
            }
        }

        String copyright = album.getChildTextNN("copyright_cline");
        String production = album.getChildTextNN("copyright_pline");

        if (copyright.length() > 0) {
            con = Contributor.make(copyright.substring(5), Contributor.TYPE_COPYRIGHT, IDs.make());
            con.year(copyright.substring(0, 4));
            bundle.addContributor(con);
        }

        if (production.length() > 0) {
            con = Contributor.make(production.substring(5), Contributor.TYPE_PRODUCTION, IDs.make());
            con.year(production.substring(0, 4));
            bundle.addContributor(con);
        }

        // cover: license_basis & license_specifics from bundle, right?           
        if (album.getChild("artwork_files") != null
                && album.getChild("artwork_files").getChild("file") != null) {
            Element cover = album.getChild("artwork_files").getChild("file");

            ItemFile itemfile = ItemFile.make();
            itemfile.type("frontcover");
            // check if file exist at path
            String filename = cover.getChildTextNN("file_name");
            File f = new File(path + filename);
            if (f != null && f.exists()) {
                itemfile.setFile(f);

                // set delivered path to file 
                itemfile.setLocation(FileLocation.make(filename, filename));
            } else {
                //file does not exist -> so we have to set the values "manually"

                //-> use filename for location
                itemfile.setLocation(FileLocation.make(filename, filename));

                //file size
                if (cover.getChild("size") != null) {
                    itemfile.bytes(Integer.parseInt(cover.getChildText("size")));
                }

                // checksum md5
                if (cover.getChild("checksum") != null) {
                    Element cs = cover.getChild("checksum");
                    if (cs != null) {
                        if (cs.getAttribute("type").equals("md5")) {
                            String sMd5 = cover.getChildText("checksum");
                            byte[] md5 = SecurityHelper.HexDecoder.decode(sMd5);
                            itemfile.checksums(Checksums.make().md5(md5));
                        }
                    }
                }
            }

            bundle.addFile(itemfile);
        }

        // init GenreConverter
        GenreConverter gc = GenreConverter.getInstance(GenreConverter.PIE_TO_OPENSDX);

        // add Tags
        ItemTags tags = ItemTags.make();

        Vector<Element> genres = album.getChild("genres").getChildren("genre");
        for (Iterator<Element> itGenres = genres.iterator(); itGenres.hasNext();) {
            Element genre = itGenres.next();
            tags.addGenre(gc.convert(genre.getAttribute("code")));
        }

        bundle.tags(tags);
        //           
        Vector<Element> tracks = album.getChild("tracks").getChildren("track");
        for (Iterator<Element> itTracks = tracks.iterator(); itTracks.hasNext();) {
            Element track = itTracks.next();

            IDs trackids = IDs.make();
            if (track.getChild("isrc") != null)
                trackids.isrc(track.getChildTextNN("isrc"));

            // displayname
            String track_displayname = track.getChildTextNN("title");

            // display_artistname / later set this to track artist if available
            String track_display_artistname = display_artistname;

            BundleInformation track_info = BundleInformation.make(srd, prd);

            // num
            if (track.getChildTextNN("number").length() > 0) {
                track_info.num(Integer.parseInt(track.getChildText("number")));
            }

            // setnum
            if (track.getChildTextNN("volume_number").length() > 0) {
                track_info.setnum(Integer.parseInt(track.getChildText("volume_number")));
            }

            // tracklength
            if (track.getChildTextNN("duration").length() > 0) {
                track_info.playlength(Integer.parseInt(track.getChildText("duration")));
            }

            // suggested prelistining offset
            if (track.getChild("preview_start_index") != null
                    && track.getChildTextNN("preview_start_index").length() > 0) {
                track_info.suggested_prelistening_offset(
                        Integer.parseInt(track.getChildText("preview_start_index")));
            }

            // track license basis
            LicenseBasis track_license_basis = LicenseBasis.make();

            Territorial track_territorial = Territorial.make();

            track_license_basis.setTerritorial(track_territorial);

            // license specifics -> empty!
            LicenseSpecifics track_license_specifics = LicenseSpecifics.make();

            // license_basis of Bundle / license_specifics of Bundle / others (?)
            Item item = Item.make(trackids, track_displayname, track_display_artistname, "", "audio",
                    track_display_artistname, track_info, track_license_basis, track_license_specifics);

            contributors = track.getChild("artists").getChildren("artist");
            for (Iterator<Element> itContributors = contributors.iterator(); itContributors.hasNext();) {
                Element contributor = itContributors.next();

                boolean display_artist_isSet = false;
                if (contributor.getChild("primary") != null) {
                    if (contributor.getChildTextNN("primary").equals("true") && !display_artist_isSet) {
                        item.display_artistname(contributor.getChildTextNN("artist_name"));
                        display_artist_isSet = true;
                    }
                }

                if (contributor.getChild("roles") != null
                        && contributor.getChild("roles").getChild("role") != null) {
                    String role = contributor.getChild("roles").getChildTextNN("role").trim().toLowerCase();
                    if (role.equals("performer")) {
                        con = Contributor.make(contributor.getChildTextNN("artist_name"),
                                Contributor.TYPE_PERFORMER, IDs.make());
                    } else if (role.equals("featuring")) {
                        con = Contributor.make(contributor.getChildTextNN("artist_name"),
                                Contributor.TYPE_FEATURING, IDs.make());
                    } else if (role.equals("composer")) {
                        con = Contributor.make(contributor.getChildTextNN("artist_name"),
                                Contributor.TYPE_COMPOSER, IDs.make());
                    } else if (role.equals("producer")) {
                        con = Contributor.make(contributor.getChildTextNN("artist_name"),
                                Contributor.TYPE_PRODUCER, IDs.make());
                    }

                    // Maybe more roles? Insert!

                    item.addContributor(con);
                } else {
                    con = Contributor.make(contributor.getChildTextNN("name"), Contributor.TYPE_PERFORMER,
                            IDs.make());
                    item.addContributor(con);
                }
            }

            // Check if track territory equal to those on bundle level
            if (forceImport) {
                //In case of force import, just like on bundle (Just allow everything)
                track_license_basis.as_on_bundle(true);
            } else {
                boolean asOnBundle = asOnBundle(albumTerritories,
                        track.getChild("products").getChildren("product"));
                if (asOnBundle) {
                    track_license_basis.as_on_bundle(asOnBundle);
                } else {
                    //Check track territories again.
                    Vector<Element> tmp = track.getChild("products").getChildren("product");
                    for (Element t : tmp) {
                        String territory = t.getChildText("territory");
                        if (t.getChildBoolean("cleared_for_sale", false)
                                || t.getChildBoolean("cleared_for_stream", false)) {
                            track_territorial.allow(territory);
                        } else {
                            track_territorial.disallow(territory);
                        }
                    }
                }
            }

            // add Tags
            ItemTags track_tags = ItemTags.make();

            Vector<Element> track_genres = track.getChild("genres").getChildren("genre");
            for (Iterator<Element> itTrackGenres = track_genres.iterator(); itTrackGenres.hasNext();) {
                Element genre = itTrackGenres.next();
                tags.addGenre(gc.convert(genre.getAttribute("code")));
            }

            item.tags(track_tags);

            Element audioFile = track.getChild("audio_file");
            // check if file exist at path (Optional, in case of an update XML this element may be missing)
            if (audioFile != null) {
                ItemFile itemfile = ItemFile.make();
                itemfile.type("full");
                String filename = track.getChild("audio_file").getChildTextNN("file_name");
                File f = new File(path + filename);
                if (f != null && f.exists()) {
                    itemfile.setFile(f); //this will also set the filesize and calculate the checksums

                    // set delivered path to file 
                    itemfile.setLocation(FileLocation.make(filename, filename));
                } else {
                    //file does not exist -> so we have to set the values "manually"

                    //-> use filename as location
                    itemfile.setLocation(FileLocation.make(filename, filename));

                    //file size
                    if (track.getChild("audio_file").getChild("size") != null) {
                        itemfile.bytes(Integer.parseInt(track.getChild("audio_file").getChildText("size")));
                    }

                    // checksum md5
                    if (track.getChild("audio_file").getChild("checksum") != null) {
                        Element cs = track.getChild("audio_file").getChild("checksum");
                        if (cs != null) {
                            if (cs.getAttribute("type").equals("md5")) {
                                String sMd5 = cs.getText();
                                byte[] md5 = SecurityHelper.HexDecoder.decode(sMd5);
                                itemfile.checksums(Checksums.make().md5(md5));
                            }
                        }
                    }

                }
                item.addFile(itemfile);
            }

            bundle.addItem(item);
        }

        feed.addBundle(bundle);

    } catch (Exception e) {
        e.printStackTrace();
        ir.succeeded = false;
        ir.errorMessage = e.getMessage();
        ir.exception = e;
    }
    return feed;
}

From source file:org.geoserver.backuprestore.web.ResourceFilePanel.java

License:Open Source License

/** @param target */
private void doUpdate(final AjaxRequestTarget target, final String valueAsString) {
    Catalog catalog = GeoServerApplication.get().getCatalog();

    // use what the user currently typed
    File file = null;//from   w w  w .  j a  v  a2  s.  c o  m
    if (!valueAsString.trim().equals("")) {
        file = new File(valueAsString);
        if (!file.exists() || file.isDirectory()) {
            file = null;
            workspaces = null;
            stores = null;
            layers = null;
        }
    }

    List<WorkspaceInfo> workspaceInfos = new ArrayList<WorkspaceInfo>();
    Map<String, List<StoreInfo>> storeInfos = new HashMap<String, List<StoreInfo>>();
    Map<String, List<LayerInfo>> layerInfos = new HashMap<String, List<LayerInfo>>();
    try {
        if (file != null) {
            Resource archiveFile = Files.asResource(file);
            if (Resources.exists(archiveFile) && archiveFile.getType() != Type.DIRECTORY) {
                Resource tmpDir = BackupUtils.geoServerTmpDir(
                        new GeoServerDataDirectory(GeoServerApplication.get().getResourceLoader()));

                try {
                    BackupUtils.extractTo(archiveFile, tmpDir);
                    Resource brCatalogIndex = tmpDir.get(AbstractCatalogBackupRestoreTasklet.BR_INDEX_XML);
                    if (Resources.exists(brCatalogIndex)) {
                        SAXBuilder saxBuilder = new SAXBuilder();
                        Document document = saxBuilder.build(brCatalogIndex.in());
                        Element classElement = document.getRootElement();
                        List<Element> workspaceList = classElement.getChildren("Workspace");

                        for (Element ws : workspaceList) {
                            String wsName = ws.getChild("Name").getText();
                            WorkspaceInfo workspace = catalog.getWorkspaceByName(wsName);
                            if (workspace == null) {
                                workspace = catalog.getFactory().createWorkspace();
                                workspace.setName(wsName);
                            }
                            workspaceInfos.add(workspace);

                            storeInfos.put(wsName, new ArrayList<StoreInfo>());
                            for (Element st : ws.getChildren("Store")) {
                                String stName = st.getChild("Name").getText();
                                String type = st.getAttribute("type").getValue();
                                StoreInfo store = null;
                                ResourceInfo resource = null;

                                if ("DataStoreInfo".equals(type)) {
                                    store = catalog.getDataStoreByName(stName);

                                    if (store == null) {
                                        store = catalog.getFactory().createDataStore();
                                        store.setName(stName);
                                    }
                                } else if ("CoverageStoreInfo".equals(type)) {
                                    store = catalog.getCoverageStoreByName(stName);

                                    if (store == null) {
                                        store = catalog.getFactory().createCoverageStore();
                                        store.setName(stName);
                                    }
                                }

                                if (store != null) {
                                    storeInfos.get(wsName).add(store);

                                    layerInfos.put(stName, new ArrayList<LayerInfo>());
                                    for (Element ly : st.getChildren("Layer")) {
                                        String lyName = ly.getChild("Name").getText();

                                        if ("DataStoreInfo".equals(type)) {
                                            resource = catalog.getFeatureTypeByName(lyName);

                                            if (resource == null) {
                                                resource = catalog.getFactory().createFeatureType();
                                                store.setWorkspace(workspace);
                                                resource.setStore(store);
                                                resource.setName(lyName);
                                            }
                                        } else if ("CoverageStoreInfo".equals(type)) {
                                            resource = catalog.getCoverageByName(lyName);

                                            if (resource == null) {
                                                resource = catalog.getFactory().createCoverage();
                                                store.setWorkspace(workspace);
                                                resource.setStore(store);
                                                resource.setName(lyName);
                                            }
                                        }

                                        LayerInfo layer = catalog.getLayerByName(lyName);
                                        if (layer == null) {
                                            layer = catalog.getFactory().createLayer();
                                            layer.setResource(resource);
                                            layer.setName(lyName);
                                        }
                                        layerInfos.get(stName).add(layer);
                                    }
                                }
                            }
                        }
                        workspaces = workspaceInfos;
                        stores = storeInfos;
                        layers = layerInfos;

                        Element filtersList = classElement.getChild("Filters");

                        for (Element filter : filtersList.getChildren("Filter")) {
                            if ("WorkspaceInfo".equals(filter.getAttribute("type").getValue())) {
                                wsFilter = ECQL.toFilter(filter.getChild("ECQL").getText());
                            }
                            if ("StoreInfo".equals(filter.getAttribute("type").getValue())) {
                                siFilter = ECQL.toFilter(filter.getChild("ECQL").getText());
                            }
                            if ("LayerInfo".equals(filter.getAttribute("type").getValue())) {
                                liFilter = ECQL.toFilter(filter.getChild("ECQL").getText());
                            }
                        }
                    }
                } finally {
                    if (tmpDir != null) {
                        tmpDir.delete();
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error occurred while parsing Backup/Restore Index.", e);
    }

    if (backupRestoreDataPage.get("workspace") != null) {
        backupRestoreDataPage.get("workspace").setDefaultModelObject(null);
        backupRestoreDataPage.get("store").setDefaultModelObject(null);
        backupRestoreDataPage.get("layer").setDefaultModelObject(null);
        target.add(backupRestoreDataPage.get("workspace"));
        target.add(backupRestoreDataPage.get("store"));
        target.add(backupRestoreDataPage.get("layer"));
    }
}

From source file:org.goobi.production.cli.helper.CopyProcess.java

License:Open Source License

private void initializePossibleDigitalCollections() {
    this.possibleDigitalCollection = new ArrayList<>();
    ArrayList<String> defaultCollections = new ArrayList<>();
    String filename = new Helper().getGoobiConfigDirectory() + "goobi_digitalCollections.xml";
    if (!StorageProvider.getInstance().isFileExists(Paths.get(filename))) {
        Helper.setFehlerMeldung("File not found: ", filename);
        return;/* ww w  . j  a v  a2 s .  c  o  m*/
    }
    this.digitalCollections = new ArrayList<>();
    try {
        /* Datei einlesen und Root ermitteln */
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(filename);
        Element root = doc.getRootElement();
        /* alle Projekte durchlaufen */
        List<Element> projekte = root.getChildren();
        for (Iterator<Element> iter = projekte.iterator(); iter.hasNext();) {
            Element projekt = iter.next();

            // collect default collections
            if (projekt.getName().equals("default")) {
                List<Element> myCols = projekt.getChildren("DigitalCollection");
                for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                    Element col = it2.next();

                    if (col.getAttribute("default") != null
                            && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                        digitalCollections.add(col.getText());
                    }

                    defaultCollections.add(col.getText());
                }
            } else {
                // run through the projects
                List<Element> projektnamen = projekt.getChildren("name");
                for (Iterator<Element> iterator = projektnamen.iterator(); iterator.hasNext();) {
                    Element projektname = iterator.next();
                    // all all collections to list
                    if (projektname.getText().equalsIgnoreCase(this.prozessKopie.getProjekt().getTitel())) {
                        List<Element> myCols = projekt.getChildren("DigitalCollection");
                        for (Iterator<Element> it2 = myCols.iterator(); it2.hasNext();) {
                            Element col = it2.next();

                            if (col.getAttribute("default") != null
                                    && col.getAttributeValue("default").equalsIgnoreCase("true")) {
                                digitalCollections.add(col.getText());
                            }

                            this.possibleDigitalCollection.add(col.getText());
                        }
                    }
                }
            }
        }
    } catch (JDOMException e1) {
        logger.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    } catch (IOException e1) {
        logger.error("error while parsing digital collections", e1);
        Helper.setFehlerMeldung("Error while parsing digital collections", e1);
    }

    if (this.possibleDigitalCollection.size() == 0) {
        this.possibleDigitalCollection = defaultCollections;
    }

    // if only one collection is possible take it directly

    if (isSingleChoiceCollection()) {
        this.digitalCollections.add(getDigitalCollectionIfSingleChoice());
    }
}

From source file:org.helm.notation2.MonomerFactory.java

License:Open Source License

private static Map<String, Map<String, Monomer>> buildMonomerDB(Element polymerList)
        throws MonomerException, IOException, JDOMException, CTKException, ChemistryException {
    Map<String, Map<String, Monomer>> map = new HashMap<String, Map<String, Monomer>>();
    List poplymers = polymerList.getChildren();

    Iterator i = poplymers.iterator();
    while (i.hasNext()) {
        Element polymer = (Element) i.next();
        Attribute polymerType = polymer.getAttribute(POLYMER_TYPE_ATTRIBUTE);

        Map idMonomerMap = new HashMap<String, Monomer>();

        List monomers = polymer.getChildren();
        Iterator it = monomers.iterator();
        while (it.hasNext()) {
            Element monomer = (Element) it.next();
            Monomer m = MonomerParser.getMonomer(monomer);
            if (MonomerParser.validateMonomer(m)) {
                idMonomerMap.put(m.getAlternateId(), m);
            }//w w w.j  a va 2s.  co m
        }
        map.put(polymerType.getValue(), idMonomerMap);
    }

    return map;
}