Example usage for java.util ConcurrentModificationException ConcurrentModificationException

List of usage examples for java.util ConcurrentModificationException ConcurrentModificationException

Introduction

In this page you can find the example usage for java.util ConcurrentModificationException ConcurrentModificationException.

Prototype

public ConcurrentModificationException(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.wooki.domain.biz.ChapterManagerImpl.java

public void updateContent(Long chapterId, Draft draft) {

    assert chapterId != null;
    assert draft != null;
    assert draft.getData() != null;

    // Update last modified timestamp
    Date lastModified = Calendar.getInstance().getTime();
    ReentrantLock lock = getOrCreateLock(chapterId);

    Publication publication = publicationDao.findLastRevision(chapterId);
    lock.lock();//from  w  w  w .  j  ava  2 s.c  o  m

    Chapter chapter = null;

    try {
        chapter = chapterDao.findById(chapterId);
        if (chapter.getLastModified() != null && !chapter.getLastModified().equals(draft.getTimestamp())) {
            throw new ConcurrentModificationException(
                    "Document has been modified by another user in the meantime.");
        }
        chapter.setLastModified(lastModified);
        chapterDao.update(chapter);
    } finally {
        lock.unlock();
    }

    // we check the published flag. If set, then this Publication must
    // be considered as "locked" and we must create a new publication as
    // the new working copy
    if (publication == null || (publication != null && publication.isPublished())) {
        publication = new Publication();

        // Security check
        if (!securityCtx.isLoggedIn() || !this.securityCtx.canWrite(chapter.getBook())) {
            throw new AuthorizationException("Publish action not authorized");
        }
        publication.setChapter(chapter);

        publication.setCreationDate(Calendar.getInstance().getTime());
        publicationDao.create(publication);
    }

    publication.setContent(draft.getData());
    publication.setLastModified(lastModified);
    publicationDao.update(publication);

}

From source file:com.examples.with.different.packagename.concolic.MathRuntimeException.java

/**
 * Constructs a new <code>ConcurrentModificationException</code> with specified formatted detail message.
 * Message formatting is delegated to {@link java.text.MessageFormat}.
 * @param pattern format specifier/* w w  w.j  a  v  a 2s  .c  o  m*/
 * @param arguments format arguments
 * @return built exception
 */
public static ConcurrentModificationException createConcurrentModificationException(final String pattern,
        final Object... arguments) {
    return new ConcurrentModificationException(buildMessage(Locale.US, pattern, arguments)) {

        /** Serializable version identifier. */
        private static final long serialVersionUID = 6134247282754009421L;

        /** {@inheritDoc} */
        @Override
        public String getLocalizedMessage() {
            return buildMessage(Locale.getDefault(), pattern, arguments);
        }

    };
}

From source file:com.microsoft.tfs.client.common.repository.RepositoryManager.java

public final TFSRepository getOrCreateRepository(final Workspace workspace,
        final RepositoryStatusContainer statusContainer) {
    Check.notNull(workspace, "workspace"); //$NON-NLS-1$

    final WorkspaceKey key = new WorkspaceKey(workspace);
    TFSRepository repository;/*from  ww  w  .  j a  va  2 s.c  om*/

    synchronized (lock) {
        if ((repository = repositoryMap.get(key)) != null) {
            if (statusContainer != null) {
                statusContainer.setRepositoryStatus(RepositoryStatus.EXISTING);
            }

            return repository;
        }

        repository = new TFSRepository(workspace);

        final RepositoryReplaceResults results;
        try {
            results = replaceRepositoryInternal(repository);
        } catch (final RepositoryConflictException e) {
            // Ensure the repository we created gets closed
            repository.close();
            throw e;
        }

        if (results.isIdenticalRepository()) {
            /*
             * Can't happen unless code erroneously adds a repository
             * without locking
             */
            throw new ConcurrentModificationException("The RepositoryManager was modified outside of a lock"); //$NON-NLS-1$
        }
    }

    getListener().onRepositoryAdded(new RepositoryManagerEvent(this, repository));

    if (statusContainer != null) {
        statusContainer.setRepositoryStatus(RepositoryStatus.CREATED);
    }

    return repository;
}

From source file:org.apache.olingo.fit.AbstractServices.java

@PATCH
@Path("/{entitySetName}({entityId})")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
public Response patchEntity(@Context final UriInfo uriInfo,
        @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
        @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer,
        @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) final String ifMatch,
        @PathParam("entitySetName") final String entitySetName, @PathParam("entityId") final String entityId,
        final String changes) {

    try {/*from  w ww . ja  va2s.  co m*/
        final Accept acceptType = Accept.parse(accept, version);

        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final Map.Entry<String, InputStream> entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM);

        final String etag = Commons.getETag(entityInfo.getKey(), version);
        if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
            throw new ConcurrentModificationException("Concurrent modification");
        }

        final Accept contentTypeValue = Accept.parse(contentType, version);

        final Entity entryChanges;

        if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        } else if (contentTypeValue == Accept.ATOM) {
            entryChanges = atomDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING))
                    .getPayload();
        } else {
            final ResWrap<Entity> jcont = jsonDeserializer
                    .toEntity(IOUtils.toInputStream(changes, Constants.ENCODING));
            entryChanges = jcont.getPayload();
        }

        final ResWrap<Entity> container = atomDeserializer.toEntity(entityInfo.getValue());

        for (Property property : entryChanges.getProperties()) {
            final Property _property = container.getPayload().getProperty(property.getName());
            if (_property == null) {
                container.getPayload().getProperties().add(property);
            } else {
                _property.setValue(property.getValueType(), property.getValue());
            }
        }

        for (Link link : entryChanges.getNavigationLinks()) {
            container.getPayload().getNavigationLinks().add(link);
        }

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, container);
        writer.flush();
        writer.close();

        final InputStream res = xml.addOrReplaceEntity(entityId, entitySetName,
                new ByteArrayInputStream(content.toByteArray()), container.getPayload());

        final ResWrap<Entity> cres = atomDeserializer.toEntity(res);

        normalizeAtomEntry(cres.getPayload(), entitySetName, entityId);

        final String path = Commons.getEntityBasePath(entitySetName, entityId);
        FSManager.instance(version).putInMemory(cres,
                path + File.separatorChar + Constants.get(version, ConstantKey.ENTITY));

        final Response response;
        if ("return-content".equalsIgnoreCase(prefer)) {
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(),
                    xml.readEntity(entitySetName, entityId, acceptType).getValue(), null, acceptType,
                    Response.Status.OK);
        } else {
            res.close();
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(), null, null, acceptType,
                    Response.Status.NO_CONTENT);
        }

        if (StringUtils.isNotBlank(prefer)) {
            response.getHeaders().put("Preference-Applied", Collections.<Object>singletonList(prefer));
        }

        return response;
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.AbstractUtilities.java

