Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.osaf.cosmo.atom.provider.ItemCollectionAdapter.java

public ResponseContext putCollection(RequestContext request) {
    CollectionTarget target = (CollectionTarget) request.getTarget();
    CollectionItem collection = target.getCollection();

    if (collection instanceof HomeCollectionItem)
        return ProviderHelper.unauthorized(request, "Home collection is not modifiable");

    if (log.isDebugEnabled())
        log.debug("updating details for collection " + collection.getUid());

    ResponseContext frc = checkCollectionWritePreconditions(request);
    if (frc != null)
        return frc;

    try {//from   w  ww  .j  a v  a  2 s  .com
        CollectionItem content = readCollection(request);

        if (!content.getDisplayName().equals(collection.getDisplayName())) {
            if (log.isDebugEnabled())
                log.debug("updating collection " + collection.getUid());
            collection.setDisplayName(content.getDisplayName());
            collection = contentService.updateCollection(collection);
        }

        return updated(collection);
    } catch (IOException e) {
        String reason = "Unable to read request content: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (ValidationException e) {
        String msg = "Invalid request content: " + e.getMessage();
        if (e.getCause() != null)
            msg += ": " + e.getCause().getMessage();
        return ProviderHelper.badrequest(request, msg);
    } catch (CollectionLockedException e) {
        return locked(request);
    } catch (CosmoSecurityException e) {
        if (e instanceof ItemSecurityException)
            return insufficientPrivileges(request,
                    new InsufficientPrivilegesException((ItemSecurityException) e));
        else
            return ProviderHelper.forbidden(request, e.getMessage());
    }
}

From source file:de.ingrid.portal.interfaces.impl.IBUSInterfaceImpl.java

/**
 * @throws Exception /*  w ww.  j a  va  2  s .com*/
 * @see de.ingrid.portal.interfaces.IBUSInterface#search(de.ingrid.utils.query.IngridQuery, int, int, int, int)
 */
public IngridHits search(IngridQuery query, int hitsPerPage, int currentPage, int startHit, int timeout)
        throws Exception {
    IngridHits hits = null;

    injectCache(query);

    try {
        if (log.isDebugEnabled()) {
            log.debug("iBus.search: IngridQuery = " + UtilsSearch.queryToString(query) + " / timeout=" + timeout
                    + ", hitsPerPage=" + hitsPerPage + ", currentPage=" + currentPage + ", startHit="
                    + startHit);
        }
        long start = System.currentTimeMillis();

        hits = bus.search(query, hitsPerPage, currentPage, startHit, timeout);

        if (log.isDebugEnabled()) {
            long duration = System.currentTimeMillis() - start;
            log.debug("iBus.search: finished !");
            log.debug("in " + duration + "ms");
        }
    } catch (java.io.IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Problems doing iBus search, query=" + UtilsSearch.queryToString(query) + " / timeout="
                    + timeout + ", hitsPerPage=" + hitsPerPage + ", currentPage=" + currentPage + ", startHit="
                    + startHit, e);
        } else if (log.isInfoEnabled()) {
            log.info("Problems doing iBus search, query=" + UtilsSearch.queryToString(query) + " / timeout="
                    + timeout + ", hitsPerPage=" + hitsPerPage + ", currentPage=" + currentPage + ", startHit="
                    + startHit + "[cause:" + e.getMessage() + "]");
        } else {
            log.warn("Problems doing iBus search, query=" + UtilsSearch.queryToString(query) + " / timeout="
                    + timeout + ", hitsPerPage=" + hitsPerPage + ", currentPage=" + currentPage + ", startHit="
                    + startHit + "[cause:" + e.getCause().getMessage() + "]", e);
        }
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            log.error("Problems doing iBus search, query=" + UtilsSearch.queryToString(query) + " / timeout="
                    + timeout + ", hitsPerPage=" + hitsPerPage + ", currentPage=" + currentPage + ", startHit="
                    + startHit, t);
        }
        throw new Exception(t);
    }

    return hits;
}

