protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { Integer itemID = UIUtil.getIntParameter(request, "itemID"); Item item = Item.find(context, itemID); String submit = UIUtil.getSubmitButton(request, "submit"); if (submit != null && submit.equals("submit")) { request.setAttribute("itemID", itemID); JSPManager.showJSP(request, response, "/tools/version-summary.jsp"); return; } String summary = request.getParameter("summary"); if (submit != null && submit.equals("submit_version")) { Integer wsid = VersionUtil.processCreateNewVersion(context, itemID, summary); response.sendRedirect(request.getContextPath() + "/submit?resume=" + wsid); context.complete(); return; } else if (submit != null && submit.equals("submit_update_version")) { String versionID = request.getParameter("versionID"); request.setAttribute("itemID", itemID); request.setAttribute("versionID", versionID); JSPManager.showJSP(request, response, "/tools/version-update-summary.jsp"); return; } // Send us back to the item page if we cancel ! response.sendRedirect(request.getContextPath() + "/handle/" + item.getHandle()); context.complete(); }
@Override public WorkspaceItem abort(Context c, XmlWorkflowItem wi, EPerson e) throws AuthorizeException, SQLException, IOException { if (!authorizeService.isAdmin(c)) { throw new AuthorizeException("You must be an admin to abort a workflow"); } c.turnOffAuthorisationSystem(); // Restore permissions for the submitter // convert into personal workspace WorkspaceItem wsi = returnToWorkspace(c, wi); log.info( LogManager.getHeader( c, "abort_workflow", "workflow_item_id=" + wi.getID() + "item_id=" + wsi.getItem().getID() + "collection_id=" + wi.getCollection().getID() + "eperson_id=" + e.getID())); c.restoreAuthSystemState(); return wsi; }
/** * Claim-tasks action. * * @param redirector unused. * @param resolver unused. * @param objectModel Cocoon's object model. * @param source unused. * @param parameters unused. * @return null. * @throws java.lang.Exception passed through. */ @Override public Map act( Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception { Request request = ObjectModelHelper.getRequest(objectModel); Context context = ContextUtil.obtainContext(objectModel); // Or the user selected a checkbox full of workflow IDs String[] workflowIDs = request.getParameterValues("workflowID"); if (workflowIDs != null) { for (String workflowID : workflowIDs) { BasicWorkflowItem workflowItem = basicWorkflowItemService.find(context, Integer.valueOf(workflowID)); int state = workflowItem.getState(); // Only unclaim tasks that are already claimed. if (state == BasicWorkflowServiceImpl.WFSTATE_STEP1POOL || state == BasicWorkflowServiceImpl.WFSTATE_STEP2POOL || state == BasicWorkflowServiceImpl.WFSTATE_STEP3POOL) { basicWorkflowService.claim(context, workflowItem, context.getCurrentUser()); } } } return null; }
/** * Delete the specified handle. It is assumed that the user has already confirmed this selection. * * @param context The current DSpace context. * @param handleID ID of handle to be removed. * @return A results object. */ public static FlowResult processDeleteHandle(Context context, int handleID) throws SQLException, AuthorizeException, IOException { FlowResult result = new FlowResult(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_handle_deletion_failed); try { Handle handleDeleted = Handle.find(context, handleID); HandleManager.changeHandle(context, handleDeleted.getHandle(), null, false); handleDeleted.delete(); context.commit(); result.setContinue(true); result.setOutcome(true); result.setMessage(T_handle_successfully_deleted); } catch (Exception e) { log.error(e.getMessage()); context.abort(); } return result; }
/** * Method to check current status of the service and logged in user. * * <p>okay: true | false authenticated: true | false epersonEMAIL: [email protected] epersonNAME: * John Doe * * @param headers Request header which contains the header named "rest-dspace-token" containing * the token as value. * @return status the Status object with information about REST API * @throws UnsupportedEncodingException The Character Encoding is not supported. */ @GET @Path("/status") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Status status(@Context HttpHeaders headers) throws UnsupportedEncodingException { org.dspace.core.Context context = null; try { context = Resource.createContext(); EPerson ePerson = context.getCurrentUser(); if (ePerson != null) { // DB EPerson needed since token won't have full info, need context EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail()); Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName()); return status; } } catch (ContextException e) { Resource.processException("Status context error: " + e.getMessage(), context); } catch (SQLException e) { Resource.processException("Status eperson db lookup error: " + e.getMessage(), context); } finally { context.abort(); } // fallback status, unauth return new Status(); }
/** * Do any processing of the information input by the user, and/or perform step processing (if no * user interaction required) * * <p>It is this method's job to save any data to the underlying database, as necessary, and * return error messages (if any) which can then be processed by the appropriate user interface * (JSP-UI or XML-UI) * * <p>NOTE: If this step is a non-interactive step (i.e. requires no UI), then it should perform * *all* of its processing in this method! * * @param context current DSpace context * @param request current servlet request object * @param response current servlet response object * @param subInfo submission info object * @return Status or error flag which will be processed by doPostProcessing() below! (if * STATUS_COMPLETE or 0 is returned, no errors occurred!) */ public int doProcessing( Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { // The Submission is COMPLETE!! log.info( LogManager.getHeader( context, "submission_complete", "Completed submission with id=" + subInfo.getSubmissionItem().getID())); // Start the workflow for this Submission boolean success = false; try { WorkflowManager.start(context, (WorkspaceItem) subInfo.getSubmissionItem()); success = true; } catch (Exception e) { log.error("Caught exception in submission step: ", e); throw new ServletException(e); } finally { // commit changes to database if (success) { context.commit(); } else { context.getDBConnection().rollback(); } } return STATUS_COMPLETE; }
@GET @Path("/{bitstream_id}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Bitstream getBitstream( @PathParam("bitstream_id") Integer bitstream_id, @QueryParam("expand") String expand) { org.dspace.core.Context context = null; try { context = new org.dspace.core.Context(); org.dspace.content.Bitstream bitstream = org.dspace.content.Bitstream.find(context, bitstream_id); if (AuthorizeManager.authorizeActionBoolean( context, bitstream, org.dspace.core.Constants.READ)) { return new org.dspace.rest.common.Bitstream(bitstream, expand); } else { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } catch (SQLException e) { log.error(e.getMessage()); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } finally { if (context != null) { try { context.complete(); } catch (SQLException e) { log.error(e.getMessage() + " occurred while trying to close"); } } } }
@Override public void setEmbargo(Context context, Item item) throws SQLException, AuthorizeException { // if lift is null, we might be restoring an item from an AIP DCDate myLift = getEmbargoTermsAsDate(context, item); if (myLift == null) { if ((myLift = recoverEmbargoDate(item)) == null) { return; } } String slift = myLift.toString(); boolean ignoreAuth = context.ignoreAuthorization(); try { context.setIgnoreAuthorization(true); itemService.clearMetadata(context, item, lift_schema, lift_element, lift_qualifier, Item.ANY); itemService.addMetadata( context, item, lift_schema, lift_element, lift_qualifier, null, slift); log.info("Set embargo on Item " + item.getHandle() + ", expires on: " + slift); setter.setEmbargo(context, item); itemService.update(context, item); } finally { context.setIgnoreAuthorization(ignoreAuth); } }
@Override public void update(Context context, Community community) throws SQLException, AuthorizeException { // Check authorisation canEdit(context, community); log.info( LogManager.getHeader(context, "update_community", "community_id=" + community.getID())); communityDAO.save(context, community); if (community.isModified()) { context.addEvent( new Event( Event.MODIFY, Constants.COMMUNITY, community.getID(), null, getIdentifiers(context, community))); community.setModified(); } if (community.isMetadataModified()) { context.addEvent( new Event( Event.MODIFY_METADATA, Constants.COMMUNITY, community.getID(), community.getDetails(), getIdentifiers(context, community))); community.clearModified(); } community.clearDetails(); }
/** Record that this application is not running. */ public void deregister() { // Remove the database entry try { Context context = new Context(); DatabaseManager.delete(context, row); context.complete(); } catch (SQLException e) { log.error("Failed to record shutdown in Webapp table.", e); } }
/** * Authenticate the given service document request. This extracts the appropriate information from * the request and forwards to the appropriate authentication method * * @param auth * @return * @throws DSpaceSwordException * @throws SwordError * @throws SwordAuthException */ public SwordContext authenticate(AuthCredentials auth) throws DSpaceSwordException, SwordError, SwordAuthException { Context context = this.constructContext(); SwordContext sc = null; try { sc = this.authenticate(context, auth); } catch (DSpaceSwordException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (SwordError e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (SwordAuthException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } catch (RuntimeException e) { if (context != null && context.isValid()) { context.abort(); } throw e; } return sc; }
/** * Return instance of collection with passed id. You can add more properties through expand * parameter. * * @param collectionId Id of collection in DSpace. * @param expand String in which is what you want to add to returned instance of collection. * Options are: "all", "parentCommunityList", "parentCommunity", "items", "license" and * "logo". If you want to use multiple options, it must be separated by commas. * @param limit Limit value for items in list in collection. Default value is 100. * @param offset Offset of start index in list of items of collection. Default value is 0. * @param headers If you want to access to collection under logged user into context. In headers * must be set header "rest-dspace-token" with passed token from login method. * @return Return instance of collection. It can also return status code NOT_FOUND(404) if id of * collection is incorrect or status code UNATHORIZED(401) if user has no permission to read * collection. * @throws WebApplicationException It is thrown when was problem with database reading * (SQLException) or problem with creating context(ContextException). It is thrown by * NOT_FOUND and UNATHORIZED status codes, too. */ @GET @Path("/{collection_id}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public org.dspace.rest.common.Collection getCollection( @PathParam("collection_id") Integer collectionId, @QueryParam("expand") String expand, @QueryParam("limit") @DefaultValue("100") Integer limit, @QueryParam("offset") @DefaultValue("0") Integer offset, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Reading collection(id=" + collectionId + ")."); org.dspace.core.Context context = null; Collection collection = null; try { context = createContext(getUser(headers)); org.dspace.content.Collection dspaceCollection = findCollection(context, collectionId, org.dspace.core.Constants.READ); writeStats( dspaceCollection, UsageEvent.Action.VIEW, user_ip, user_agent, xforwarderfor, headers, request, context); collection = new Collection(dspaceCollection, expand, context, limit, offset); context.complete(); } catch (SQLException e) { processException( "Could not read collection(id=" + collectionId + "), SQLException. Message: " + e, context); } catch (ContextException e) { processException( "Could not read collection(id=" + collectionId + "), ContextException. Message: " + e.getMessage(), context); } finally { processFinally(context); } log.trace("Collection(id=" + collectionId + ") has been successfully read."); return collection; }
/** * Construct the context object member variable of this class using the passed IP address as part * of the loggable information * * @throws org.dspace.sword2.DSpaceSwordException */ private Context constructContext() throws DSpaceSwordException { try { Context context = new Context(); // Set the session ID and IP address context.setExtraLogInfo("session_id=0"); return context; } catch (SQLException e) { log.error("caught exception: ", e); throw new DSpaceSwordException("There was a problem with the database", e); } }
/** * Search for first collection with passed name. * * @param name Name of collection. * @param headers If you want to access to collection under logged user into context. In headers * must be set header "rest-dspace-token" with passed token from login method. * @return It returns null if collection was not found. Otherwise returns first founded * collection. * @throws WebApplicationException */ @POST @Path("/find-collection") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Collection findCollectionByName(String name, @Context HttpHeaders headers) throws WebApplicationException { log.info("Searching for first collection with name=" + name + "."); org.dspace.core.Context context = null; Collection collection = null; try { context = createContext(getUser(headers)); org.dspace.content.Collection[] dspaceCollections; dspaceCollections = org.dspace.content.Collection.findAll(context); for (org.dspace.content.Collection dspaceCollection : dspaceCollections) { if (AuthorizeManager.authorizeActionBoolean( context, dspaceCollection, org.dspace.core.Constants.READ)) { if (dspaceCollection.getName().equals(name)) { collection = new Collection(dspaceCollection, "", context, 100, 0); break; } } } context.complete(); } catch (SQLException e) { processException( "Something went wrong while searching for collection(name=" + name + ") from database. Message: " + e, context); } catch (ContextException e) { processException( "Something went wrong while searching for collection(name=" + name + "), ContextError. Message: " + e.getMessage(), context); } finally { processFinally(context); } if (collection == null) { log.info("Collection was not found."); } else { log.info("Collection was found with id(" + collection.getId() + ")."); } return collection; }
/** * Send an alert to the designated "alert recipient" - that is, when a database error or internal * error occurs, this person is sent an e-mail with details. * * <p>The recipient is configured via the "alert.recipient" property in <code>dspace.cfg</code>. * If this property is omitted, no alerts are sent. * * <p>This method "swallows" any exception that might occur - it will just be logged. This is * because this method will usually be invoked as part of an error handling routine anyway. * * @param request the HTTP request leading to the error * @param exception the exception causing the error, or null */ public static void sendAlert(HttpServletRequest request, Exception exception) { String logInfo = UIUtil.getRequestLogInfo(request); Context c = (Context) request.getAttribute("dspace.context"); Locale locale = getSessionLocale(request); EPerson user = null; try { String recipient = ConfigurationManager.getProperty("alert.recipient"); if (recipient != null) { Email email = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, "internal_error")); email.addRecipient(recipient); email.addArgument(ConfigurationManager.getProperty("dspace.url")); email.addArgument(new Date()); email.addArgument(request.getSession().getId()); email.addArgument(logInfo); String stackTrace; if (exception != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); pw.flush(); stackTrace = sw.toString(); } else { stackTrace = "No exception"; } email.addArgument(stackTrace); try { user = c.getCurrentUser(); } catch (Exception e) { log.warn("No context, the database might be down or the connection pool exhausted."); } if (user != null) { email.addArgument(user.getFullName() + " (" + user.getEmail() + ")"); } else { email.addArgument("Anonymous"); } email.addArgument(request.getRemoteAddr()); email.send(); } } catch (Exception e) { // Not much we can do here! log.warn("Unable to send email alert", e); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // we expect a path in the form /resource/<prefix>/<suffix>. String pathInfo = request.getPathInfo(); log.debug("Pathinfo: " + pathInfo); if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) { log.debug("Path does not contain the expected number of slashes."); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // remove trailing slash of the path info and split it. String[] path = request.getPathInfo().substring(1).split("/"); String handle = path[0] + "/" + path[1]; String dspaceURL = (new DSpace()).getConfigurationService().getProperty("dspace.url"); // Prepare content negotiation int requestedMimeType = Negotiator.negotiate(request.getHeader(ACCEPT_HEADER_NAME)); Context context = null; DSpaceObject dso = null; try { context = new Context(Context.READ_ONLY); dso = handleService.resolveToObject(context, handle); } catch (SQLException ex) { log.error("SQLException: " + ex.getMessage(), ex); context.abort(); // probably a problem with the db connection => send Service Unavailable response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } catch (IllegalStateException ex) { log.error( "Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex); context.abort(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (dso == null) { log.info("Cannot resolve handle '" + handle + "' to dso. => 404"); context.abort(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // close the context and send forward. context.abort(); Negotiator.sendRedirect(response, handle, "", requestedMimeType, true); }
/** * Check to see if the current user is a System Admin. Always return <code>true</code> if * c.ignoreAuthorization is set. Anonymous users can't be Admins (EPerson set to NULL) * * @param c current context * @return <code>true</code> if user is an admin or ignore authorization flag set */ public static boolean isAdmin(Context c) throws SQLException { // if we're ignoring authorization, user is member of admin if (c.ignoreAuthorization()) { return true; } EPerson e = c.getCurrentUser(); if (e == null) { return false; // anonymous users can't be admins.... } else { return Group.isMember(c, 1); } }
@Override public void removeCollection(Context context, Community community, Collection collection) throws SQLException, AuthorizeException, IOException { // Check authorisation authorizeService.authorizeAction(context, community, Constants.REMOVE); community.removeCollection(collection); ArrayList<String> removedIdentifiers = collectionService.getIdentifiers(context, collection); String removedHandle = collection.getHandle(); UUID removedId = collection.getID(); collection.removeCommunity(community); if (CollectionUtils.isEmpty(collection.getCommunities())) { collectionService.delete(context, collection); } log.info( LogManager.getHeader( context, "remove_collection", "community_id=" + community.getID() + ",collection_id=" + collection.getID())); // Remove any mappings context.addEvent( new Event( Event.REMOVE, Constants.COMMUNITY, community.getID(), Constants.COLLECTION, removedId, removedHandle, removedIdentifiers)); }
@Override public void removeSubcommunity( Context context, Community parentCommunity, Community childCommunity) throws SQLException, AuthorizeException, IOException { // Check authorisation authorizeService.authorizeAction(context, parentCommunity, Constants.REMOVE); ArrayList<String> removedIdentifiers = getIdentifiers(context, childCommunity); String removedHandle = childCommunity.getHandle(); UUID removedId = childCommunity.getID(); parentCommunity.removeSubCommunity(childCommunity); childCommunity.getParentCommunities().remove(parentCommunity); if (CollectionUtils.isEmpty(childCommunity.getParentCommunities())) { rawDelete(context, childCommunity); } log.info( LogManager.getHeader( context, "remove_subcommunity", "parent_comm_id=" + parentCommunity.getID() + ",child_comm_id=" + childCommunity.getID())); context.addEvent( new Event( Event.REMOVE, Constants.COMMUNITY, parentCommunity.getID(), Constants.COMMUNITY, removedId, removedHandle, removedIdentifiers)); }
@Override public void addCollection(Context context, Community community, Collection collection) throws SQLException, AuthorizeException { // Check authorisation authorizeService.authorizeAction(context, community, Constants.ADD); log.info( LogManager.getHeader( context, "add_collection", "community_id=" + community.getID() + ",collection_id=" + collection.getID())); if (!community.getCollections().contains(collection)) { community.addCollection(collection); collection.addCommunity(community); } context.addEvent( new Event( Event.ADD, Constants.COMMUNITY, community.getID(), Constants.COLLECTION, collection.getID(), community.getHandle(), getIdentifiers(context, community))); }
@Override public void addSubcommunity(Context context, Community parentCommunity, Community childCommunity) throws SQLException, AuthorizeException { // Check authorisation authorizeService.authorizeAction(context, parentCommunity, Constants.ADD); log.info( LogManager.getHeader( context, "add_subcommunity", "parent_comm_id=" + parentCommunity.getID() + ",child_comm_id=" + childCommunity.getID())); if (!parentCommunity.getSubcommunities().contains(childCommunity)) { parentCommunity.addSubCommunity(childCommunity); childCommunity.addParentCommunity(parentCommunity); } context.addEvent( new Event( Event.ADD, Constants.COMMUNITY, parentCommunity.getID(), Constants.COMMUNITY, childCommunity.getID(), parentCommunity.getHandle(), getIdentifiers(context, parentCommunity))); }
/* * Add authenticated users to the group defined in dspace.cfg by * the login.specialgroup key. */ @Override public List<Group> getSpecialGroups(Context context, HttpServletRequest request) { // Prevents anonymous users from being added to this group, and the second check // ensures they are LDAP users try { if (!context.getCurrentUser().getNetid().equals("")) { String groupName = ConfigurationManager.getProperty("authentication-ldap", "login.specialgroup"); if ((groupName != null) && (!groupName.trim().equals(""))) { Group ldapGroup = groupService.findByName(context, groupName); if (ldapGroup == null) { // Oops - the group isn't there. log.warn( LogManager.getHeader( context, "ldap_specialgroup", "Group defined in login.specialgroup does not exist")); return ListUtils.EMPTY_LIST; } else { return Arrays.asList(ldapGroup); } } } } catch (Exception npe) { // The user is not an LDAP user, so we don't need to worry about them } return ListUtils.EMPTY_LIST; }
public static void main(String[] args) { // get a context from an anonymous user. // don't switch off authorization system! We'll export the converted // data into a triple store that provides a public sparql endpoint. // all exported rdf data can be read by anonymous users. // We won't change the database => read_only context will assure this. Context context = new Context(Context.READ_ONLY); RDFizer myself = null; myself = new RDFizer(); myself.overrideContext(context); myself.runCLI(args); // we don't change anything in the database, so abort the context. context.abort(); }
/** * Process the input from the CC license page * * @param context current DSpace context * @param request current servlet request object * @param response current servlet response object * @param subInfo submission info object * @return Status or error flag which will be processed by doPostProcessing() below! (if * STATUS_COMPLETE or 0 is returned, no errors occurred!) */ protected int processCC( Context context, HttpServletRequest request, HttpServletResponse response, SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException { String buttonPressed = Util.getSubmitButton(request, NEXT_BUTTON); // RLR hack - need to distinguish between progress bar real submission // (if cc_license_url exists, then users has accepted the CC License) String ccLicenseUrl = request.getParameter("cc_license_url"); if (buttonPressed.equals("submit_no_cc")) { // Skipping the CC license - remove any existing license selection creativeCommonsService.removeLicense(context, subInfo.getSubmissionItem().getItem()); } else if ((ccLicenseUrl != null) && (ccLicenseUrl.length() > 0)) { Item item = subInfo.getSubmissionItem().getItem(); // save the CC license creativeCommonsService.setLicense(context, item, ccLicenseUrl); } // commit changes context.dispatchEvents(); // completed without errors return STATUS_COMPLETE; }
/** * 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; } }
/** * 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(); } } }
/** * Execute an update, insert or delete query. Returns the number of rows affected by the query. * * @param context Current DSpace context * @param query The SQL query to execute * @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 The number of rows affected by the query. * @exception SQLException If a database error occurs */ public static int updateQuery(Context context, String query, Object... parameters) throws SQLException { PreparedStatement statement = null; if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder("Running query \"").append(query).append("\" with parameters: "); for (int i = 0; i < parameters.length; i++) { if (i > 0) { sb.append(","); } sb.append(parameters[i].toString()); } log.debug(sb.toString()); } try { statement = context.getDBConnection().prepareStatement(query); loadParameters(statement, parameters); return statement.executeUpdate(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException sqle) { } } } }
private boolean allowedToMediate(Context context) { // get the configuration String mediatorCfg = ConfigurationManager.getProperty("swordv2-server", "on-behalf-of.update.mediators"); if (mediatorCfg == null) { // if there's no explicit list of mediators, then anyone can mediate return true; } // get the email and netid of the mediator EPerson eperson = context.getCurrentUser(); if (eperson == null) { return false; } String email = eperson.getEmail(); String netid = eperson.getNetid(); String[] mediators = mediatorCfg.split(","); for (String mediator : mediators) { String m = mediator.trim(); if (email != null && m.equals(email.trim())) { return true; } if (netid != null && m.equals(netid.trim())) { return true; } } return false; }
/** * Update changes to the RDBMS. Note that if the update fails, the values in the row will NOT be * reverted. * * @param context Current DSpace context * @param row The row to update * @return The number of rows affected (1 or 0) * @exception SQLException If a database error occurs */ public static int update(Context context, TableRow row) throws SQLException { String table = row.getTable(); StringBuilder sql = new StringBuilder().append("update ").append(table).append(" set "); List<ColumnInfo> columns = new ArrayList<ColumnInfo>(); ColumnInfo pk = getPrimaryKeyColumnInfo(table); Collection<ColumnInfo> info = getColumnInfo(table); String separator = ""; for (ColumnInfo col : info) { // Only update this column if it has changed if (!col.isPrimaryKey()) { if (row.hasColumnChanged(col.getName())) { sql.append(separator).append(col.getName()).append(" = ?"); columns.add(col); separator = ", "; } } } // Only execute the update if there is anything to update if (columns.size() > 0) { sql.append(" where ").append(pk.getName()).append(" = ?"); columns.add(pk); return executeUpdate(context.getDBConnection(), sql.toString(), columns, row); } return 1; }
/** Record that this application is running. */ public void register() { // Create the database entry Timestamp now = new Timestamp(started.getTime()); try { Context context = new Context(); row = DatabaseManager.create(context, "Webapp"); row.setColumn("AppName", kind); row.setColumn("URL", url); row.setColumn("Started", now); row.setColumn("isUI", isUI() ? 1 : 0); // update won't widen boolean to integer DatabaseManager.update(context, row); context.complete(); } catch (SQLException e) { log.error("Failed to record startup in Webapp table.", e); } }