Search in sources :

Example 1 with SynapseNotFoundException

use of org.sagebionetworks.client.exceptions.SynapseNotFoundException in project BridgeServer2 by Sage-Bionetworks.

the class AppAndUsersValidator method validate.

@Override
public void validate(Object object, Errors errors) {
    AppAndUsers appAndUsers = (AppAndUsers) object;
    App app = appAndUsers.getApp();
    if (app == null) {
        errors.rejectValue("app", "cannot be null");
        return;
    } else {
        errors.pushNestedPath("app");
        try {
            BridgeUtils.toSynapseFriendlyName(app.getName());
        } catch (NullPointerException | IllegalArgumentException e) {
            errors.rejectValue("name", "is an invalid Synapse project name");
        }
        if (StringUtils.isBlank(app.getSponsorName())) {
            errors.rejectValue("sponsorName", "is required");
        }
        if (StringUtils.isBlank(app.getIdentifier())) {
            errors.rejectValue("identifier", "is required");
        }
        errors.popNestedPath();
    }
    StudyParticipantValidator participantValidator = new StudyParticipantValidator(studyService, organizationService, app, true);
    List<String> adminIds = appAndUsers.getAdminIds();
    if (adminIds == null || adminIds.isEmpty()) {
        errors.rejectValue("adminIds", "are required");
    } else {
        for (int i = 0; i < adminIds.size(); i++) {
            String adminId = adminIds.get(i);
            errors.pushNestedPath("adminIds[" + i + "]");
            if (isBlank(adminId)) {
                errors.rejectValue("", "cannot be blank or null");
            }
            try {
                synapseClient.getUserProfile(adminId);
            } catch (SynapseNotFoundException e) {
                errors.rejectValue("", "is invalid");
            } catch (SynapseException se) {
                throw new RuntimeException(se);
            }
            errors.popNestedPath();
        }
    }
    List<StudyParticipant> users = appAndUsers.getUsers();
    if (users == null || users.isEmpty()) {
        errors.rejectValue("users", "are required");
    } else {
        for (int i = 0; i < users.size(); i++) {
            StudyParticipant user = users.get(i);
            errors.pushNestedPath("users[" + i + "]");
            if (isBlank(user.getSynapseUserId())) {
                errors.rejectValue("synapseUserId", "cannot be blank");
            } else {
                try {
                    synapseClient.getUserProfile(user.getSynapseUserId());
                } catch (SynapseNotFoundException e) {
                    errors.rejectValue("synapseUserId", "is invalid");
                } catch (SynapseException se) {
                    throw new RuntimeException(se);
                }
            }
            // validate roles for each user
            if (user.getRoles() == null || user.getRoles().isEmpty()) {
                errors.rejectValue("roles", "should have at least one role");
            } else if (!Collections.disjoint(user.getRoles(), ImmutableSet.of(ADMIN, WORKER, SUPERADMIN))) {
                errors.rejectValue("roles", "can only have roles developer and/or researcher");
            }
            // validate the user
            participantValidator.validate(user, errors);
            errors.popNestedPath();
        }
    }
}
Also used : App(org.sagebionetworks.bridge.models.apps.App) SynapseException(org.sagebionetworks.client.exceptions.SynapseException) StudyParticipant(org.sagebionetworks.bridge.models.accounts.StudyParticipant) AppAndUsers(org.sagebionetworks.bridge.models.apps.AppAndUsers) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException)

Example 2 with SynapseNotFoundException

use of org.sagebionetworks.client.exceptions.SynapseNotFoundException in project Synapse-Repository-Services by Sage-Bionetworks.

the class DeleteWorker method call.