From source file:org.pentaho.big.data.impl.shim.mapreduce.PentahoMapReduceJobBuilderImplTest.java

@Test(expected = IOException.class)
public void testSubmitNoInstallPath() throws IOException {
    Configuration conf = mock(Configuration.class);
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_USE_DISTRIBUTED_CACHE))
            .thenReturn("true");
    try {/*  w w  w  .java2  s . c o  m*/
        pentahoMapReduceJobBuilder.submit(conf);
    } catch (IOException e) {
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_INSTALLATION_OF_KETTLE_FAILED),
                e.getMessage());
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_KETTLE_HDFS_INSTALL_DIR_MISSING),
                e.getCause().getMessage());
        throw e;
    }
}

From source file:org.osaf.cosmo.atom.provider.ItemCollectionAdapter.java

protected ResponseContext createCollectionXHTML(RequestContext request) {
    NewCollectionTarget target = (NewCollectionTarget) request.getTarget();
    User user = target.getUser();/* ww  w  .j  av a  2s  .c o m*/
    HomeCollectionItem home = target.getHomeCollection();

    if (log.isDebugEnabled())
        log.debug("creating collection in home collection of user '" + user.getUsername() + "'");

    ResponseContext frc = checkCollectionWritePreconditions(request);
    if (frc != null)
        return frc;

    try {
        CollectionItem content = readCollection(request);

        CollectionItem collection = getEntityFactory().createCollection();
        collection.setUid(content.getUid());
        collection.setName(collection.getUid());
        collection.setDisplayName(content.getDisplayName());
        collection.setOwner(user);

        CalendarCollectionStamp stamp = getEntityFactory().createCalendarCollectionStamp(collection);

        stamp.setDescription(collection.getDisplayName());
        // XXX set the calendar language from Content-Language
        collection.addStamp(stamp);

        collection = contentService.createCollection(home, collection);

        ServiceLocator locator = createServiceLocator(request);

        return created(collection, locator);
    } catch (IOException e) {
        String reason = "Unable to read request content: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (ValidationException e) {
        String msg = "Invalid request content: " + e.getMessage();
        if (e.getCause() != null)
            msg += ": " + e.getCause().getMessage();
        return ProviderHelper.badrequest(request, msg);
    } catch (UidInUseException e) {
        return ProviderHelper.conflict(request, "Uid already in use");
    } catch (CollectionLockedException e) {
        return locked(request);
    } catch (CosmoSecurityException e) {
        if (e instanceof ItemSecurityException)
            return insufficientPrivileges(request,
                    new InsufficientPrivilegesException((ItemSecurityException) e));
        else
            return ProviderHelper.forbidden(request, e.getMessage());
    }
}

From source file:org.pentaho.big.data.impl.shim.mapreduce.PentahoMapReduceJobBuilderImplTest.java

@Test(expected = IOException.class)
public void testSubmitNoPmrArchive() throws IOException, ConfigurationException, URISyntaxException {
    Configuration conf = mock(Configuration.class);
    FileSystem fileSystem = mock(FileSystem.class);
    DistributedCacheUtil distributedCacheUtil = mock(DistributedCacheUtil.class);
    Path kettleEnvInstallDir = mock(Path.class);
    URI kettleEnvInstallDirUri = new URI("http://testUri/path");
    when(kettleEnvInstallDir.toUri()).thenReturn(kettleEnvInstallDirUri);

    when(hadoopShim.getFileSystem(conf)).thenReturn(fileSystem);
    when(hadoopShim.getDistributedCacheUtil()).thenReturn(distributedCacheUtil);
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_USE_DISTRIBUTED_CACHE))
            .thenReturn("true");
    String installPath = "/path" + Const.FILE_SEPARATOR;
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_KETTLE_HDFS_INSTALL_DIR))
            .thenReturn(installPath);//from w w w . ja v a 2 s.  c o  m
    String installId = "install_id";
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_KETTLE_INSTALLATION_ID))
            .thenReturn(installId);
    when(fileSystem.asPath(installPath, installId)).thenReturn(kettleEnvInstallDir);
    when(distributedCacheUtil.isKettleEnvironmentInstalledAt(fileSystem, kettleEnvInstallDir))
            .thenReturn(false);
    String mapreduceClasspath = "mapreduceClasspath";
    when(conf.get(PentahoMapReduceJobBuilderImpl.MAPREDUCE_APPLICATION_CLASSPATH,
            PentahoMapReduceJobBuilderImpl.DEFAULT_MAPREDUCE_APPLICATION_CLASSPATH))
                    .thenReturn(mapreduceClasspath);
    String archiveName = "archiveName";
    when(pmrArchiveGetter.getVfsFilename(conf)).thenReturn(archiveName);

    try {
        pentahoMapReduceJobBuilder.submit(conf);
    } catch (IOException e) {
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_INSTALLATION_OF_KETTLE_FAILED),
                e.getMessage());
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_UNABLE_TO_LOCATE_ARCHIVE,
                archiveName).trim(), e.getCause().getMessage().trim());
        throw e;
    }
}

