Search in sources :

Example 16 with DataAccessException

use of org.springframework.dao.DataAccessException in project hudson-2.x by hudson.

the class ClientAuthenticationCache method get.

/**
     * Gets the persisted authentication for this Hudson.
     *
     * @return {@link Hudson#ANONYMOUS} if no such credential is found, or if the stored credential is invalid.
     */
public Authentication get() {
    Hudson h = Hudson.getInstance();
    Secret userName = Secret.decrypt(props.getProperty(getPropertyKey()));
    // failed to decrypt
    if (userName == null)
        return Hudson.ANONYMOUS;
    try {
        UserDetails u = h.getSecurityRealm().loadUserByUsername(userName.toString());
        return new UsernamePasswordAuthenticationToken(u.getUsername(), u.getPassword(), u.getAuthorities());
    } catch (AuthenticationException e) {
        return Hudson.ANONYMOUS;
    } catch (DataAccessException e) {
        return Hudson.ANONYMOUS;
    }
}
Also used : Secret(hudson.util.Secret) UserDetails(org.acegisecurity.userdetails.UserDetails) AuthenticationException(org.acegisecurity.AuthenticationException) Hudson(hudson.model.Hudson) UsernamePasswordAuthenticationToken(org.acegisecurity.providers.UsernamePasswordAuthenticationToken) DataAccessException(org.springframework.dao.DataAccessException)

Example 17 with DataAccessException

use of org.springframework.dao.DataAccessException in project opennms by OpenNMS.

the class DefaultEventConfDao method loadConfig.

private synchronized void loadConfig() throws DataAccessException {
    try {
        Events events = JaxbUtils.unmarshal(Events.class, m_configResource);
        m_lastModifiedEventFiles = events.loadEventFiles(m_configResource);
        m_partition = new EnterpriseIdPartition();
        events.initialize(m_partition, new EventOrdering());
        m_events = events;
    } catch (Exception e) {
        throw new DataRetrievalFailureException("Unabled to load " + m_configResource, e);
    }
}
Also used : EventOrdering(org.opennms.netmgt.xml.eventconf.EventOrdering) Events(org.opennms.netmgt.xml.eventconf.Events) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) DataAccessException(org.springframework.dao.DataAccessException) DataRetrievalFailureException(org.springframework.dao.DataRetrievalFailureException) IOException(java.io.IOException)

Example 18 with DataAccessException

use of org.springframework.dao.DataAccessException in project perun by CESNET.

the class AttributesManagerImpl method setAttributeInDB.

