Ejemplo n.º 1
0
  /**
   * Return a url to the DSpace object, either use the official handle for the item or build a url
   * based upon the current server.
   *
   * <p>If the dspaceobject is null then a local url to the repository is generated.
   *
   * @param request current servlet request
   * @param dso The object to reference, null if to the repository.
   * @return URL
   */
  protected String resolveURL(HttpServletRequest request, DSpaceObject dso) {
    // If no object given then just link to the whole repository,
    // since no offical handle exists so we have to use local resolution.
    if (dso == null) {
      if (baseURL == null) {
        if (request == null) {
          baseURL = ConfigurationManager.getProperty("dspace.url");
        } else {
          baseURL = (request.isSecure()) ? "https://" : "http://";
          baseURL += ConfigurationManager.getProperty("dspace.hostname");
          baseURL += ":" + request.getServerPort();
          baseURL += request.getContextPath();
        }
      }
      return baseURL;
    }

    // return a link to handle in repository
    else if (ConfigurationManager.getBooleanProperty("webui.feed.localresolve")) {
      return resolveURL(request, null) + "/handle/" + dso.getHandle();
    }

    // link to the Handle server or other persistent URL source
    else {
      return HandleServiceFactory.getInstance()
          .getHandleService()
          .getCanonicalForm(dso.getHandle());
    }
  }
Ejemplo n.º 2
0
  /**
   * Generate the unique caching key. This key must be unique inside the space of this component.
   */
  public Serializable getKey() {
    try {
      String key = "";

      // Page Parameter
      key += "-" + getParameterPage();
      key += "-" + getParameterRpp();
      key += "-" + getParameterSortBy();
      key += "-" + getParameterOrder();
      key += "-" + getParameterEtAl();

      // What scope the search is at
      DSpaceObject scope = getScope();
      if (scope != null) {
        key += "-" + scope.getHandle();
      }

      // The actual search query.
      key += "-" + getQuery();

      return HashUtil.hash(key);
    } catch (RuntimeException re) {
      throw re;
    } catch (Exception e) {
      // Ignore all errors and just don't cache.
      return "0";
    }
  }
Ejemplo n.º 3
0
  /**
   * Return a List of the policies for an object
   *
   * @param c current context
   * @param o object to retrieve policies for
   * @return List of <code>ResourcePolicy</code> objects
   */
  public static List<ResourcePolicy> getPolicies(Context c, DSpaceObject o) throws SQLException {
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c,
            "resourcepolicy",
            "SELECT * FROM resourcepolicy WHERE resource_type_id= ? AND resource_id= ? ",
            o.getType(),
            o.getID());

    List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>();

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        // first check the cache (FIXME: is this right?)
        ResourcePolicy cachepolicy =
            (ResourcePolicy) c.fromCache(ResourcePolicy.class, row.getIntColumn("policy_id"));

        if (cachepolicy != null) {
          policies.add(cachepolicy);
        } else {
          policies.add(new ResourcePolicy(c, row));
        }
      }
    } finally {
      if (tri != null) {
        tri.close();
      }
    }

    return policies;
  }
Ejemplo n.º 4
0
  protected DSpaceObject resolveHandle(String handle) {
    DSpaceObject dso = null;
    try {
      dso = handleService.resolveToObject(this.context, handle);
    } catch (SQLException ex) {
      log.error(ex);
      System.err.println(
          "A problem with the database connection " + "occurred. Canceled pending actions.");
      System.err.println(ex.getMessage());
      ex.printStackTrace(System.err);
      System.exit(1);
    } catch (IllegalStateException ex) {
      log.error(ex);
      System.err.println("Cannot recognize identifier '" + handle + "', skipping.");
      return null;
    }
    if (dso == null) {
      System.err.println("Cannot resolve identifier '" + handle + "', skipping.");
      log.debug("Couldn't resolve identifier '" + handle + "', dso was null.");
      return null;
    }
    if (dso.getType() != Constants.SITE
        && dso.getType() != Constants.COMMUNITY
        && dso.getType() != Constants.COLLECTION
        && dso.getType() != Constants.ITEM) {
      System.err.println(
          contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
              + " are currently not "
              + "supported as independent entities. Bundles and Bitstreams "
              + "should be processed as part of their item.");
      return null;
    }

    return dso;
  }