From source file:org.pentaho.big.data.impl.shim.mapreduce.PentahoMapReduceJobBuilderImplTest.java

@Test(expected = IOException.class)
public void testSubmitInstallFail()
        throws URISyntaxException, IOException, ConfigurationException, KettleFileException {
    Configuration conf = mock(Configuration.class);
    FileSystem fileSystem = mock(FileSystem.class);
    DistributedCacheUtil distributedCacheUtil = mock(DistributedCacheUtil.class);
    Path kettleEnvInstallDir = mock(Path.class);
    URI kettleEnvInstallDirUri = new URI("http://testUri/path");
    when(kettleEnvInstallDir.toUri()).thenReturn(kettleEnvInstallDirUri);

    when(hadoopShim.getFileSystem(conf)).thenReturn(fileSystem);
    when(hadoopShim.getDistributedCacheUtil()).thenReturn(distributedCacheUtil);
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_USE_DISTRIBUTED_CACHE))
            .thenReturn("true");
    String installPath = "/path";
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_KETTLE_HDFS_INSTALL_DIR))
            .thenReturn(installPath);/*from   w  w w.j av  a 2 s  . co m*/
    installPath += Const.FILE_SEPARATOR;
    String installId = "install_id";
    when(conf.get(PentahoMapReduceJobBuilderImpl.PENTAHO_MAPREDUCE_PROPERTY_KETTLE_INSTALLATION_ID))
            .thenReturn(installId);
    when(fileSystem.asPath(installPath, installId)).thenReturn(kettleEnvInstallDir);
    when(distributedCacheUtil.isKettleEnvironmentInstalledAt(fileSystem, kettleEnvInstallDir))
            .thenReturn(false);
    String mapreduceClasspath = "mapreduceClasspath";
    when(conf.get(PentahoMapReduceJobBuilderImpl.MAPREDUCE_APPLICATION_CLASSPATH,
            PentahoMapReduceJobBuilderImpl.DEFAULT_MAPREDUCE_APPLICATION_CLASSPATH))
                    .thenReturn(mapreduceClasspath);
    when(pmrArchiveGetter.getPmrArchive(conf)).thenReturn(mock(FileObject.class));

    try {
        pentahoMapReduceJobBuilder.submit(conf);
    } catch (IOException e) {
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_INSTALLATION_OF_KETTLE_FAILED),
                e.getMessage());
        assertEquals(BaseMessages.getString(PentahoMapReduceJobBuilderImpl.PKG,
                PentahoMapReduceJobBuilderImpl.JOB_ENTRY_HADOOP_TRANS_JOB_EXECUTOR_KETTLE_INSTALLATION_MISSING_FROM,
                kettleEnvInstallDirUri.getPath()).trim(), e.getCause().getMessage().trim());
        throw e;
    }
}

From source file:com.redhat.rhn.manager.kickstart.cobbler.CobblerPowerSettingsUpdateCommand.java

/**
 * Updates a server's power settings. Creates a Cobbler system profile if it
 * does not exist.//from  w  w w . j a va2 s. c  o  m
 * @return any errors
 */