@Override
public WorkerResult call() throws Exception {
    try {
        // We only delete from the destination.
        SynapseAdministration client = clientFactory.createNewDestinationClient(configuration);
        for (String entityId : this.entites) {
            try {
                MigratableObjectDescriptor mod = new MigratableObjectDescriptor();
                mod.setId(entityId);
                mod.setType(objectType);
                client.deleteObject(mod);
            } catch (SynapseNotFoundException e) {
            // There is nothing to do if the entity does not exist
            } catch (SynapseServiceException e) {
                if (e.getCause() instanceof SocketTimeoutException) {
                    // Deletes can take a long to complete so we just continue when it happens
                    Thread.sleep(2000);
                } else {
                    throw e;
                }
            }
            progress.setCurrent(progress.getCurrent() + 1);
            Thread.sleep(1000);
        }
        // done
        progress.setDone();
        return new WorkerResult(this.entites.size(), WorkerResult.JobStatus.SUCCEEDED);
    } catch (Exception e) {
        // done
        progress.setDone();
        // Log any errors
        log.error("CreateUpdateWorker Failed to run job: " + entites.toString(), e);
        return new WorkerResult(0, WorkerResult.JobStatus.FAILED);
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) SynapseServiceException(org.sagebionetworks.client.exceptions.SynapseServiceException) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException) MigratableObjectDescriptor(org.sagebionetworks.repo.model.MigratableObjectDescriptor) SynapseAdministration(org.sagebionetworks.client.SynapseAdministration) SynapseServiceException(org.sagebionetworks.client.exceptions.SynapseServiceException) SocketTimeoutException(java.net.SocketTimeoutException) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException)

Example 3 with SynapseNotFoundException

use of org.sagebionetworks.client.exceptions.SynapseNotFoundException in project Synapse-Repository-Services by Sage-Bionetworks.

the class Synapse method dispatchSynapseRequest.

/**
 * Convert exceptions emanating from the service to
 * Synapse[User|Service]Exception but let all other types of exceptions
 * bubble up as usual
 *
 * @param requestUrl
 * @param requestMethod
 * @param requestContent
 * @param requestHeaders
 * @return
 */
