/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doCountQuery() */ public int doCountQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_count_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); if (tri.hasNext()) { TableRow row = tri.next(); return (int) row.getLongColumn("num"); } else { return 0; } } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } }
/** * Get all workflow items for a particular collection. * * @param context the context object * @param c the collection * @return array of the corresponding workflow items */ public static WorkflowItem[] findByCollection(Context context, Collection c) throws SQLException { List wsItems = new ArrayList(); TableRowIterator tri = DatabaseManager.queryTable( context, "workflowitem", "SELECT workflowitem.* FROM workflowitem WHERE " + "workflowitem.collection_id= ? ", c.getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); // Check the cache WorkflowItem wi = (WorkflowItem) context.fromCache(WorkflowItem.class, row.getIntColumn("workflow_id")); // not in cache? turn row into workflowitem if (wi == null) { wi = new WorkflowItem(context, row); } wsItems.add(wi); } } finally { if (tri != null) tri.close(); } WorkflowItem[] wsArray = new WorkflowItem[wsItems.size()]; wsArray = (WorkflowItem[]) wsItems.toArray(wsArray); return wsArray; }
/** * Perform a database query to obtain the string array of values corresponding to the passed * parameters. This is only really called from <code> * getMetadata(schema, element, qualifier, lang); * </code> which will obtain the value from cache if available first. * * @param schema * @param element * @param qualifier * @param lang */ @Override public List<DCValue> getMetadata( Item item, String schema, String element, String qualifier, String lang) { List<DCValue> metadata = new ArrayList<DCValue>(); try { TableRowIterator tri; if (qualifier == null) { Object[] params = {item.getID(), element, schema}; tri = DatabaseManager.query(context, getByMetadataElement, params); } else if (Item.ANY.equals(qualifier)) { Object[] params = {item.getID(), element, schema}; tri = DatabaseManager.query(context, getByMetadataAnyQualifier, params); } else { Object[] params = {item.getID(), element, qualifier, schema}; tri = DatabaseManager.query(context, getByMetadata, params); } while (tri.hasNext()) { TableRow tr = tri.next(); DCValue dcv = new DCValue(); dcv.schema = schema; dcv.element = element; dcv.qualifier = qualifier; dcv.language = lang; dcv.value = tr.getStringColumn("text_value"); metadata.add(dcv); } } catch (SQLException sqle) { throw new RuntimeException(sqle); } return metadata; }
/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doValueQuery() */ public List<String[]> doValueQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query)); TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<String[]> results = new ArrayList<String[]>(); while (tri.hasNext()) { TableRow row = tri.next(); String valueResult = row.getStringColumn("value"); String authorityResult = row.getStringColumn("authority"); if (enableBrowseFrequencies) { long frequency = row.getLongColumn("num"); results.add(new String[] {valueResult, authorityResult, String.valueOf(frequency)}); } else results.add(new String[] {valueResult, authorityResult, ""}); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } }
/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doQuery() */ public List<BrowseItem> doQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); if (log.isDebugEnabled()) { log.debug(LogManager.getHeader(context, "executing_full_query", "query=" + query)); } TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List<BrowseItem> results = new ArrayList<BrowseItem>(); while (tri.hasNext()) { TableRow row = tri.next(); BrowseItem browseItem = new BrowseItem(context, row.getIntColumn("item_id"), itemsInArchive, itemsWithdrawn); results.add(browseItem); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException("problem with query: " + query, e); } finally { if (tri != null) { tri.close(); } } }
/** * Obtiene todas las revisiones finalizadas. * * @param context DSpace context object * @return an iterator over the items in the archive. * @throws SQLException */ public static RevisionToken[] findAllRevisiones(Context context) throws SQLException { String myQuery = "SELECT * FROM revision_token WHERE tipo='R' and revision_id is not null"; TableRowIterator rows = DatabaseManager.queryTable(context, "revision_token", myQuery); try { List<TableRow> revisionRows = rows.toList(); RevisionToken[] revisionToken = new RevisionToken[revisionRows.size()]; for (int i = 0; i < revisionRows.size(); i++) { TableRow row = (TableRow) revisionRows.get(i); // First check the cache RevisionToken fromCache = (RevisionToken) context.fromCache(RevisionToken.class, row.getIntColumn("revision_token_id")); if (fromCache != null) { revisionToken[i] = fromCache; } else { revisionToken[i] = new RevisionToken(row); } } return revisionToken; } finally { if (rows != null) { rows.close(); } } }
/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doDistinctOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doDistinctOffsetQuery(String column, String value) throws BrowseException { TableRowIterator tri = null; try { List paramsList = new ArrayList(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatementDistinct(queryBuf, paramsList); queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); if (containerTable != null && tableMap != null) { queryBuf.append(" AND ").append("mappings.distinct_id="); queryBuf.append(table).append(".id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return (int) row.getLongColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } }
/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doValueQuery() */ public List doValueQuery() throws BrowseException { String query = getQuery(); Object[] params = getQueryParams(); log.debug(LogManager.getHeader(context, "executing_value_query", "query=" + query)); TableRowIterator tri = null; try { // now run the query tri = DatabaseManager.query(context, query, params); // go over the query results and process List results = new ArrayList(); while (tri.hasNext()) { TableRow row = tri.next(); String stringResult = row.getStringColumn("value"); results.add(stringResult); } return results; } catch (SQLException e) { log.error("caught exception: ", e); throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } }
/** * Return all metadata fields that are found in a given schema. * * @param context dspace context * @param schemaID schema by db ID * @return array of metadata fields * @throws SQLException */ public static MetadataField[] findAllInSchema(Context context, int schemaID) throws SQLException { List<MetadataField> fields = new ArrayList<MetadataField>(); // Get all the metadatafieldregistry rows TableRowIterator tri = DatabaseManager.queryTable( context, "MetadataFieldRegistry", "SELECT * FROM MetadataFieldRegistry WHERE metadata_schema_id= ? " + " ORDER BY element, qualifier", schemaID); try { // Make into DC Type objects while (tri.hasNext()) { fields.add(new MetadataField(tri.next())); } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } // Convert list into an array MetadataField[] typeArray = new MetadataField[fields.size()]; return (MetadataField[]) fields.toArray(typeArray); }
/** * Return a List of the policies for a group * * @param c current context * @param g group to retrieve policies for * @return List of <code>ResourcePolicy</code> objects */ public static List<ResourcePolicy> getPoliciesForGroup(Context c, Group g) throws SQLException { TableRowIterator tri = DatabaseManager.queryTable( c, "resourcepolicy", "SELECT * FROM resourcepolicy WHERE epersongroup_id= ? ", g.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; }
public static RevisionToken find(Context context, String token) throws IOException, SQLException, AuthorizeException { // Grab rows from DB TableRowIterator tri = DatabaseManager.queryTable( context, "revision_token", "SELECT * FROM revision_token where token= ? ", token); TableRow row = null; try { if (tri.hasNext()) { row = tri.next(); } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } if (row == null) { return null; } else { return new RevisionToken(row); } }
// load caches if necessary private static synchronized void initCache(Context context) throws SQLException { if (!isCacheInitialized()) { Map<Integer, MetadataField> new_id2field = new HashMap<Integer, MetadataField>(); log.info("Loading MetadataField elements into cache."); // Grab rows from DB TableRowIterator tri = DatabaseManager.queryTable( context, "MetadataFieldRegistry", "SELECT * from MetadataFieldRegistry"); try { while (tri.hasNext()) { TableRow row = tri.next(); int fieldID = row.getIntColumn("metadata_field_id"); new_id2field.put(Integer.valueOf(fieldID), new MetadataField(row)); } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } id2field = new_id2field; } }
public static RevisionToken findItemOfRevision(Context context, int id) throws IOException, SQLException, AuthorizeException { // Grab rows from DB log.debug("Buscando item de la revision del id:" + id); TableRowIterator tri = DatabaseManager.queryTable( context, "revision_token", "SELECT * FROM revision_token where revision_id= ? and tipo='R' and revision_id is not null", "" + id); TableRow row = null; try { while (tri.hasNext()) { row = tri.next(); return new RevisionToken(row); } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } return null; }
public static ArrayList<RevisionToken> findJuiciosOfHandle(Context context, String handle) throws IOException, SQLException, AuthorizeException { ArrayList<RevisionToken> resultado = new ArrayList<RevisionToken>(); if (handle != null) { // Grab rows from DB TableRowIterator tri = DatabaseManager.queryTable( context, "revision_token", "SELECT * FROM revision_token where handle_revisado= ? and tipo='J' and revision_id is not null", handle); TableRow row = null; try { while (tri.hasNext()) { row = tri.next(); resultado.add(new RevisionToken(row)); } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } } return resultado; }
/** * Return an iterator with the results of the query. * * @param context The context object * @param query The SQL query * @param parameters A set of SQL parameters to be included in query. The order of the parameters * must correspond to the order of their reference within the query. * @return A TableRowIterator with the results of the query * @exception SQLException If a database error occurs */ public static TableRowIterator query(Context context, String query, Object... parameters) throws SQLException { if (log.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < parameters.length; i++) { if (i > 0) { sb.append(","); } sb.append(parameters[i].toString()); } log.debug("Running query \"" + query + "\" with parameters: " + sb.toString()); } PreparedStatement statement = context.getDBConnection().prepareStatement(query); try { loadParameters(statement, parameters); TableRowIterator retTRI = new TableRowIterator(statement.executeQuery()); retTRI.setStatement(statement); return retTRI; } catch (SQLException sqle) { if (statement != null) { try { statement.close(); } catch (SQLException s) { } } throw sqle; } }
public static CollectionRole find(Context context, int collection, String role) throws SQLException { TableRowIterator tri = DatabaseManager.queryTable( context, "xmlwf_collectionrole", "SELECT * FROM xmlwf_collectionrole WHERE collection_id=" + collection + " AND role_id= ? ", role); TableRow row = null; if (tri.hasNext()) { row = tri.next(); } // close the TableRowIterator to free up resources tri.close(); if (row == null) { return null; } else { return new CollectionRole(context, row); } }
/** * Returns the ID of the item as opposed to the item itself when we are iterating over the * TableRow array. * * @return the item id, or -1 if none */ private int nextByRowID() throws SQLException { if (itemRows.hasNext()) { TableRow row = itemRows.next(); return row.getIntColumn("item_id"); } else { return -1; } }
List<DCValue> get(Context c, int resourceId, int resourceTypeId, Logger log) throws SQLException { if (metadata == null) { metadata = new ArrayList<DCValue>(); // Get Dublin Core metadata TableRowIterator tri = retrieveMetadata(resourceId, resourceTypeId); if (tri != null) { try { while (tri.hasNext()) { TableRow resultRow = tri.next(); // Get the associated metadata field and schema information int fieldID = resultRow.getIntColumn("metadata_field_id"); MetadataField field = MetadataField.find(c, fieldID); if (field == null) { log.error("Loading item - cannot find metadata field " + fieldID); } else { MetadataSchema schema = MetadataSchema.find(c, field.getSchemaID()); if (schema == null) { log.error( "Loading item - cannot find metadata schema " + field.getSchemaID() + ", field " + fieldID); } else { // Make a DCValue object DCValue dcv = new DCValue(); dcv.element = field.getElement(); dcv.qualifier = field.getQualifier(); dcv.value = resultRow.getStringColumn("text_value"); dcv.language = resultRow.getStringColumn("text_lang"); // dcv.namespace = schema.getNamespace(); dcv.schema = schema.getName(); dcv.authority = resultRow.getStringColumn("authority"); dcv.confidence = resultRow.getIntColumn("confidence"); // Add it to the list metadata.add(dcv); } } } } finally { // close the TableRowIterator to free up resources if (tri != null) { tri.close(); } } } } return metadata; }
public static boolean IsInstitution(Context context, String ip) throws SQLException { String sql = "select ip_range from stats.ip_institution"; TableRowIterator iterator = DatabaseManager.query(context, sql); while (iterator.hasNext()) { TableRow row = iterator.next(); String range = row.getStringColumn("ip_range"); if (ip.indexOf(range) == 0) return true; } return false; }
/** * Attempt to identify the format of a particular bitstream. If the format is unknown, null is * returned. * * @param bitstream the bitstream to identify the format of * @return a format from the bitstream format registry, or null */ public static BitstreamFormat guessFormat(Context context, Bitstream bitstream) throws SQLException { // FIXME: Just setting format to first guess // For now just get the file name String filename = bitstream.getName().toLowerCase(); // Gracefully handle the null case if (filename == null) { return null; } // This isn't rocket science. We just get the name of the // bitstream, get the extension, and see if we know the type. String extension = filename; int lastDot = filename.lastIndexOf('.'); if (lastDot != -1) { extension = filename.substring(lastDot + 1); } // If the last character was a dot, then extension will now be // an empty string. If this is the case, we don't know what // file type it is. if (extension.equals("")) { return null; } // See if the extension is in the fileextension table TableRowIterator tri = DatabaseManager.query( context, "SELECT bitstreamformatregistry.* FROM bitstreamformatregistry, " + "fileextension WHERE fileextension.extension LIKE ? " + "AND bitstreamformatregistry.bitstream_format_id=" + "fileextension.bitstream_format_id", extension); BitstreamFormat retFormat = null; try { if (tri.hasNext()) { // Return first match retFormat = new BitstreamFormat(context, tri.next()); } else { retFormat = null; } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } return retFormat; }
/** * Return the single row result to this query, or null if no result. If more than one row results, * only the first is returned. * * @param context Current DSpace context * @param table The name of the table which results * @param query The SQL query * @param parameters A set of SQL parameters to be included in query. The order of the parameters * must correspond to the order of their reference within the query. * @return A TableRow object, or null if no result * @exception SQLException If a database error occurs */ public static TableRow querySingleTable( Context context, String table, String query, Object... parameters) throws SQLException { TableRow retRow = null; TableRowIterator iterator = queryTable(context, canonicalize(table), query, parameters); try { retRow = (!iterator.hasNext()) ? null : iterator.next(); } finally { if (iterator != null) { iterator.close(); } } return (retRow); }
/** * Finds all groups in the site * * @param context DSpace context * @param sortField field to sort by -- Group.ID or Group.NAME * @return array of all groups in the site */ public static Group[] findAll(Context context, int sortField) throws SQLException { String s; switch (sortField) { case ID: s = "eperson_group_id"; break; case NAME: s = "name"; break; default: s = "name"; } // NOTE: The use of 's' in the order by clause can not cause an SQL // injection because the string is derived from constant values above. TableRowIterator rows = DatabaseManager.queryTable( context, "epersongroup", "SELECT * FROM epersongroup ORDER BY " + s); try { List<TableRow> gRows = rows.toList(); Group[] groups = new Group[gRows.size()]; for (int i = 0; i < gRows.size(); i++) { TableRow row = gRows.get(i); // First check the cache Group fromCache = (Group) context.fromCache(Group.class, row.getIntColumn("eperson_group_id")); if (fromCache != null) { groups[i] = fromCache; } else { groups[i] = new Group(context, row); } } return groups; } finally { if (rows != null) { rows.close(); } } }
/** * Is the given item in a DSpace workspace? * * <p>This method queries the database directly to determine if this is the case rather than using * the DSpace API (which is very slow) * * @param context * @param item * @return * @throws DSpaceSwordException */ public boolean isItemInWorkspace(Context context, Item item) throws DSpaceSwordException { try { String query = "SELECT workspace_item_id FROM workspaceitem WHERE item_id = ?"; Object[] params = {item.getID()}; TableRowIterator tri = DatabaseManager.query(context, query, params); if (tri.hasNext()) { tri.close(); return true; } return false; } catch (SQLException e) { throw new DSpaceSwordException(e); } }
/** * 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; }
/** * getOwnedTasks() returns a List of WorkflowItems containing the tasks claimed and owned by an * EPerson. The GUI displays this info on the MyDSpace page. * * @param e The EPerson we want to fetch owned tasks for. */ public static List getOwnedTasks(Context c, EPerson e) throws java.sql.SQLException { ArrayList mylist = new ArrayList(); String myquery = "SELECT * FROM WorkflowItem WHERE owner= ? "; TableRowIterator tri = DatabaseManager.queryTable(c, "workflowitem", myquery, e.getID()); try { while (tri.hasNext()) { mylist.add(new WorkflowItem(c, tri.next())); } } finally { if (tri != null) tri.close(); } return mylist; }
/* (non-Javadoc) * @see org.dspace.browse.BrowseDAO#doOffsetQuery(java.lang.String, java.lang.String, java.lang.String) */ public int doOffsetQuery(String column, String value, boolean isAscending) throws BrowseException { TableRowIterator tri = null; if (column == null || value == null) { return 0; } try { List<Serializable> paramsList = new ArrayList<Serializable>(); StringBuffer queryBuf = new StringBuffer(); queryBuf.append("COUNT(").append(column).append(") AS offset "); buildSelectStatement(queryBuf, paramsList); if (isAscending) { queryBuf.append(" WHERE ").append(column).append("<?"); paramsList.add(value); } else { queryBuf.append(" WHERE ").append(column).append(">?"); paramsList.add(value + Character.MAX_VALUE); } if (containerTable != null || (value != null && valueField != null && tableDis != null && tableMap != null)) { queryBuf.append(" AND ").append("mappings.item_id="); queryBuf.append(table).append(".item_id"); } tri = DatabaseManager.query(context, queryBuf.toString(), paramsList.toArray()); TableRow row; if (tri.hasNext()) { row = tri.next(); return (int) row.getLongColumn("offset"); } else { return 0; } } catch (SQLException e) { throw new BrowseException(e); } finally { if (tri != null) { tri.close(); } } }
/** * Obtain the WorkflowItem object which wraps the given Item * * <p>This method queries the database directly to determine if this is the case rather than using * the DSpace API (which is very slow) * * @param context * @param item * @return * @throws DSpaceSwordException */ public WorkflowItem getWorkflowItem(Context context, Item item) throws DSpaceSwordException { try { String query = "SELECT workflow_id FROM workflowitem WHERE item_id = ?"; Object[] params = {item.getID()}; TableRowIterator tri = DatabaseManager.query(context, query, params); if (tri.hasNext()) { TableRow row = tri.next(); int wfid = row.getIntColumn("workflow_id"); WorkflowItem wfi = WorkflowItem.find(context, wfid); tri.close(); return wfi; } return null; } catch (SQLException e) { throw new DSpaceSwordException(e); } }
/** Return the list of running applications. */ public static List<AbstractDSpaceWebapp> getApps() { ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>(); TableRowIterator tri; Context context = null; HttpMethod request = null; try { context = new Context(); tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp"); for (TableRow row : tri.toList()) { DSpaceWebapp app = new DSpaceWebapp(); app.kind = row.getStringColumn("AppName"); app.url = row.getStringColumn("URL"); app.started = row.getDateColumn("Started"); app.uiQ = row.getBooleanColumn("isUI"); HttpClient client = new HttpClient(); request = new HeadMethod(app.url); int status = client.executeMethod(request); request.getResponseBody(); if (status != HttpStatus.SC_OK) { DatabaseManager.delete(context, row); context.commit(); continue; } apps.add(app); } } catch (SQLException e) { log.error("Unable to list running applications", e); } catch (HttpException e) { log.error("Failure checking for a running webapp", e); } catch (IOException e) { log.error("Failure checking for a running webapp", e); } finally { if (null != request) { request.releaseConnection(); } if (null != context) { context.abort(); } } return apps; }
/** * Find out if there are any more items to iterate over * * @return <code>true</code> if there are more items * @throws SQLException */ public boolean hasNext() throws SQLException { if (iditr != null) { return iditr.hasNext(); } else if (itemRows != null) { return itemRows.hasNext(); } return false; }
/** * Return the next item instantiated from the supplied TableRow * * @return the item or null if none * @throws SQLException */ private Item nextByRow() throws SQLException { if (itemRows.hasNext()) { // Convert the row into an Item object TableRow row = itemRows.next(); // Check cache Item fromCache = (Item) ourContext.fromCache(Item.class, row.getIntColumn("item_id")); if (fromCache != null) { return fromCache; } else { return new Item(ourContext, row); } } else { return null; } }