Ejemplo n.º 5
0
  /**
   * See if is necessary and possible to get the backup file from cloud.
   *
   * @param context DSpace context
   * @param ref ID of the object
   * @param type type of the object DSpace
   * @return true if it is necessary or possible to get the backup from cloud or false if not
   */
  private Boolean couldGetFileFromCloud(Context context, int ref, int type) {
    // get the corresponding Dspace Object
    DSpaceObject obj = this.getDSpaceObject(context, type, ref);

    // if Object DSpace doesn't exist, return false
    if (obj == null) return false;

    // see if backup file exists in cloud, if not return false
    if (this.filesInCloud.containsKey(obj.getHandle())) {
      BackupProcess backupPro = new BackupProcess();
      String ETagSaved = backupPro.getETag(context, obj.getHandle());

      // see if ETag of file in cloud, has equal to the last send, if not return false
      if (ETagSaved.compareTo(this.filesInCloud.get(obj.getHandle())) == 0) {
        // see if exists backup file locally
        Backup backup = new Backup();
        String filename = backup.getFileNameObj(obj);
        Boolean existLocalFile = backup.existFile(filename);

        // if not exist file locally return true
        if (existLocalFile == true) {
          // get MD5 of local file
          String md5LocalFile = backup.getMD5File(filename);
          // get MD5 of the last file sent to cloud
          String md5FileSentCloud = backupPro.getSentMD5(context, obj.getHandle());

          // if files equal, there is no necessity to get file from cloud, then return false
          if (md5LocalFile.compareTo(md5FileSentCloud) == 0) return false;
          else return true;
        } else return true;
      } else return false;
    } else return false;
  }
Ejemplo n.º 6
0
 /**
  * removes ALL policies for an object. FIXME doesn't check authorization
  *
  * @param c DSpace context
  * @param o object to remove policies for
  * @throws SQLException if there's a database problem
  */
 public static void removeAllPolicies(Context c, DSpaceObject o) throws SQLException {
   // FIXME: authorization check?
   DatabaseManager.updateQuery(
       c,
       "DELETE FROM resourcepolicy WHERE " + "resource_type_id= ? AND resource_id= ? ",
       o.getType(),
       o.getID());
 }
Ejemplo n.º 7
0
  /**
   * Match the URIs this subclass understands and return the corresponding resource. Since the
   * "dso_" format can lead to several different resource types, handle it here.
   *
   * @param context the context
   * @param request the request
   * @param response the response
   * @param pathElt the path elt
   * @return the DAV resource
   * @throws DAVStatusException the DAV status exception
   * @throws SQLException the SQL exception
   * @throws AuthorizeException the authorize exception
   */
  protected static DAVResource matchResourceURI(
      Context context, HttpServletRequest request, HttpServletResponse response, String pathElt[])
      throws DAVStatusException, SQLException, AuthorizeException {
    // Match /dso_<handle>{...} .. look for last "dso_" element
    if (pathElt[0].startsWith("dso_")) {
      int i = 1;
      for (; i < pathElt.length && pathElt[i].startsWith("dso_"); ++i) {
        // empty
      }
      --i;
      String handle = decodeHandle(pathElt[i].substring(4));

      // Replace substituted handle separator char with '/' to
      // get back a normal handle: (inverse of getPathElt() above)
      int sepIndex = handle.indexOf(handleSeparator);
      if (sepIndex >= 0) {
        char hc[] = handle.toCharArray();
        hc[sepIndex] = '/';
        handle = String.copyValueOf(hc);
      }

      DSpaceObject dso = HandleManager.resolveToObject(context, handle);
      if (dso == null) {
        throw new DAVStatusException(
            HttpServletResponse.SC_NOT_FOUND, "Cannot resolve handle \"" + handle + "\"");
      } else if (dso.getType() == Constants.ITEM) {
        if (i + 1 < pathElt.length) {
          if (pathElt[i + 1].startsWith("bitstream_")) {
            Bitstream bs = DAVBitstream.findBitstream(context, (Item) dso, pathElt[i + 1]);
            if (bs == null) {
              throw new DAVStatusException(
                  HttpServletResponse.SC_NOT_FOUND,
                  "Bitstream \"" + pathElt[i + 1] + "\" not found in item: " + pathElt[i]);
            }
            return new DAVBitstream(context, request, response, pathElt, (Item) dso, bs);
          } else {
            throw new DAVStatusException(
                HttpServletResponse.SC_NOT_FOUND,
                "Illegal resource path, \""
                    + pathElt[i + 1]
                    + "\" is not a Bitstream identifier for item: "
                    + pathElt[i]);
          }
        } else {
          return new DAVItem(context, request, response, pathElt, (Item) dso);
        }
      } else if (dso.getType() == Constants.COLLECTION) {
        return new DAVCollection(context, request, response, pathElt, (Collection) dso);
      } else if (dso.getType() == Constants.COMMUNITY) {
        return new DAVCommunity(context, request, response, pathElt, (Community) dso);
      } else {
        throw new DAVStatusException(
            HttpServletResponse.SC_BAD_REQUEST,
            "Unrecognized DSpace object type for handle=" + handle);
      }
    }
    return null;
  }