@Override
public ValidatorError store() {
    Long sid = server.getId();
    SystemRecord systemRecord = getSystemRecordForSystem();

    if (systemRecord == null) {
        log.debug("No Cobbler system record found for system " + sid);
        try {
            CobblerConnection connection = getCobblerConnection();
            Image image = createDummyImage(connection);
            systemRecord = SystemRecord.create(connection,
                    CobblerSystemCreateCommand.getCobblerSystemRecordName(server), image);
            systemRecord.enableNetboot(false);
            server.setCobblerId(systemRecord.getId());
        } catch (IOException e) {
            log.error("Could not create temporary file for Cobbler image");
            return new ValidatorError("kickstart.powermanagement.cannot_create_file");
        }
    }

    try {
        log.debug("Setting Cobbler parameters for system " + sid);
        if (powerType != null && !powerType.equals("") && !powerType.equals(systemRecord.getPowerType())) {
            systemRecord.setPowerType(powerType);
        }
        if (powerAddress != null && !powerAddress.equals(systemRecord.getPowerAddress())) {
            systemRecord.setPowerAddress(powerAddress);
        }
        if (powerUsername != null && !powerUsername.equals(systemRecord.getPowerUsername())) {
            systemRecord.setPowerUsername(powerUsername);
        }
        if (powerPassword != null && !powerPassword.equals(systemRecord.getPowerPassword())) {
            systemRecord.setPowerPassword(powerPassword);
        }
        if (powerId != null && !powerId.equals(systemRecord.getPowerId())) {
            systemRecord.setPowerId(powerId);
        }
        systemRecord.save();
        log.debug("Settings saved for system " + sid);
    } catch (XmlRpcException e) {
        Throwable cause = e.getCause();
        if (cause != null) {
            String message = cause.getMessage();
            if (message != null && message.contains("power type must be one of")) {
                log.error("Unsupported Cobbler power type " + powerType);
                return new ValidatorError("kickstart.powermanagement.unsupported_power_type");
            }
            if (message != null && message.contains("Invalid characters found in input")) {
                log.error(message);
                return new ValidatorError("kickstart.powermanagement.invalid_chars");
            }
        }
        throw e;
    }

    return null;
}

From source file:com.spectralogic.ds3client.integration.GetJobManagement_Test.java

@Test
public void testReadRetrybugWhenChannelThrowsAccessException() throws IOException, URISyntaxException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    final String tempPathPrefix = null;
    final Path tempDirectoryPath = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final AtomicBoolean caughtException = new AtomicBoolean(false);

    try {/*from  w w  w . jav a  2 s.c  o m*/
        final String DIR_NAME = "largeFiles/";
        final String FILE_NAME = "lesmis-copies.txt";

        final Path objPath = ResourceUtils.loadFileResource(DIR_NAME + FILE_NAME);
        final long bookSize = Files.size(objPath);
        final Ds3Object obj = new Ds3Object(FILE_NAME, bookSize);

        final Ds3ClientShim ds3ClientShim = new Ds3ClientShim((Ds3ClientImpl) client);

        final int maxNumBlockAllocationRetries = 1;
        final int maxNumObjectTransferAttempts = 3;
        final Ds3ClientHelpers ds3ClientHelpers = Ds3ClientHelpers.wrap(ds3ClientShim,
                maxNumBlockAllocationRetries, maxNumObjectTransferAttempts);

        final Ds3ClientHelpers.Job readJob = ds3ClientHelpers.startReadJob(BUCKET_NAME, Arrays.asList(obj));

        final GetJobSpectraS3Response jobSpectraS3Response = ds3ClientShim
                .getJobSpectraS3(new GetJobSpectraS3Request(readJob.getJobId()));

        assertThat(jobSpectraS3Response.getMasterObjectListResult(), is(notNullValue()));

        readJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() {
            @Override
            public SeekableByteChannel buildChannel(final String key) throws IOException {
                throw new AccessControlException(key);
            }
        });
    } catch (final IOException e) {
        caughtException.set(true);
        assertTrue(e.getCause() instanceof AccessControlException);
    } finally {
        FileUtils.deleteDirectory(tempDirectoryPath.toFile());
    }

    assertTrue(caughtException.get());
}