protected JSONObject dispatchSynapseRequest(String endpoint, String uri, String requestMethod, String requestContent, Map<String, String> requestHeaders) throws SynapseException {
    if (requestProfile && !requestMethod.equals("DELETE")) {
        requestHeaders.put(REQUEST_PROFILE_DATA, "true");
    } else {
        if (requestHeaders.containsKey(REQUEST_PROFILE_DATA))
            requestHeaders.remove(REQUEST_PROFILE_DATA);
    }
    // remove session token if it is null
    if (requestHeaders.containsKey(SESSION_TOKEN_HEADER) && requestHeaders.get(SESSION_TOKEN_HEADER) == null) {
        requestHeaders.remove(SESSION_TOKEN_HEADER);
    }
    JSONObject results = null;
    URL requestUrl = null;
    try {
        URL parsedEndpoint = new URL(endpoint);
        String endpointPrefix = parsedEndpoint.getPath();
        String endpointLocation = endpoint.substring(0, endpoint.length() - endpointPrefix.length());
        requestUrl = (uri.startsWith(endpointPrefix)) ? new URL(endpointLocation + uri) : new URL(endpoint + uri);
        HttpResponse response = clientProvider.performRequest(requestUrl.toString(), requestMethod, requestContent, requestHeaders);
        if (requestProfile && !requestMethod.equals("DELETE")) {
            Header header = response.getFirstHeader(PROFILE_RESPONSE_OBJECT_HEADER);
            String encoded = header.getValue();
            String decoded = new String(Base64.decodeBase64(encoded.getBytes("UTF-8")), "UTF-8");
            profileData = new JSONObject(decoded);
        } else {
            profileData = null;
        }
        String responseBody = (null != response.getEntity()) ? EntityUtils.toString(response.getEntity()) : null;
        if (null != responseBody && responseBody.length() > 0) {
            try {
                results = new JSONObject(responseBody);
            } catch (JSONException jsone) {
                throw new SynapseServiceException("responseBody: <<" + responseBody + ">>", jsone);
            }
            if (log.isDebugEnabled()) {
                if (authEndpoint.equals(endpoint)) {
                    log.debug(requestMethod + " " + requestUrl + " : (not logging auth request details)");
                } else {
                    log.debug(requestMethod + " " + requestUrl + " : " + results.toString(JSON_INDENT));
                }
            }
        }
    } catch (HttpClientHelperException e) {
        // Well-handled server side exceptions come back as JSON, attempt to
        // deserialize and convert the error
        // assume a service exception
        int statusCode = 500;
        statusCode = e.getHttpStatus();
        String response = "";
        String resultsStr = "";
        try {
            response = e.getResponse();
            if (null != response && response.length() > 0) {
                try {
                    results = new JSONObject(response);
                } catch (JSONException jsone) {
                    throw new SynapseServiceException("Failed to parse: " + response, jsone);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved " + requestUrl + " : " + results.toString(JSON_INDENT));
                }
                if (results != null)
                    resultsStr = results.getString("reason");
            }
            String exceptionContent = "Service Error(" + statusCode + "): " + resultsStr + " " + e.getMessage();
            if (statusCode == 401) {
                throw new SynapseUnauthorizedException(exceptionContent);
            } else if (statusCode == 403) {
                throw new SynapseForbiddenException(exceptionContent);
            } else if (statusCode == 404) {
                throw new SynapseNotFoundException(exceptionContent);
            } else if (statusCode == 400) {
                throw new SynapseBadRequestException(exceptionContent);
            } else if (statusCode >= 400 && statusCode < 500) {
                throw new SynapseUserException(exceptionContent);
            } else {
                throw new SynapseServiceException("request content: " + requestContent + " exception content: " + exceptionContent);
            }
        } catch (JSONException jsonEx) {
            // return the response as-is since it is not JSON
            throw new SynapseServiceException(jsonEx);
        } catch (ParseException parseEx) {
            throw new SynapseServiceException(parseEx);
        }
    }// end catch
     catch (MalformedURLException e) {
        throw new SynapseServiceException(e);
    } catch (ClientProtocolException e) {
        throw new SynapseServiceException(e);
    } catch (IOException e) {
        throw new SynapseServiceException(e);
    } catch (JSONException e) {
        throw new SynapseServiceException(e);
    }
    return results;
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException) URL(java.net.URL) HttpClientHelperException(org.sagebionetworks.utils.HttpClientHelperException) ClientProtocolException(org.apache.http.client.ClientProtocolException) SynapseBadRequestException(org.sagebionetworks.client.exceptions.SynapseBadRequestException) SynapseUnauthorizedException(org.sagebionetworks.client.exceptions.SynapseUnauthorizedException) SynapseForbiddenException(org.sagebionetworks.client.exceptions.SynapseForbiddenException) JSONObject(org.json.JSONObject) Header(org.apache.http.Header) EntityHeader(org.sagebionetworks.repo.model.EntityHeader) SynapseUserException(org.sagebionetworks.client.exceptions.SynapseUserException) SynapseServiceException(org.sagebionetworks.client.exceptions.SynapseServiceException) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException) ParseException(org.apache.http.ParseException)

Example 4 with SynapseNotFoundException

use of org.sagebionetworks.client.exceptions.SynapseNotFoundException in project Synapse-Repository-Services by Sage-Bionetworks.

the class IT100BackupRestoration method testPLFM1464DeleteACL.