Ejemplo n.º 8
0
 /**
  * Removes all policies from a group for a particular object that belong to a Group. FIXME doesn't
  * check authorization
  *
  * @param c current context
  * @param o the object
  * @param g the group
  * @throws SQLException if there's a database problem
  */
 public static void removeGroupPolicies(Context c, DSpaceObject o, Group g) throws SQLException {
   DatabaseManager.updateQuery(
       c,
       "DELETE FROM resourcepolicy WHERE "
           + "resource_type_id= ? AND resource_id= ? AND epersongroup_id= ? ",
       o.getType(),
       o.getID(),
       g.getID());
 }
  /**
   * Generate the unique caching key. This key must be unique inside the space of this component.
   */
  public Serializable getKey() {
    try {
      DSpaceObject dso = HandleUtil.obtainHandle(objectModel);

      if (dso == null) return "0";

      return HashUtil.hash(dso.getHandle());
    } catch (SQLException sqle) {
      // Ignore all errors and just return that the component is not
      // cachable.
      return "0";
    }
  }
Ejemplo n.º 10
0
  /**
   * Delete the data about the DSpaceObject from the triplestore. All data about descendent
   * Subcommunities, Collections and Items will be deleted as well.
   */
  public void delete(DSpaceObject dso, boolean reset) throws SQLException {
    if (dso.getType() != Constants.SITE
        && dso.getType() != Constants.COMMUNITY
        && dso.getType() != Constants.COLLECTION
        && dso.getType() != Constants.ITEM) {
      throw new IllegalArgumentException(
          contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
              + " is currently not supported as independent entity.");
    }

    if (dso.getType() == Constants.SITE) {
      // we don't need to iterate over all objects, use a shorctut:
      this.deleteAll();
    }
    Callback callback =
        new Callback() {
          @Override
          protected void callback(DSpaceObject dso) throws SQLException {
            String identifier = RDFUtil.generateIdentifier(context, dso);

            if (StringUtils.isEmpty(identifier)) {
              System.err.println(
                  "Cannot determine RDF URI for "
                      + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
                      + " "
                      + dso.getID()
                      + "(handle "
                      + dso.getHandle()
                      + ")"
                      + ", skipping. Please "
                      + "delete it specifing the RDF URI.");
              log.error(
                  "Cannot detgermine RDF URI for "
                      + contentServiceFactory.getDSpaceObjectService(dso).getTypeText(dso)
                      + " "
                      + dso.getID()
                      + "(handle "
                      + dso.getHandle()
                      + ")"
                      + ", skipping deletion.");
              return;
            }

            report("Deleting Named Graph" + identifier);
            if (!dryrun) {
              storage.delete(identifier);
            }
          }
        };
    this.dspaceDFS(dso, callback, false, reset);
  }