From source file:org.osaf.cosmo.atom.provider.ItemCollectionAdapter.java

@Override
public ResponseContext putMedia(RequestContext request) {
    ItemTarget target = (ItemTarget) request.getTarget();
    NoteItem item = target.getItem();/*from w  w  w  .  j  av  a  2 s. c om*/
    if (log.isDebugEnabled())
        log.debug("updating media for item " + item.getUid());

    ResponseContext frc = checkMediaWritePreconditions(request);
    if (frc != null)
        return frc;

    try {
        ContentProcessor processor = createContentProcessor(request.getContentType().toString());
        processor.processContent(request.getReader(), item);
        item = (NoteItem) contentService.updateContent((ContentItem) item);

        return updated(item);
    } catch (IOException e) {
        String reason = "Unable to read request content: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (UnsupportedContentTypeException e) {
        return ProviderHelper.notsupported(request, "Unsupported media type " + e.getContentType());
    } catch (ValidationException e) {
        String reason = "Invalid content: ";
        if (e.getCause() != null)
            reason = reason + e.getCause().getMessage();
        else
            reason = reason + e.getMessage();
        return ProviderHelper.badrequest(request, reason);
    } catch (ProcessorException e) {
        String reason = "Unknown content processing error: " + e.getMessage();
        log.error(reason, e);
        return ProviderHelper.servererror(request, reason, e);
    } catch (CollectionLockedException e) {
        return locked(request);
    } catch (CosmoSecurityException e) {
        if (e instanceof ItemSecurityException)
            return insufficientPrivileges(request,
                    new InsufficientPrivilegesException((ItemSecurityException) e));
        else
            return ProviderHelper.forbidden(request, e.getMessage());
    }
}

From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java

/**
 * Add staff details in to system./*from   w  w w  .j  a v  a  2 s . co m*/
 * 
 * @param staff - {@link Staff}
 * @param bindingResult - {@link BindingResult}
 * @param model - {@link ModelMap}
 * @param request - {@link HttpServletRequest}
 * @return view of the student details.
 * @throws AkuraAppException - throw detailed exception.
 */