private boolean setAttributeInDB(final PerunSession sess, final Attribute attribute, final String tableName, final Map<String, Object> params) throws InternalErrorException {
    // get two sorted lists for parameter names and values
    List<String> columnNames = new ArrayList<>();
    List<Object> columnValues = new ArrayList<>();
    for (Entry entry : params.entrySet()) {
        columnNames.add((String) entry.getKey());
        columnValues.add(entry.getValue());
    }
    try {
        // deleting the attibute if the given attribute value is null
        if (attribute.getValue() == null) {
            int numAffected = jdbc.update("delete from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
            if (numAffected > 1) {
                throw new ConsistencyErrorException(String.format("Too much rows to delete (" + numAffected + " rows). SQL: delete from " + tableName + " where " + buildParameters(columnNames, "=%s", " and "), columnValues.toArray()));
            }
            return numAffected == 1;
        }
        // set the column name according to the size of the attribute
        boolean largeAttribute = isLargeAttribute(sess, attribute);
        String valueColName = (largeAttribute ? "attr_value_text" : "attr_value");
        // if the DB value is the same as parameter, return
        if (!largeAttribute) {
            try {
                Object value = BeansUtils.stringToAttributeValue(jdbc.queryForObject("select attr_value from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), String.class, columnValues.toArray()), attribute.getType());
                if (attribute.getValue().equals(value)) {
                    return false;
                }
            } catch (EmptyResultDataAccessException ex) {
            //This is ok. Attribute will be stored later.
            }
        }
        int repetatCounter = 0;
        while (true) {
            // number of values of this attribute value in db
            int numOfAttributesInDb = jdbc.queryForInt("select count(attr_id) from " + tableName + " where " + buildParameters(columnNames, "=?", " and "), columnValues.toArray());
            switch(numOfAttributesInDb) {
                case 0:
                    {
                        // value doesn't exist -> insert
                        try {
                            return self.insertAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
                        } catch (DataAccessException ex) {
                            // unsuccessful insert, do it again in while loop
                            if (++repetatCounter > MERGE_TRY_CNT) {
                                throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
                            }
                            try {
                                //randomized sleep
                                Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
                            } catch (InterruptedException IGNORE) {
                            }
                        }
                        break;
                    }
                case 1:
                    {
                        // value exists -> update
                        try {
                            return self.updateAttribute(sess, valueColName, attribute, tableName, columnNames, columnValues);
                        } catch (DataAccessException ex) {
                            // unsuccessful insert, do it again in while loop
                            if (++repetatCounter > MERGE_TRY_CNT) {
                                throw new InternalErrorException("SQL merger (or other UPSERT command) failed more than " + MERGE_TRY_CNT + " times.");
                            }
                            try {
                                //randomized sleep
                                Thread.sleep(Math.round(MERGE_RAND_SLEEP_MAX * Math.random()));
                            } catch (InterruptedException IGNORE) {
                            }
                        }
                        break;
                    }
                default:
                    throw new ConsistencyErrorException(String.format("Attribute id " + attribute.getId() + " for " + tableName + " with parameters: " + buildParameters(columnNames, "=%s", " and ") + " is more than once in DB.", columnValues.toArray()));
            }
        }
    } catch (RuntimeException e) {
        throw new InternalErrorException(e);
    }
}
Also used : ConsistencyErrorException(cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Entry(java.util.Map.Entry) ConsistencyErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.ConsistencyErrorRuntimeException) InternalErrorRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) DataAccessException(org.springframework.dao.DataAccessException)

Example 19 with DataAccessException

use of org.springframework.dao.DataAccessException in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method addExternalIdentifiers.

/**
     * Add new external identifiers to the profile. As with all calls, if the
     * message contains any other elements, a 400 Bad Request will be returned.
     * 
     * @param orcidMessage
     *            the message congtaining the external ids
     * @return If successful, returns a 200 OK with the updated content.
     */
@Override
@AccessControl(requiredScope = ScopePathType.ORCID_BIO_EXTERNAL_IDENTIFIERS_CREATE)
public Response addExternalIdentifiers(UriInfo uriInfo, String orcid, OrcidMessage orcidMessage) {
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    try {
        ExternalIdentifiers updatedExternalIdentifiers = orcidProfile.getOrcidBio().getExternalIdentifiers();
        // Get the client profile information
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String clientId = null;
        if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
            OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
            clientId = authorizationRequest.getClientId();
        }
        for (ExternalIdentifier ei : updatedExternalIdentifiers.getExternalIdentifier()) {
            // Set the client profile to each external identifier
            if (ei.getSource() == null) {
                Source source = new Source();
                source.setSourceClientId(new SourceClientId(clientId));
                ei.setSource(source);
            } else {
                // Check if the provided external orcid exists
                Source source = ei.getSource();
                String sourceOrcid = source.retrieveSourcePath();
                if (sourceOrcid != null) {
                    if (StringUtils.isBlank(sourceOrcid) || (!profileEntityManager.orcidExists(sourceOrcid) && !clientDetailsManager.exists(sourceOrcid))) {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("orcid", sourceOrcid);
                        throw new OrcidNotFoundException(params);
                    }
                }
            }
        }
        orcidProfile = orcidProfileManager.addExternalIdentifiers(orcidProfile);
        return getOrcidMessageResponse(orcidProfile, orcid);
    } catch (DataAccessException e) {
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_createorcid.exception"));
    }
}
Also used : ExternalIdentifier(org.orcid.jaxb.model.message.ExternalIdentifier) HashMap(java.util.HashMap) SourceClientId(org.orcid.jaxb.model.message.SourceClientId) Source(org.orcid.jaxb.model.message.Source) OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) ExternalIdentifiers(org.orcid.jaxb.model.message.ExternalIdentifiers) DataAccessException(org.springframework.dao.DataAccessException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 20 with DataAccessException

use of org.springframework.dao.DataAccessException in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method createProfile.

/**
     * Creates a new profile and returns the saved representation of it. The
     * response should include the 'location' to retrieve the newly created
     * profile from.
     * 
     * @param orcidMessage
     *            the message to be saved. If the message already contains an
     *            ORCID value a 400 Bad Request
     * @return if the creation was successful, returns a 201 along with the
     *         location of the newly created resource otherwise returns an error
     *         response describing the problem
     */
@Override
@AccessControl(requiredScope = ScopePathType.ORCID_PROFILE_CREATE)
public Response createProfile(UriInfo uriInfo, OrcidMessage orcidMessage) {
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    try {
        setSponsorFromAuthentication(orcidProfile);
        orcidProfile = orcidProfileManager.createOrcidProfileAndNotify(orcidProfile);
        return getCreatedResponse(uriInfo, PROFILE_GET_PATH, orcidProfile);
    } catch (DataAccessException e) {
        if (e.getCause() != null && ConstraintViolationException.class.isAssignableFrom(e.getCause().getClass())) {
            throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_email_exists.exception"));
        }
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_createorcid.exception"), e);
    }
}
Also used : OrcidProfile(org.orcid.jaxb.model.message.OrcidProfile) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) DataAccessException(org.springframework.dao.DataAccessException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Aggregations

DataAccessException (org.springframework.dao.DataAccessException)89 SQLException (java.sql.SQLException)40 Test (org.junit.Test)26 Connection (java.sql.Connection)17 ResultSet (java.sql.ResultSet)16 PreparedStatement (java.sql.PreparedStatement)14 MongoException (com.mongodb.MongoException)13 Document (org.bson.Document)8 TransactionStatus (org.springframework.transaction.TransactionStatus)7 HashMap (java.util.HashMap)6 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)5 DeadlockLoserDataAccessException (org.springframework.dao.DeadlockLoserDataAccessException)5 IOException (java.io.IOException)4 ConnectionCallback (org.springframework.jdbc.core.ConnectionCallback)4 SpringSqlParams (com.opengamma.elsql.SpringSqlParams)3 DatabaseMetaData (java.sql.DatabaseMetaData)3 Statement (java.sql.Statement)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IJoinQueryString (org.apereo.portal.jdbc.IJoinQueryString)3