Ejemplo n.º 11
0
  /**
   * Returns all groups authorized to perform an action on an object. Returns empty array if no
   * matches.
   *
   * @param c current context
   * @param o object
   * @param actionID ID of action frm <code>org.dspace.core.Constants</code>
   * @return array of <code>Group</code>s that can perform the specified action on the specified
   *     object
   * @throws java.sql.SQLException if there's a database problem
   */
  public static Group[] getAuthorizedGroups(Context c, DSpaceObject o, int actionID)
      throws java.sql.SQLException {
    // do query matching groups, actions, and objects
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c,
            "resourcepolicy",
            "SELECT * FROM resourcepolicy WHERE resource_type_id= ? "
                + "AND resource_id= ? AND action_id= ? ",
            o.getType(),
            o.getID(),
            actionID);

    List<Group> groups = new ArrayList<Group>();
    try {

      while (tri.hasNext()) {
        TableRow row = tri.next();

        // first check the cache (FIXME: is this right?)
        ResourcePolicy cachepolicy =
            (ResourcePolicy) c.fromCache(ResourcePolicy.class, row.getIntColumn("policy_id"));

        ResourcePolicy myPolicy = null;

        if (cachepolicy != null) {
          myPolicy = cachepolicy;
        } else {
          myPolicy = new ResourcePolicy(c, row);
        }

        // now do we have a group?
        Group myGroup = myPolicy.getGroup();

        if (myGroup != null) {
          groups.add(myGroup);
        }
      }
    } finally {
      if (tri != null) {
        tri.close();
      }
    }

    Group[] groupArray = new Group[groups.size()];
    groupArray = groups.toArray(groupArray);

    return groupArray;
  }
Ejemplo n.º 12
0
 /**
  * Remove all policies from an object that match a given action. FIXME doesn't check authorization
  *
  * @param context current context
  * @param dso object to remove policies from
  * @param actionID ID of action to match from <code>org.dspace.core.Constants</code>, or -1=all
  * @throws SQLException if there's a database problem
  */
 public static void removePoliciesActionFilter(Context context, DSpaceObject dso, int actionID)
     throws SQLException {
   if (actionID == -1) {
     // remove all policies from object
     removeAllPolicies(context, dso);
   } else {
     DatabaseManager.updateQuery(
         context,
         "DELETE FROM resourcepolicy WHERE resource_type_id= ? AND "
             + "resource_id= ? AND action_id= ? ",
         dso.getType(),
         dso.getID(),
         actionID);
   }
 }
Ejemplo n.º 13
0
  protected void logSearch() {
    int countCommunities = 0;
    int countCollections = 0;
    int countItems = 0;

    for (Integer type : queryResults.getHitTypes()) {
      switch (type.intValue()) {
        case Constants.ITEM:
          countItems++;
          break;
        case Constants.COLLECTION:
          countCollections++;
          break;
        case Constants.COMMUNITY:
          countCommunities++;
          break;
      }
    }

    String logInfo = "";

    try {
      DSpaceObject dsoScope = getScope();

      if (dsoScope instanceof Collection) {
        logInfo = "collection_id=" + dsoScope.getID() + ",";
      } else if (dsoScope instanceof Community) {
        logInfo = "community_id=" + dsoScope.getID() + ",";
      }
    } catch (SQLException sqle) {
      // Ignore, as we are only trying to get the scope to add detail to the log message
    }

    log.info(
        LogManager.getHeader(
            context,
            "search",
            logInfo
                + "query=\""
                + queryArgs.getQuery()
                + "\",results=("
                + countCommunities
                + ","
                + countCollections
                + ","
                + countItems
                + ")"));
  }
Ejemplo n.º 14
0
 /**
  * Make URI path element for a DSpaceObject.
  *
  * @param dso the DSpaceObject, which needs to have a valid Handle.
  * @return path element string or null if no handle.
  */
 protected static String getPathElt(DSpaceObject dso) {
   String handle = dso.getHandle();
   if (handle == null) {
     return null;
   }
   return getPathElt(handle);
 }
