Package org.fao.geonet.kernel

Examples of org.fao.geonet.kernel.DataManager


     * @return
     * @throws Exception
     */
    public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception {
        GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
        DataManager dataMan = gc.getBean(DataManager.class);
        AccessManager accessMan = gc.getBean(AccessManager.class);

        String id = Utils.getIdentifierFromParameters(params, context);
        String groupOwner = Util.getParam(params, "groupid");

        int iLocalId = Integer.parseInt(id);
        if (!dataMan.existsMetadata(iLocalId)) {
            throw new IllegalArgumentException("Metadata with identifier '" + id + "' not found.");
        }

        if (!accessMan.canEdit(context, id)) {
            throw new OperationNotAllowedEx();
        }

        int iGroupOwner = Integer.parseInt(groupOwner);
        Group group = context.getBean(GroupRepository.class).findOne(iGroupOwner);
        if (group == null) {
            throw new IllegalArgumentException("Group with identifier '" + groupOwner + "' not found.");
        }

        //--- Update groupOwner
        MetadataRepository metadataRepository = context.getBean(MetadataRepository.class);
        Metadata metadata = metadataRepository.findOne(iLocalId);
        metadata.getSourceInfo().setGroupOwner(iGroupOwner);
        metadataRepository.save(metadata);

        //--- index metadata
        dataMan.indexMetadata(id, true);

        //--- return id for showing
        return new Element(Jeeves.Elem.RESPONSE).
                addContent(new Element(Geonet.Elem.ID).
                        setText(id));
View Full Code Here


  //--------------------------------------------------------------------------

  public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception
  {
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager   dm = gc.getBean(DataManager.class);
    UserSession   us = context.getUserSession();

    String id = Utils.getIdentifierFromParameters(params, context);
    boolean update = Util.getParam(params, Params.UPDATEONLY, "false").equals("true");

    //-----------------------------------------------------------------------
    //--- check access

    Metadata info = context.getBean(MetadataRepository.class).findOne(id);

    if (info == null)
      throw new MetadataNotFoundEx(id);

    //-----------------------------------------------------------------------
    //--- remove old operations

    boolean skip = false;

    //--- in case of owner, privileges for groups 0,1 and GUEST are disabled
    //--- and are not sent to the server. So we cannot remove them

    boolean isAdmin   = Profile.Administrator == us.getProfile();
    boolean isReviewer= Profile.Reviewer == us.getProfile();


    if (us.getUserIdAsInt() == info.getSourceInfo().getOwner() && !isAdmin && !isReviewer) {
      skip = true;
        }

    if (!update) {
      dm.deleteMetadataOper(context, id, skip);
    }
   
    //-----------------------------------------------------------------------
    //--- set new ones

    @SuppressWarnings("unchecked")
        List<Element> list = params.getChildren();

    for (Element el : list) {
      String name  = el.getName();

      if (name.startsWith("_"))
      {
        StringTokenizer st = new StringTokenizer(name, "_");

        String groupId = st.nextToken();
        String operId  = st.nextToken();

        if (!update) {
          dm.setOperation(context, id, groupId, operId);
        } else {
          boolean publish = "on".equals(el.getTextTrim());
          if (publish) {
            dm.setOperation(context, id, groupId, operId);
          } else {
            dm.unsetOperation(context, id, groupId, operId);
          }
        }
      }
    }

    //--- index metadata
        dm.indexMetadata(id, true);

        //--- return id for showing
    return new Element(Jeeves.Elem.RESPONSE).addContent(new Element(Geonet.Elem.ID).setText(id));
  }
View Full Code Here

    // -----------------------------------------------------------------------
    // --- check access

    GeonetContext gc = (GeonetContext) context
        .getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager dm = gc.getBean(DataManager.class);

    String id = Utils.getIdentifierFromParameters(params, context);

    if (!skipPopularity) { // skipPopularity could be a URL param as well
      String skip = Util.getParam(params, "skipPopularity", "n");
      skipPopularity = skip.equals("y");
    }

    if (id == null)
      throw new MetadataNotFoundEx("Metadata not found.");

    Lib.resource.checkPrivilege(context, id, ReservedOperation.view);

    // -----------------------------------------------------------------------
    // --- get metadata

    Element elMd;
    boolean addEditing = false;
    if (!skipInfo) {
            boolean withValidationErrors = false, keepXlinkAttributes = false;
      elMd = dm.getMetadata(context, id, addEditing, withValidationErrors, keepXlinkAttributes);
    } else {
      elMd = dm.getMetadataNoInfo(context, id);
    }

    if (elMd == null)
      throw new MetadataNotFoundEx(id);

    if (addRefs) { // metadata.show for GeoNetwork needs geonet:element
      elMd = dm.enumerateTree(elMd);
    }

    //
    // setting schemaLocation
    // TODO currently it's only set for ISO metadata - this should all move
    // to
    // the updatefixedinfo.xsl for each schema

    // do not set schemaLocation if it is already there
    if (elMd.getAttribute("schemaLocation", Csw.NAMESPACE_XSI) == null) {
      Namespace gmdNs = elMd.getNamespace("gmd");
      // document has ISO root element and ISO namespace
      if (gmdNs != null
          && gmdNs.getURI()
              .equals("http://www.isotc211.org/2005/gmd")) {
        String schemaLocation;
        // if document has srv namespace then add srv schemaLocation
        if (elMd.getNamespace("srv") != null) {
          schemaLocation = " http://www.isotc211.org/2005/srv http://schemas.opengis.net/iso/19139/20060504/srv/srv.xsd";
        }
        // otherwise add gmd schemaLocation
        // (but not both! as that is invalid, the schemas describe
        // partially the same schema types)
        else {
          schemaLocation = "http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/gmd.xsd";
        }
        Attribute schemaLocationA = new Attribute("schemaLocation",
            schemaLocation, Csw.NAMESPACE_XSI);
        elMd.setAttribute(schemaLocationA);
      }
    }

    // --- increase metadata popularity
    if (!skipPopularity)
      dm.increasePopularity(context, id);

    return elMd;
  }