public InputStream patchEntity(final String entitySetName, final String entityId, final InputStream changes,
        final Accept accept, final String ifMatch) throws Exception {
    final Map.Entry<String, InputStream> entityInfo = readEntity(entitySetName, entityId, accept);

    final String etag = Commons.getETag(entityInfo.getKey(), version);
    if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
        throw new ConcurrentModificationException("Concurrent modification");
    }//from  w  ww .j  a v  a  2s  .c om

    final Map<String, InputStream> replacement = getChanges(changes);
    return addOrReplaceEntity(entityId, entitySetName, setChanges(entityInfo.getValue(), replacement));
}

From source file:org.auraframework.integration.test.service.ServerServiceImplTest.java

/**
 * Verifies second exception within handleServletException is caught and processed
 * we throw 'EmptyStackException' when getting InstanceStack, when
 * exceptionAdapter.handleException(death) handle the exception,
 * we throw second exception, then verify we printout the error message to response's writer
 *///w ww.j a  v a2s.  com
@Test
public void testHandleExceptionDoubleDeathCaught() throws Exception {
    PrintWriter writer = mock(PrintWriter.class);
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ContextService mockContextService = mock(ContextService.class);
    AuraContext mockContext = mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();
    String ccmeMsg = "double dead";
    Throwable secondException = new ConcurrentModificationException("double dead");

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.HTML);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.DEV);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(false);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException);
    Mockito.when(mockExceptionAdapter.handleException(firstException)).thenThrow(secondException);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = new ServletUtilAdapterImpl();
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setExceptionAdapter(mockExceptionAdapter);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    ArgumentCaptor<String> exceptionMessage = ArgumentCaptor.forClass(String.class);
    Mockito.verify(writer, Mockito.times(1)).println(exceptionMessage.capture());

    assertEquals(ccmeMsg, exceptionMessage.getValue());
    Mockito.verify(mockResponse, atLeastOnce()).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Mockito.verify(mockContextService, atLeastOnce()).endContext();
}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java