Ejemplo n.º 15
0
 /**
  * Create URI as string for a given handle and optional bitstream. URI is relative to top of DAV
  * hierarchy, but starts with '/'.
  *
  * @param dso a DSpace object (Item, Collection, etc)
  * @param bsPid bitstream persistent identifier.
  * @return "absolute" URI from top of DAV hierarchy
  * @throws IOException Signals that an I/O exception has occurred.
  * @throws SQLException the SQL exception
  */
 private String makeURI(DSpaceObject dso, String bsPid) throws IOException, SQLException {
   // make sure that bitstream actually exists:
   if (bsPid != null) {
     if (dso.getType() != Constants.ITEM) {
       log.warn("Non-Item with Bitstream Sequence ID in DAV Lookup.");
       return null;
     }
     try {
       int pid = Integer.parseInt(bsPid);
       if (DAVBitstream.getBitstreamBySequenceID((Item) dso, pid) == null) {
         log.warn("Bitstream Sequence ID Not Found in DAV Lookup: \"" + bsPid + "\"");
         return null;
       }
     } catch (NumberFormatException nfe) {
       log.warn("Invalid Bitstream Sequence ID in DAV Lookup: \"" + bsPid + "\"");
       return null;
     }
   }
   String base = "/" + DAVDSpaceObject.getPathElt(dso);
   if (bsPid != null) {
     return base + "/bitstream_" + bsPid;
   } else {
     return base;
   }
 }
Ejemplo n.º 16
0
  private void writeStats(
      org.dspace.core.Context context,
      Integer bitstream_id,
      String user_ip,
      String user_agent,
      String xforwarderfor,
      HttpHeaders headers,
      HttpServletRequest request) {

    try {
      DSpaceObject bitstream = DSpaceObject.find(context, Constants.BITSTREAM, bitstream_id);

      if (user_ip == null || user_ip.length() == 0) {
        new DSpace()
            .getEventService()
            .fireEvent(new UsageEvent(UsageEvent.Action.VIEW, request, context, bitstream));
      } else {
        new DSpace()
            .getEventService()
            .fireEvent(
                new UsageEvent(
                    UsageEvent.Action.VIEW,
                    user_ip,
                    user_agent,
                    xforwarderfor,
                    context,
                    bitstream));
      }
      log.debug("fired event");

    } catch (SQLException ex) {
      log.error("SQL exception can't write usageEvent \n" + ex);
    }
  }
  private List disseminateListInternal(DSpaceObject dso, boolean addSchema)
      throws CrosswalkException, IOException, SQLException, AuthorizeException {
    if (dso.getType() != Constants.ITEM)
      throw new CrosswalkObjectNotSupported(
          "MODSDisseminationCrosswalk can only crosswalk an Item.");
    Item item = (Item) dso;
    initMap();

    MetadataValue[] dc = item.getMetadata(Item.ANY, Item.ANY, Item.ANY, Item.ANY);
    List result = new ArrayList(dc.length);
    for (int i = 0; i < dc.length; i++) {
      // Compose qualified DC name - schema.element[.qualifier]
      // e.g. "dc.title", "dc.subject.lcc", "lom.Classification.Keyword"
      String qdc =
          dc[i].getMetadataField().getSchema()
              + "."
              + ((dc[i].getMetadataField().getQualifier() == null)
                  ? dc[i].getMetadataField().getElement()
                  : (dc[i].getMetadataField().getElement()
                      + "."
                      + dc[i].getMetadataField().getQualifier()));

      modsTriple trip = (modsTriple) modsMap.get(qdc);
      if (trip == null)
        log.warn("WARNING: " + getPluginInstanceName() + ": No MODS mapping for \"" + qdc + "\"");
      else {
        try {
          Element me = (Element) trip.xml.clone();
          if (addSchema) me.setAttribute("schemaLocation", schemaLocation, XSI_NS);
          Iterator ni = trip.xpath.selectNodes(me).iterator();
          if (!ni.hasNext())
            log.warn(
                "XPath \""
                    + trip.xpath.getXPath()
                    + "\" found no elements in \""
                    + outputUgly.outputString(me)
                    + "\", qdc="
                    + qdc);
          while (ni.hasNext()) {
            Object what = ni.next();
            if (what instanceof Element) ((Element) what).setText(dc[i].getValue());
            else if (what instanceof Attribute) ((Attribute) what).setValue(dc[i].getValue());
            else if (what instanceof Text) ((Text) what).setText(dc[i].getValue());
            else log.warn("Got unknown object from XPath, class=" + what.getClass().getName());
          }
          result.add(me);
        } catch (JDOMException je) {
          log.error(
              "Error following XPath in modsTriple: context="
                  + outputUgly.outputString(trip.xml)
                  + ", xpath="
                  + trip.xpath.getXPath()
                  + ", exception="
                  + je.toString());
        }
      }
    }
    return result;
  }
  private static String formatMessage(DSpaceObject object) {
    try {
      String objText = Constants.typeText[object.getType()].toLowerCase();
      String handle = object.getHandle();

      /* Emulate Item logger */
      if (handle != null && object instanceof Item) {
        return "handle=" + object.getHandle();
      } else {
        return objText + "_id=" + object.getID();
      }

    } catch (Exception e) {

    }
    return "";
  }
 public static URL getLocalURL(DSpaceObject dso) {
   URL url = null;
   ObjectIdentifier oid = dso.getIdentifier();
   if (oid == null) {
     return null;
   }
   url = IdentifierFactory.getURL(oid);
   return url;
 }
  public Serializable getKey() {
    try {
      BrowseParams params = getUserParams();

      String key = params.getKey();

      if (key != null) {
        DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
        if (dso != null) key += "-" + dso.getHandle();

        return HashUtil.hash(key);
      }
    } catch (Exception e) {
      // Ignore all errors and just don't cache.
    }

    return "0";
  }
  private static String formatAction(Action action, DSpaceObject object) {
    try {
      String objText = Constants.typeText[object.getType()].toLowerCase();
      return action.text() + "_" + objText;
    } catch (Exception e) {

    }
    return "";
  }