@RequestMapping(value = REQ_MAP_VALUE_SAVE)
public String saveStaffDetails(@ModelAttribute(MODEL_ATT_STAFF) Staff staff, BindingResult bindingResult,
        ModelMap model, HttpServletRequest request) throws AkuraAppException {

    String selectedCountryCodeRes = request.getParameter(SELECTED_COUNTRYCODE_RES);
    String selectedCountryCodeMob = request.getParameter(SELECTED_COUNTRYCODE_MOB);
    String selectedCountryCodeEmgRes = request.getParameter(SELECTED_COUNTRYCODE_EMG_RES);
    String selectedCountryCodeEmgMob = request.getParameter(SELECTED_COUNTRYCODE_EMG_MOB);

    if (request.getMethod().equals(REQUEST_METHOD)) {
        return VIEW_GET_STAFF;
    }

    staffDetailsValidator.validate(staff, bindingResult);
    if (bindingResult.hasErrors()) {
        handleValidationError(staff, model);
        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                selectedCountryCodeEmgMob, model);
        return VIEW_GET_STAFF;
    }
    checkEmailExistOrNot(staff, bindingResult);
    if (bindingResult.hasErrors()) {
        handleValidationError(staff, model);
        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                selectedCountryCodeEmgMob, model);
        return VIEW_GET_STAFF;
    }

    if (!staff.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
        if (staff.getResidenceNo() != null && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                && PhoneNumberValidateUtil.isValidPhoneNumber(staff.getResidenceNo(), selectedCountryCodeRes)) {
            displayResidencePhoneNumberDetails(staff, selectedCountryCodeRes);
        } else {
            displayCountryFlagsWhenError(staff, model, selectedCountryCodeRes, selectedCountryCodeMob,
                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob);
            return VIEW_GET_STAFF;
        }
    }

    if (!staff.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
        if (staff.getMobileNo() != null && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                && PhoneNumberValidateUtil.isValidPhoneNumber(staff.getMobileNo(), selectedCountryCodeMob)) {
            displayMobilePhoneNumberDetails(staff, selectedCountryCodeMob);
        } else {
            displayCountryFlagsWhenError(staff, model, selectedCountryCodeRes, selectedCountryCodeMob,
                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob);
            return VIEW_GET_STAFF;
        }
    }

    if (!staff.getEmergencyContactResidenceNo().isEmpty() && !selectedCountryCodeEmgRes.isEmpty()) {
        if (staff.getEmergencyContactResidenceNo() != null
                && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                && PhoneNumberValidateUtil.isValidPhoneNumber(staff.getEmergencyContactResidenceNo(),
                        selectedCountryCodeEmgRes)) {
            displayEmgResidencePhoneNumberDetails(staff, selectedCountryCodeEmgRes);
        } else {
            displayCountryFlagsWhenError(staff, model, selectedCountryCodeRes, selectedCountryCodeMob,
                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob);
            return VIEW_GET_STAFF;
        }
    }

    if (!staff.getEmergencyContactMobileNo().isEmpty() && !selectedCountryCodeEmgMob.isEmpty()) {
        if (staff.getEmergencyContactMobileNo() != null
                && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO) && PhoneNumberValidateUtil
                        .isValidPhoneNumber(staff.getEmergencyContactMobileNo(), selectedCountryCodeEmgMob)) {
            displayEmgMobilePhoneNumberDetails(staff, selectedCountryCodeEmgMob);
        } else {
            displayCountryFlagsWhenError(staff, model, selectedCountryCodeRes, selectedCountryCodeMob,
                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob);
            return VIEW_GET_STAFF;
        }
    }

    if (staff.getRegistrationNo() != null) {
        staff.setRegistrationNo(staff.getRegistrationNo().trim());
    }
    boolean isAcademicCategory = validateCoreSubject(staff, bindingResult);
    if (bindingResult.hasErrors()) {
        handleValidationError(staff, model);
        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                selectedCountryCodeEmgMob, model);
        return VIEW_GET_STAFF;
    } else {
        boolean isNew = false;

        try {
            if (!isAcademicCategory) {

                staff.setCoreSubject(null);
                staff.setStudyMedium(null);
            }

            int maxStaffId = staffService.getMaxStaffId();
            if (maxStaffId < staff.getStaffId()) {
                uploadImage(staff);
                staffService.addStaff(staff);
                String message = new ErrorMsgLoader().getErrorMessage(MESSAGE_RECORD_ADDED);
                model.addAttribute(MESSAGE, message);

            } else if (staff.getStaffId() == 0) {
                isNew = true;
                uploadImage(staff);
                staffService.addStaff(staff);
                String message = new ErrorMsgLoader().getErrorMessage(MESSAGE_RECORD_ADDED);
                model.addAttribute(MESSAGE, message);
            } else {
                return updateStaffDetails(staff, model, request);
            }
        } catch (IOException e) {
            LOG.error(ERROR_RETRIEVING_FILE + e.toString());
            throw new AkuraAppException(AkuraConstant.FILE_NOT_FOUND, e);
        } catch (AkuraAppException e) {
            if (e.getCause() instanceof TransientDataAccessResourceException) {
                handleTransientDataAccessResourceException(staff, bindingResult, model, isNew);
                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                        selectedCountryCodeEmgMob, model);
                return VIEW_GET_STAFF;
            }
            if (e.getCause() instanceof DataIntegrityViolationException) {
                handleDataIntegrityViolation(staff, bindingResult, model, isNew);
                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                        selectedCountryCodeEmgMob, model);
                return VIEW_GET_STAFF;
            }
        }
    }
    return showStaffDetailsForm(request, model);
}