/**
 * Verifies second exception within handleServletException is caught and processed
 * we throw 'EmptyStackException' when getting InstanceStack, when
 * exceptionAdapter.handleException(death) handle the exception,
 * we throw second exception, then verify we printout the error message to response's writer
 *///from www . j  a  v a  2  s .  c om
@Test
public void testHandleExceptionDoubleDeathCaught() throws Exception {
    PrintWriter writer = Mockito.mock(PrintWriter.class);
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
    ContextService mockContextService = Mockito.mock(ContextService.class);
    AuraContext mockContext = Mockito.mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = Mockito.mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = Mockito.mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();
    String ccmeMsg = "double dead";
    Throwable secondException = new ConcurrentModificationException("double dead");

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.HTML);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.DEV);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(false);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException);
    Mockito.when(mockExceptionAdapter.handleException(firstException)).thenThrow(secondException);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = Mockito.spy(new ServletUtilAdapterImpl());
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setExceptionAdapter(mockExceptionAdapter);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    ArgumentCaptor<String> exceptionMessage = ArgumentCaptor.forClass(String.class);
    Mockito.verify(writer, Mockito.times(1)).println(exceptionMessage.capture());

    assertEquals(ccmeMsg, exceptionMessage.getValue());
    // in this case we return SC_OK, and we set non-cacheable.
    Mockito.verify(mockResponse, Mockito.atLeastOnce()).setStatus(HttpStatus.SC_OK);
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
    Mockito.verify(adapter, Mockito.atLeastOnce()).setNoCache(mockResponse);
}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Store a triple in the database. This method assumes that all nodes used by the triple are already persisted.
 *
 * @param triple     the triple to store
 * @throws SQLException/*from w  w w  .j a  v a 2 s.  c  om*/
 * @throws NullPointerException in case the subject, predicate, object or context have not been persisted
 * @return true in case the update added a new triple to the database, false in case the triple already existed
 */
public synchronized void storeTriple(final KiWiTriple triple) throws SQLException {
    // mutual exclusion: prevent parallel adding and removing of the same triple
    synchronized (triple) {

        requireJDBCConnection();

        if (triple.getId() < 0) {
            triple.setId(getNextSequence());
        }

        if (deletedStatementsLog.mightContain(triple.getId())) {
            // this is a hack for a concurrency problem that may occur in case the triple is removed in the
            // transaction and then added again; in these cases the createStatement method might return
            // an expired state of the triple because it uses its own database connection

            //deletedStatementsLog.remove(triple.getId());
            undeleteTriple(triple);

        } else {

            if (batchCommit) {
                commitLock.lock();
                try {
                    cacheTriple(triple);
                    tripleBatch.add(triple);
                    if (tripleBatch.size() >= batchSize) {
                        flushBatch();
                    }
                } finally {
                    commitLock.unlock();
                }
            } else {
                Preconditions.checkNotNull(triple.getSubject().getId());
                Preconditions.checkNotNull(triple.getPredicate().getId());
                Preconditions.checkNotNull(triple.getObject().getId());

                try {
                    RetryExecution<Boolean> execution = new RetryExecution<>("STORE");
                    execution.setUseSavepoint(true);
                    execution.execute(connection, new RetryCommand<Boolean>() {
                        @Override
                        public Boolean run() throws SQLException {
                            PreparedStatement insertTriple = getPreparedStatement("store.triple");
                            insertTriple.setLong(1, triple.getId());
                            insertTriple.setLong(2, triple.getSubject().getId());
                            insertTriple.setLong(3, triple.getPredicate().getId());
                            insertTriple.setLong(4, triple.getObject().getId());
                            if (triple.getContext() != null) {
                                insertTriple.setLong(5, triple.getContext().getId());
                            } else {
                                insertTriple.setNull(5, Types.BIGINT);
                            }
                            insertTriple.setBoolean(6, triple.isInferred());
                            insertTriple.setTimestamp(7, new Timestamp(triple.getCreated().getTime()));
                            int count = insertTriple.executeUpdate();

                            cacheTriple(triple);

                            return count > 0;
                        }
                    });

                } catch (SQLException ex) {
                    if ("HYT00".equals(ex.getSQLState())) { // H2 table locking timeout
                        throw new ConcurrentModificationException(
                                "the same triple was modified in concurrent transactions (triple=" + triple
                                        + ")");
                    } else {
                        throw ex;
                    }
                }
            }
        }
    }
}