Ejemplo n.º 22
0
  /**
   * Process sets of objects to add, update, and delete in index. Correct for interactions between
   * the sets -- e.g. objects which were deleted do not need to be added or updated, new objects
   * don't also need an update, etc.
   */
  public void end(Context ctx) throws Exception {

    if (objectsToUpdate != null && handlesToDelete != null) {

      // update the changed Items not deleted because they were on create list
      for (DSpaceObject iu : objectsToUpdate) {
        /* we let all types through here and
         * allow the search DSIndexer to make
         * decisions on indexing and/or removal
         */
        String hdl = iu.getHandle();
        if (hdl != null && !handlesToDelete.contains(hdl)) {
          try {
            DSIndexer.indexContent(ctx, iu, true);
            log.debug(
                "Indexed "
                    + Constants.typeText[iu.getType()]
                    + ", id="
                    + String.valueOf(iu.getID())
                    + ", handle="
                    + hdl);
          } catch (Exception e) {
            log.error("Failed while indexing object: ", e);
          }
        }
      }

      for (String hdl : handlesToDelete) {
        try {
          DSIndexer.unIndexContent(ctx, hdl);
          if (log.isDebugEnabled()) {
            log.debug("UN-Indexed Item, handle=" + hdl);
          }
        } catch (Exception e) {
          log.error("Failed while UN-indexing object: " + hdl, e);
        }
      }
    }

    // "free" the resources
    objectsToUpdate = null;
    handlesToDelete = null;
  }