View Full Code Here

  //---
  //--------------------------------------------------------------------------

  public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception {
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager   dataMan   = gc.getBean(DataManager.class);
    AccessManager accessMan = gc.getBean(AccessManager.class);
    UserSession   session   = context.getUserSession();

    Set<Integer> metadata = new HashSet<Integer>();
    Set<Integer> notFound = new HashSet<Integer>();
    Set<Integer> notOwner = new HashSet<Integer>();
        boolean backupFile = Util.getParam(params, Params.BACKUP_FILE, true);

        if(context.isDebugEnabled())
            context.debug("Get selected metadata");
    SelectionManager sm = SelectionManager.getManager(session);

    synchronized(sm.getSelection("metadata")) {
    for (Iterator<String> iter = sm.getSelection("metadata").iterator(); iter.hasNext();) {
      String uuid = (String) iter.next();
            if(context.isDebugEnabled())
                context.debug("Deleting metadata with uuid:"+ uuid);

      String id   = dataMan.getMetadataId(uuid);
      //--- Metadata may have been deleted since selection
      if (id != null) {
        //-----------------------------------------------------------------------
        //--- check access
 
        Metadata info = context.getBean(MetadataRepository.class).findOne(id);
 
        if (info == null) {
          notFound.add(Integer.valueOf(id));
        } else if (!accessMan.isOwner(context, id)) {
          notOwner.add(Integer.valueOf(id));
        } else {
 
          //--- backup metadata in 'removed' folder
          if (backupFile && info.getDataInfo().getType() != MetadataType.SUB_TEMPLATE) {
            backupFile(context, id, info.getUuid(), MEFLib.doExport(context, info.getUuid(), "full", false, true, false));
          }
     
          //--- remove the metadata directory
          File pb = new File(Lib.resource.getMetadataDir(context, id));
          FileCopyMgr.removeDirectoryOrFile(pb);
 
          //--- delete metadata and return status
          dataMan.deleteMetadata(context, id);
                    if(context.isDebugEnabled())
                        context.debug("  Metadata with id " + id + " deleted.");
          metadata.add(Integer.valueOf(id));
        }
      } else
View Full Code Here

  public Element exec(Element params, ServiceContext context) throws Exception
  {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager   dm   = gc.getBean(DataManager.class);
    UserSession session = context.getUserSession();

    String id = Utils.getIdentifierFromParameters(params, context);
    String access = Util.getParam(params, Params.ACCESS, Params.Access.PUBLIC);

    //--- resource required is public (thumbnails)
    if (access.equals(Params.Access.PUBLIC)) {
      File dir = new File(Lib.resource.getDir(context, access, id));
      String fname = Util.getParam(params, Params.FNAME);

      if (fname.contains("..")) {
        throw new BadParameterEx("Invalid character found in resource name.", fname);
      }
     
      File file = new File(dir, fname);
      return BinaryFile.encode(200, file.getAbsolutePath(),false);
    }

    //--- from here on resource required is private datafile(s)

    //--- check if disclaimer for this metadata has been displayed
    Element elData = (Element) session.getProperty(Geonet.Session.FILE_DISCLAIMER);
    if (elData == null) {
      return new Element("response");
    } else {
      String idAllowed = elData.getChildText(Geonet.Elem.ID);
      if (idAllowed == null || !idAllowed.equals(id)) {
        return new Element("response");
      }
    }

    //--- check whether notify is required
    boolean doNotify = false;
    Lib.resource.checkPrivilege(context, id, ReservedOperation.download);
    doNotify = true;

    //--- set username for emails and logs
    String username = session.getUsername();
    if (username == null) username = "internet";
    String userId  = session.getUserId();

    //--- get feedback/reason for download info passed in & record in 'entered'
//    String name     = Util.getParam(params, Params.NAME);
//    String org      = Util.getParam(params, Params.ORG);
//    String email    = Util.getParam(params, Params.EMAIL);
//    String comments = Util.getParam(params, Params.COMMENTS);
    Element entered = new Element("entered").addContent(params.cloneContent());
 
    //--- get logged in user details & record in 'userdetails'
    Element userDetails = new Element("userdetails");
    if (!username.equals("internet")) {
            final User user = context.getBean(UserRepository.class).findOne(userId);
      if (user != null) {
        userDetails.addContent(user.asXml());
      }
    }
 
    //--- get metadata info
    Metadata info = context.getBean(MetadataRepository.class).findOne(id);

    // set up zip output stream
    File zFile = File.createTempFile(username+"_"+info.getUuid(),".zip");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zFile));

    //--- because often content has already been compressed
     out.setLevel(Deflater.NO_COMPRESSION);

    //--- now add the files chosen from the interface and record in 'downloaded'
    Element downloaded = new Element("downloaded");
    File dir = new File(Lib.resource.getDir(context, access, id));

    @SuppressWarnings("unchecked")
        List<Element> files = params.getChildren(Params.FNAME);
    for (Element elem : files) {
      String fname = elem.getText();

      if (fname.contains("..")) {
        continue;
      }
     
      File file = new File(dir, fname);
      if (!file.exists()) throw new ResourceNotFoundEx(file.getAbsolutePath());

      Element fileInfo = new Element("file");

      Element details = BinaryFile.encode(200, file.getAbsolutePath(), false);
      String remoteURL = details.getAttributeValue("remotepath");
      if (remoteURL != null) {
                if(context.isDebugEnabled())
                    context.debug("Downloading "+remoteURL+" to archive "+zFile.getName());
        fileInfo.setAttribute("size","unknown");
        fileInfo.setAttribute("datemodified","unknown");
        fileInfo.setAttribute("name",remoteURL);
        notifyAndLog(doNotify, id, info.getUuid(), access, username, remoteURL+" (local config: "+file.getAbsolutePath()+")", context);
        fname = details.getAttributeValue("remotefile");
      } else {
                if(context.isDebugEnabled())
                    context.debug("Writing "+fname+" to archive "+zFile.getName());
        fileInfo.setAttribute("size",file.length()+"");
        fileInfo.setAttribute("name",fname);
        Date date = new Date(file.lastModified());
        fileInfo.setAttribute("datemodified",sdf.format(date));
        notifyAndLog(doNotify, id, info.getUuid(), access, username, file.getAbsolutePath(), context);
      }
      addFile(out, file.getAbsolutePath(), details, fname);
      downloaded.addContent(fileInfo);
    }

    //--- get metadata
        boolean forEditing = false, withValidationErrors = false, keepXlinkAttributes = false;
        Element elMd = dm.getMetadata(context, id, forEditing, withValidationErrors, keepXlinkAttributes);

    if (elMd == null)
      throw new MetadataNotFoundEx("Metadata not found - deleted?");

        //--- manage the download hook
View Full Code Here

 
  private void notifyAndLog(boolean doNotify, String id, String uuid, String access, String username, String theFile, ServiceContext context) throws Exception {

    GeonetContext  gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    SettingManager sm = gc.getBean(SettingManager.class);
    DataManager    dm = gc.getBean(DataManager.class);

    //--- increase metadata popularity
    if (access.equals(Params.Access.PRIVATE)) {
            dm.increasePopularity(context, id);
        }

    //--- send email notification
    if (doNotify) {
     
View Full Code Here

  public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception
  {
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);

    DataManager dataMan = gc.getBean(DataManager.class);

    String data       = Util.getParam(params, Params.DATA);
    String group      = Util.getParam(params, Params.GROUP);
        MetadataType metadataType = MetadataType.lookup(Util.getParam(params, Params.TEMPLATE, "n"));
    String style      = Util.getParam(params, Params.STYLESHEET, "_none_");

    boolean validate = Util.getParam(params, Params.VALIDATE, "off").equals("on");

//    Sub template does not need a title.
//     if (isTemplate.equals("s") && title.length() == 0)
//       throw new MissingParameterEx("title");

    //-----------------------------------------------------------------------
    //--- add the DTD to the input xml to perform validation

    Element xml = Xml.loadString(data, false);

        // Apply a stylesheet transformation if requested
        if (!style.equals("_none_"))
            xml = Xml.transform(xml, stylePath +"/"+ style);

        String schema = dataMan.autodetectSchema(xml);
        if (schema == null)
          throw new BadParameterEx("Can't detect schema for metadata automatically.", "schema is unknown");

    if (validate) DataManager.validateMetadata(schema, xml, context);

    //-----------------------------------------------------------------------
    //--- if the uuid does not exist and is not a template we generate it

    String uuid;
    if (metadataType == MetadataType.TEMPLATE)
    {
      uuid = dataMan.extractUUID(schema, xml);
      if (uuid.length() == 0) uuid = UUID.randomUUID().toString();
    }
    else uuid = UUID.randomUUID().toString();

    String uuidAction = Util.getParam(params, Params.UUID_ACTION,
        Params.NOTHING);

    String date = new ISODate().toString();

    final List<String> id = new ArrayList<String>();
    final List<Element> md = new ArrayList<Element>();
    md.add(xml);
   

        DataManager dm = gc.getBean(DataManager.class);

    // Import record
        Importer.importRecord(uuid, uuidAction, md, schema, 0,
                gc.getBean(SettingManager.class).getSiteId(), gc.getBean(SettingManager.class).getSiteName(), context, id, date,
        date, group, metadataType);
   
    int iId = Integer.parseInt(id.get(0));
   
   
    // Set template
    dm.setTemplate(iId, metadataType, null);

   
    // Import category
    String category   = Util.getParam(params, Params.CATEGORY, "");

    if (!category.equals("_none_") || !category.equals("")) {
      Element categs = new Element("categories");
      categs.addContent((new Element("category")).setAttribute(
          "name", category));

            final Metadata metadata = context.getBean(MetadataRepository.class).findOne(id.get(0));
            Importer.addCategoriesToMetadata(metadata , categs, context);
    }

    // Index
        dm.indexMetadata(id.get(0), true);

        // Return response
    Element response = new Element(Jeeves.Elem.RESPONSE);
    response.addContent(new Element(Params.ID).setText(String.valueOf(iId)));
          response.addContent(new Element(Params.UUID).setText(String.valueOf(dm.getMetadataUuid(id.get(0)))));

    return response;
  };
View Full Code Here

        }
        addElement(response, Params.ACCESS, access);

        //--- get metadata
        boolean forEditing = false, withValidationErrors = false, keepXlinkAttributes = false;
        final DataManager dataManager = context.getBean(DataManager.class);
        Element elMd = dataManager.getMetadata(context, id, forEditing, withValidationErrors, keepXlinkAttributes);

        if (elMd == null)
            throw new IllegalArgumentException("Metadata not found --> " + id);

        //--- place xml in metadata element
View Full Code Here

  //--------------------------------------------------------------------------

  public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception
  {
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager   dm = gc.getBean(DataManager.class);

    String child = Util.getParam(params, Params.CHILD, "n");
    String isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
    String id = "";
    String uuid = "";
    boolean haveAllRights = Boolean.valueOf(Util.getParam(params, Params.FULL_PRIVILEGES, "false"));
   
    // does the request contain a UUID ?
    try {
      uuid = Util.getParam(params, Params.UUID);
      // lookup ID by UUID
      id = dm.getMetadataId(uuid);
    }
    catch(BadInputEx x) {
      try {
        id = Util.getParam(params, Params.ID);
        uuid = dm.getMetadataUuid(id);
      }
      // request does not contain ID
      catch(BadInputEx xx) {
        // give up
        throw new Exception("Request must contain a UUID or an ID");
      }   
    }
   
    String groupOwner= Util.getParam(params, Params.GROUP);
   
    // TODO : Check user can create a metadata in that group
    UserSession user = context.getUserSession();
    if (user.getProfile() != Profile.Administrator) {
            final Specifications<UserGroup> spec = where(UserGroupSpecs.hasProfile(Profile.Editor))
                    .and(UserGroupSpecs.hasUserId(user.getUserIdAsInt()))
                    .and(UserGroupSpecs.hasGroupId(Integer.valueOf(groupOwner)));

            final List<UserGroup> userGroups = context.getBean(UserGroupRepository.class).findAll(spec);

      if (userGroups.size() == 0) {
        throw new ServiceNotAllowedEx("Service not allowed. User needs to be Editor in group with id " + groupOwner);
      }
    }
   
    //--- query the data manager

        String newId = dm.createMetadata(context, id, groupOwner,
                gc.getBean(SettingManager.class).getSiteId(), context.getUserSession().getUserIdAsInt(),
                          (child.equals("n")?null:uuid), isTemplate, haveAllRights);

        try {
          copyDataDir(context, id, newId, Params.Access.PUBLIC);
View Full Code Here

    @Override
    public void process() throws Exception {
        GeonetContext gc = (GeonetContext) context
                .getHandlerContext(Geonet.CONTEXT_NAME);
        DataManager dm = gc.getBean(DataManager.class);

        // Build replacements parameter for xslt process
        Element replacements = new Element("replacements");

        if (!StringUtils.isEmpty(params.getChildText("caseinsensitive"))) {
            Element caseInsensitiveEl = new Element("caseInsensitive").setText(params.getChildText("caseinsensitive"));
            replacements.addContent(caseInsensitiveEl);
        }

        List<Element> paramsList = params.getChildren();
        for (Element p: paramsList) {
            if (p.getName().startsWith("mdfield-")) {
                String key = p.getName().split("-")[1];

                String searchValue = params.getChildText("searchValue-" + key);
                String replaceValue = params.getChildText("replaceValue-" + key);

                Element replacement = new Element("replacement");
                replacement.addContent(new Element("field").setText(p.getText()));
                replacement.addContent(new Element("searchValue").setText(searchValue));
                replacement.addContent(new Element("replaceValue").setText(replaceValue));

                replacements.addContent(replacement);

            }
        }

        String replacementsString = Xml.getString(replacements);
        //replacementsString = replacementsString.replaceAll("\\s","");

        while (iter.hasNext()) {
            String uuid = iter.next();
            String id = dm.getMetadataId(uuid);
            context.info("Processing metadata with id:" + id);

            processInternal(id, process, "replacements", replacementsString, context, metadata);
        }
    }
View Full Code Here

TOP

Related Classes of org.fao.geonet.kernel.DataManager

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.