From source file:org.apache.olingo.fit.Services.java

private Response patchEntityInternal(final UriInfo uriInfo, final String accept, final String contentType,
        final String prefer, final String ifMatch, final String entitySetName, final String entityId,
        final String changes) {

    try {/*  w w w.  java  2s .  c  o m*/
        final Accept acceptType = Accept.parse(accept);

        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final Map.Entry<String, InputStream> entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM);

        final String etag = Commons.getETag(entityInfo.getKey());
        if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
            throw new ConcurrentModificationException("Concurrent modification");
        }

        final Accept contentTypeValue = Accept.parse(contentType);

        final Entity entryChanges;

        if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        } else if (contentTypeValue == Accept.ATOM) {
            entryChanges = atomDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING))
                    .getPayload();
        } else {
            final ResWrap<Entity> jcont = jsonDeserializer
                    .toEntity(IOUtils.toInputStream(changes, Constants.ENCODING));
            entryChanges = jcont.getPayload();
        }

        final ResWrap<Entity> container = atomDeserializer.toEntity(entityInfo.getValue());

        for (Property property : entryChanges.getProperties()) {
            final Property _property = container.getPayload().getProperty(property.getName());
            if (_property == null) {
                container.getPayload().getProperties().add(property);
            } else {
                _property.setValue(property.getValueType(), property.getValue());
            }
        }

        for (Link link : entryChanges.getNavigationLinks()) {
            container.getPayload().getNavigationLinks().add(link);
        }

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, container);
        writer.flush();
        writer.close();

        final InputStream res = xml.addOrReplaceEntity(entityId, entitySetName,
                new ByteArrayInputStream(content.toByteArray()), container.getPayload());

        final ResWrap<Entity> cres = atomDeserializer.toEntity(res);

        normalizeAtomEntry(cres.getPayload(), entitySetName, entityId);

        final String path = Commons.getEntityBasePath(entitySetName, entityId);
        FSManager.instance().putInMemory(cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY));

        final Response response;
        if ("return-content".equalsIgnoreCase(prefer)) {
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(),
                    xml.readEntity(entitySetName, entityId, acceptType).getValue(), null, acceptType,
                    Response.Status.OK);
        } else {
            res.close();
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(), null, null, acceptType,
                    Response.Status.NO_CONTENT);
        }

        if (StringUtils.isNotBlank(prefer)) {
            response.getHeaders().put("Preference-Applied", Collections.<Object>singletonList(prefer));
        }

        return response;
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

From source file:org.ow2.authzforce.pap.dao.flatfile.FlatFileBasedDomainsDAO.java

@Override
public String addDomain(final WritableDomainProperties props) throws IOException, IllegalArgumentException {
    final UUID uuid = uuidGen.generate();
    /*/*from   ww w.j a  va 2  s  .  c o m*/
     * Encode UUID with Base64url to have shorter IDs in REST API URL paths
     * and to be compatible with filenames on any operating system, since
     * the resulting domain ID is used as name for the directory where all
     * the domain's data will be stored.
     */
    final ByteBuffer byteBuf = ByteBuffer.wrap(new byte[16]);
    byteBuf.putLong(uuid.getMostSignificantBits());
    byteBuf.putLong(uuid.getLeastSignificantBits());
    final String domainId = FlatFileDAOUtils.base64UrlEncode(byteBuf.array());
    synchronized (domainsRootDir) {
        // this should not happen if the UUID generator can be trusted, but
        // - hey - we never
        // know.
        if (this.domainMap.containsKey(domainId)) {
            throw new ConcurrentModificationException(
                    "Generated domain ID conflicts (is same as) ID of existing domain (flawed domain UUID generator or ID generated in different way?): ID="
                            + domainId);
        }

        final Path domainDir = this.domainsRootDir.resolve(domainId);
        if (Files.notExists(domainDir)) {
            /*
             * Create/initialize new domain directory from domain template
             * directory
             */
            FlatFileDAOUtils.copyDirectory(this.domainTmplDirPath, domainDir, 3);
        }

        addDomainToCacheAfterDirectoryCreated(domainId, domainDir, props);
    }

    return domainId;
}