Ejemplo n.º 23
0
  /**
   * Add the basic navigational options:
   *
   * <p>Search - advanced search
   *
   * <p>browse - browse by Titles - browse by Authors - browse by Dates
   *
   * <p>language FIXME: add languages
   *
   * <p>context no context options are added.
   *
   * <p>action no action options are added.
   */
  public void addOptions(Options options)
      throws SAXException, WingException, UIException, SQLException, IOException,
          AuthorizeException {
    /* Create skeleton menu structure to ensure consistent order between aspects,
     * even if they are never used
     */
    List browse = options.addList("browse");
    options.addList("account");
    options.addList("context");
    options.addList("administrative");

    browse.setHead(T_head_browse);

    List browseGlobal = browse.addList("global");
    List browseContext = browse.addList("context");

    browseGlobal.setHead(T_head_all_of_dspace);

    browseGlobal.addItemXref(contextPath + "/community-list", T_communities_and_collections);

    // Add the configured browse lists for 'top level' browsing
    addBrowseOptions(browseGlobal, contextPath + "/browse");

    DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    if (dso != null) {
      if (dso instanceof Item) {
        // If we are an item change the browse scope to the parent
        // collection.
        dso = ((Item) dso).getOwningCollection();
      }

      if (dso instanceof Collection) {
        browseContext.setHead(T_head_this_collection);
      }
      if (dso instanceof Community) {
        browseContext.setHead(T_head_this_community);
      }

      // Add the configured browse lists for scoped browsing
      String handle = dso.getHandle();
      addBrowseOptions(browseContext, contextPath + "/handle/" + handle + "/browse");
    }
  }
Ejemplo n.º 24
0
  /**
   * Return the specific DSpaceObject. Could be a community, collection or item.
   *
   * @param context DSpace context
   * @param type DSpace Object Type
   * @param ref ID of the object
   * @return the DSpaceObject if exists or null
   */
  private DSpaceObject getDSpaceObject(Context context, int type, int ref) {
    DSpaceObject obj = null;
    try {
      obj = DSpaceObject.find(context, type, ref);
    } catch (SQLException ex) {
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
    }

    return obj;
  }
Ejemplo n.º 25
0
  /**
   * Generate the unique caching key. This key must be unique inside the space of this component.
   */
  public Serializable getKey() {
    try {
      Request request = ObjectModelHelper.getRequest(objectModel);
      String key =
          request.getScheme()
              + request.getServerName()
              + request.getServerPort()
              + request.getSitemapURI()
              + request.getQueryString();

      DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
      if (dso != null) {
        key += "-" + dso.getHandle();
      }

      return HashUtil.hash(key);
    } catch (SQLException sqle) {
      // Ignore all errors and just return that the component is not cachable.
      return "0";
    }
  }
Ejemplo n.º 26
0
  /**
   * Return the metadata URL of the supplied object, assuming it's a DSpace item, community or
   * collection.
   */
  public String getObjectURL(Object object) throws WingException {
    if (object instanceof DSpaceObject) {
      DSpaceObject dso = (DSpaceObject) object;
      String handle = dso.getHandle();

      // If the object has a handle then refrence it by it's handle.
      if (handle != null) {
        return "/metadata/handle/" + handle + "/mets.xml";
      } else {
        // No handle then refrence it by an internal ID.
        if (dso instanceof Item || dso instanceof BrowseItem) {
          return "/metadata/internal/item/" + dso.getID() + "/mets.xml";
        } else if (object instanceof Collection) {
          return "/metadata/internal/collection/" + dso.getID() + "/mets.xml";
        } else if (object instanceof Community) {
          return "/metadata/internal/community/" + dso.getID() + "/mets.xml";
        }
      }
    }

    return null;
  }