@Test
public void testPLFM1464DeleteACL() throws Exception {
    // Create a project
    Project project = new Project();
    project = synapse.createEntity(project);
    assertNotNull(project);
    toDelete.add(project);
    // create a child object for this project
    Data data = new Data();
    data.setParentId(project.getId());
    data = synapse.createEntity(data);
    // Now make a backup copy of this entity
    BackupSubmission submission = new BackupSubmission();
    Set<String> set = new HashSet<String>();
    set.add(project.getId());
    set.add(data.getId());
    submission.setEntityIdsToBackup(set);
    BackupRestoreStatus status = synapse.startBackupDaemon(submission, MigratableObjectType.ENTITY);
    assertNotNull(status);
    // Wait for the daemon to complete
    status = waitForDaemon(status.getId());
    assertNotNull(status.getBackupUrl());
    String backupFileName = getFileNameFromUrl(status.getBackupUrl());
    try {
        synapse.getACL(data.getId());
        fail("exception expected");
    } catch (SynapseNotFoundException e) {
    // as expected
    }
    // give the child its own ACL
    AccessControlList acl = new AccessControlList();
    acl.setId(data.getId());
    Set<ResourceAccess> ras = new HashSet<ResourceAccess>();
    ResourceAccess ra = new ResourceAccess();
    String myPrincipalId = synapse.getMyProfile().getOwnerId();
    ra.setPrincipalId(Long.parseLong(myPrincipalId));
    ra.setAccessType(new HashSet<ACCESS_TYPE>(Arrays.asList(new ACCESS_TYPE[] { ACCESS_TYPE.READ })));
    ras.add(ra);
    acl.setResourceAccess(ras);
    acl = synapse.createACL(acl);
    // should not generate a SynapseNotFoundException
    synapse.getACL(data.getId());
    // Now restore the single project
    RestoreSubmission restore = new RestoreSubmission();
    restore.setFileName(backupFileName);
    status = synapse.startRestoreDaemon(restore, MigratableObjectType.ENTITY);
    // Wait for the daemon to complete
    status = waitForDaemon(status.getId());
    // Now make sure we can get the project
    project = synapse.getEntity(project.getId(), Project.class);
    assertNotNull(project);
    // child should not have an ACL
    try {
        synapse.getACL(data.getId());
        fail("exception expected");
    } catch (SynapseNotFoundException e) {
    // as expected
    }
}
Also used : BackupSubmission(org.sagebionetworks.repo.model.daemon.BackupSubmission) AccessControlList(org.sagebionetworks.repo.model.AccessControlList) ResourceAccess(org.sagebionetworks.repo.model.ResourceAccess) BackupRestoreStatus(org.sagebionetworks.repo.model.daemon.BackupRestoreStatus) RestoreSubmission(org.sagebionetworks.repo.model.daemon.RestoreSubmission) Data(org.sagebionetworks.repo.model.Data) Project(org.sagebionetworks.repo.model.Project) ACCESS_TYPE(org.sagebionetworks.repo.model.ACCESS_TYPE) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with SynapseNotFoundException

use of org.sagebionetworks.client.exceptions.SynapseNotFoundException in project BridgeServer2 by Sage-Bionetworks.

the class AppAndUsersValidatorTest method userSynapseUserIdInvalid.

@Test
public void userSynapseUserIdInvalid() throws SynapseException {
    when(mockSynapseClient.getUserProfile("userId")).thenThrow(new SynapseNotFoundException());
    StudyParticipant participant = new StudyParticipant.Builder().withSynapseUserId("userId").build();
    AppAndUsers model = new AppAndUsers(null, App.create(), ImmutableList.of(participant));
    assertValidatorMessage(validator, model, "users[0].synapseUserId", "is invalid");
    verify(mockSynapseClient).getUserProfile("userId");
}
Also used : AppAndUsers(org.sagebionetworks.bridge.models.apps.AppAndUsers) SynapseNotFoundException(org.sagebionetworks.client.exceptions.SynapseNotFoundException) StudyParticipant(org.sagebionetworks.bridge.models.accounts.StudyParticipant) Test(org.testng.annotations.Test)

Aggregations

SynapseNotFoundException (org.sagebionetworks.client.exceptions.SynapseNotFoundException)8 AppAndUsers (org.sagebionetworks.bridge.models.apps.AppAndUsers)4 Test (org.testng.annotations.Test)3 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 StudyParticipant (org.sagebionetworks.bridge.models.accounts.StudyParticipant)2 SynapseServiceException (org.sagebionetworks.client.exceptions.SynapseServiceException)2 ACCESS_TYPE (org.sagebionetworks.repo.model.ACCESS_TYPE)2 AccessControlList (org.sagebionetworks.repo.model.AccessControlList)2 Data (org.sagebionetworks.repo.model.Data)2 Project (org.sagebionetworks.repo.model.Project)2 ResourceAccess (org.sagebionetworks.repo.model.ResourceAccess)2 BackupRestoreStatus (org.sagebionetworks.repo.model.daemon.BackupRestoreStatus)2 BackupSubmission (org.sagebionetworks.repo.model.daemon.BackupSubmission)2 RestoreSubmission (org.sagebionetworks.repo.model.daemon.RestoreSubmission)2 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URL (java.net.URL)1 Header (org.apache.http.Header)1