Ejemplo n.º 27
0
  @Override
  public int perform(DSpaceObject dso) throws IOException {
    status = Curator.CURATE_SKIP;
    logDebugMessage("The target dso is " + dso.getName());
    if (dso instanceof Item) {
      status = Curator.CURATE_SUCCESS;
      Item item = (Item) dso;
      try {
        openSession();
      } catch (IOException ioE) {
        // no point going further - set result and error out
        closeSession();
        setResult(CONNECT_FAIL_MESSAGE);
        return Curator.CURATE_ERROR;
      }

      try {
        Bundle bundle = item.getBundles("ORIGINAL")[0];
        results = new ArrayList<String>();
        for (Bitstream bitstream : bundle.getBitstreams()) {
          InputStream inputstream = bitstream.retrieve();
          logDebugMessage("Scanning " + bitstream.getName() + " . . . ");
          int bstatus = scan(bitstream, inputstream, getItemHandle(item));
          inputstream.close();
          if (bstatus == Curator.CURATE_ERROR) {
            // no point going further - set result and error out
            setResult(SCAN_FAIL_MESSAGE);
            status = bstatus;
            break;
          }
          if (failfast && bstatus == Curator.CURATE_FAIL) {
            status = bstatus;
            break;
          } else if (bstatus == Curator.CURATE_FAIL && status == Curator.CURATE_SUCCESS) {
            status = bstatus;
          }
        }
      } catch (AuthorizeException authE) {
        throw new IOException(authE.getMessage(), authE);
      } catch (SQLException sqlE) {
        throw new IOException(sqlE.getMessage(), sqlE);
      } finally {
        closeSession();
      }

      if (status != Curator.CURATE_ERROR) {
        formatResults(item);
      }
    }
    return status;
  }
  public static String getCanonicalForm(DSpaceObject dso) {
    String cf = "";
    String ns = ConfigurationManager.getProperty("identifier.url-scheme");
    if (!"".equals(ns) && ns != null) {
      ExternalIdentifierType type = ExternalIdentifierMint.getType(ns);
      List<ExternalIdentifier> eids = dso.getExternalIdentifiers();
      for (ExternalIdentifier eid : eids) {
        if (eid.getType().equals(type)) {
          cf = eid.getCanonicalForm();
        }
      }
    }

    if ("".equals(cf)) {
      ObjectIdentifier oid = dso.getIdentifier();
      if (oid == null) {
        return cf;
      }
      cf = oid.getCanonicalForm();
    }

    return cf;
  }
Ejemplo n.º 29
0
  /**
   * Check to see if the current user is an Administrator of a given object within DSpace. Always
   * return <code>true</code> if the user is a System Admin
   *
   * @param c current context
   * @param o current DSpace Object, if <code>null</code> the call will be equivalent to a call to
   *     the <code>isAdmin(Context c)</code> method
   * @return <code>true</code> if user has administrative privileges on the given DSpace object
   */
  public static boolean isAdmin(Context c, DSpaceObject o) throws SQLException {

    // return true if user is an Administrator
    if (isAdmin(c)) {
      return true;
    }

    if (o == null) {
      return false;
    }

    // is eperson set? if not, userid = 0 (anonymous)
    int userid = 0;
    EPerson e = c.getCurrentUser();
    if (e != null) {
      userid = e.getID();
    }

    //
    // First, check all Resource Policies directly on this object
    //
    List<ResourcePolicy> policies = getPoliciesActionFilter(c, o, Constants.ADMIN);

    for (ResourcePolicy rp : policies) {
      // check policies for date validity
      if (rp.isDateValid()) {
        if ((rp.getEPersonID() != -1) && (rp.getEPersonID() == userid)) {
          return true; // match
        }

        if ((rp.getGroupID() != -1) && (Group.isMember(c, rp.getGroupID()))) {
          // group was set, and eperson is a member
          // of that group
          return true;
        }
      }
    }

    // If user doesn't have specific Admin permissions on this object,
    // check the *parent* objects of this object.  This allows Admin
    // permissions to be inherited automatically (e.g. Admin on Community
    // is also an Admin of all Collections/Items in that Community)
    DSpaceObject parent = o.getParentObject();
    if (parent != null) {
      return isAdmin(c, parent);
    }

    return false;
  }
  public static URL getURL(DSpaceObject dso) {
    URL url = null;

    String ns = ConfigurationManager.getProperty("identifier.url-scheme");
    if (!"".equals(ns) && ns != null) {
      ExternalIdentifierType type = ExternalIdentifierMint.getType(ns);
      List<ExternalIdentifier> eids = dso.getExternalIdentifiers();
      for (ExternalIdentifier eid : eids) {
        if (eid.getType().equals(type)) {
          url = IdentifierFactory.getURL(eid);
        }
      }
    }

    if (url == null) {
      ObjectIdentifier oid = dso.getIdentifier();
      if (oid == null) {
        return null;
      }
      url = IdentifierFactory.getURL(oid);
    }

    return url;
  }