Example usage for java.util.concurrent.locks Lock lock

List of usage examples for java.util.concurrent.locks Lock lock

Introduction

In this page you can find the example usage for java.util.concurrent.locks Lock lock.

Prototype

lock

Source Link

Usage

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for setup a schema namespace (indexes)
 *
 * @param ns: namespace name/*  w  ww.j a  va  2 s  . c om*/
 * @return 200 response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/setup_schema")
public Response setupSchema(@PathParam("ns") String ns) {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);
        try (Transaction tx = graphDB.beginTx()) {
            app.setupSchema();
            tx.success();
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.OK).build();
}

From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java

/**
 * <p>Tests a failed asynchronous request where the implementation of the 
 * {@link AsyncHandler#onFailure(HttpResponse)} callback throws an exception.</p>
 *  /* w  w w  .  j a v a  2s.c  o  m*/
 * @since 1.3.0
 */
@Test
public final void testAsyncFailureCallbackError() throws InterruptedException {

    String subpath = "/failurecallbackerror";

    stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(404)));

    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();

    asyncEndpoint.asyncFailureCallbackError(new AsyncHandler<String>() {

        @Override
        public void onSuccess(HttpResponse httpResponse, String e) {
        }

        @Override
        public void onFailure(HttpResponse httpResponse) {

            try {

                throw new IllegalStateException();
            } finally {

                lock.lock();
                condition.signal();
                lock.unlock();
            }
        }
    });

    lock.lock();
    condition.await();
    lock.unlock();

    verify(getRequestedFor(urlEqualTo(subpath)));

    successScenario(); //verify that the asynchronous request executor has survived the exception
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for importing data exported via export api. The importing does not setup all the indexes,
 * so user need run /reindex api after importing.
 *
 * @param ns:     namespace/* w  w  w .j  av a2 s .  com*/
 * @param stream: request body stream
 * @return 200 response if import success
 * @throws IOException
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/import")
public Response imports(@PathParam("ns") String ns, InputStream stream) throws IOException {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        final Application app = new Application(graphDB, ns);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
        try (BatchTransaction tx = new BatchTransaction(graphDB, 1000)) {
            DataImportExport importer = new DataImportExport(app, new Reporter() {
                @Override
                public void report() {
                    tx.increment();
                }
            });
            importer.importFrom(bufferedReader);
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.OK).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for adding multiple events./*from w w w .  ja va2  s .c o  m*/
 * Post events via request body in json format. e.g.
 *   [{
 *      "action_label":"do x",
 *      "start_at":1451956588844,
 *      "digest":"907e7d49",
 *      "anonymous_id":"9f0d0311",
 *      "session_id":"9f0d0311",
 *      "user":"johndoe@example.com",
 *      "properties":{
 *          "prop-a":"foo",
 *          "prop-b":"bar"
 *      }
 *    }]
 * @param ns: namespace under operation
 * @param eventsJSON: request body, json format, array event
 * @return 201 response
 * @throws IOException
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{ns}/add_events")
public Response addEvents(@PathParam("ns") String ns, String eventsJSON) throws IOException {

    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);

        List<Map> eventsAttrs = jsonToListMap(eventsJSON);
        try (Transaction tx = graphDB.beginTx()) {
            for (Map eventAttrs : eventsAttrs) {
                //noinspection unchecked
                app.events().add(eventAttrs);
            }
            tx.success();
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.CREATED).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for destroying all data under a namespace
 *
 * @param ns namespace name/*from   w w w .j a  v  a  2 s .  c om*/
 * @return 200 response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/destroy")
public Response destroy(@PathParam("ns") String ns) {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);
        try (Transaction tx = graphDB.beginTx()) {
            app.tearDownSchema();
            tx.success();
        }

        try (Transaction tx = graphDB.beginTx()) {
            app.journeys().tearDownLegacyIndex();
            tx.success();
        }

        app.destroyData();
    } finally {
        writingLock.unlock();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for identify a user and setup traits.
 * @param ns: namespace under operation// ww  w  .  j a  v  a2s . c om
 * @param uid: unique identify for the user
 * @param anonymousId: anonymous_id to associate existing anonymous events
 * @param traitsJSON: request body for traits for the user
 * @return 201 response
 * @throws IOException
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{ns}/identify")
public Response identify(@PathParam("ns") String ns, @QueryParam("uid") String uid,
        @QueryParam("anonymous_id") String anonymousId, String traitsJSON) throws IOException {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();

    try {
        Application app = new Application(graphDB, ns);
        Users users = app.users();

        try (Transaction tx = graphDB.beginTx()) {
            Node user = users.identify(uid, anonymousId);
            if (traitsJSON != null) {
                Map<String, Object> traits = jsonToMap(traitsJSON);
                for (String key : traits.keySet()) {
                    users.addTrait(user, key, traits.get(key));
                }
            }
            tx.success();
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.CREATED).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for run migrations under the namespace
 *
 * @param ns namespace name/*  w  w  w. ja  v  a  2  s  .c  o m*/
 * @return 200 response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/migrate")
public Response migrate(@PathParam("ns") String ns) {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);
        ArrayList<Long> ids = new ArrayList<>();
        try (Transaction ignored = graphDB.beginTx()) {
            ResourceIterator<Node> nodes = graphDB.findNodes(app.journeys().getLabel());
            while (nodes.hasNext()) {
                Node node = nodes.next();
                ids.add(node.getId());
            }
        }

        try (BatchTransaction tx = new BatchTransaction(graphDB, 5000)) {
            for (Long id : ids) {
                Node journey = graphDB.getNodeById(id);
                if (!journey.hasProperty(Journeys.PROP_LENGTH)) {
                    Integer length = journey.getDegree(RelTypes.BELONGS_TO, Direction.INCOMING);
                    journey.setProperty(Journeys.PROP_LENGTH, length);
                    Index<Node> index = GraphDbUtils.legacyIndex(graphDB, app.journeys().getLabel());
                    index.add(journey, Journeys.PROP_LENGTH, new ValueContext(length).indexNumeric());
                }
                tx.increment();
            }
        }
    } finally {
        writingLock.unlock();
    }
    return Response.status(Response.Status.OK).build();
}

From source file:com.thoughtworks.studios.journey.JourneyService.java

/**
 * API for reindex journeys.//w  w w . j av a 2  s . c  om
 *
 * @param ns namespace under operation
 * @return 200 response
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
@Path("/{ns}/reindex")
public Response reindex(@PathParam("ns") String ns) {
    Lock writingLock = getWritingLock(ns);
    writingLock.lock();
    try {
        Application app = new Application(graphDB, ns);
        try (Transaction tx = graphDB.beginTx()) {
            app.journeys().tearDownLegacyIndex();
            tx.success();
        }

        ArrayList<Long> ids = new ArrayList<>();
        try (Transaction tx = graphDB.beginTx()) {
            ResourceIterator<Node> journeys = graphDB.findNodes(app.journeys().getLabel());
            while (journeys.hasNext()) {
                ids.add(journeys.next().getId());
            }
            tx.success();
        }

        try (BatchTransaction tx = new BatchTransaction(graphDB, 100)) {
            for (Long id : ids) {
                Node journey = graphDB.getNodeById(id);
                app.journeys().reindex(journey);
                tx.increment();
            }
        }
    } finally {
        writingLock.unlock();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java

/**
 * Initializes the cache. Only the cache specific to the sesison's locale
 * will be populated.//from ww w  .  ja va2  s.c  o  m
 */
protected void initCache(IPentahoSession session) {

    final List<Catalog> cache = getCache(session);

    final boolean needUpdate;
    final Lock readLock = cacheLock.readLock();

    try {
        readLock.lock();
        // Check if the cache is empty.
        if (cache.size() == 0) {
            needUpdate = true;
        } else {
            needUpdate = false;
        }
    } finally {
        readLock.unlock();
    }

    if (needUpdate) {
        final Lock writeLock = cacheLock.writeLock();
        try {
            writeLock.lock();

            // First clear the cache
            cache.clear();

            final Callable<Void> call = new Callable<Void>() {
                public Void call() throws Exception {
                    // Now build the cache. Use the system session in the holder.
                    for (String name : getHelper().getHostedCatalogs()) {
                        try {
                            addCatalogToCache(PentahoSessionHolder.getSession(), name);
                        } catch (Throwable t) {
                            LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                        }
                    }
                    for (String name : getHelper().getOlap4jServers()) {
                        try {
                            addCatalogToCache(PentahoSessionHolder.getSession(), name);
                        } catch (Throwable t) {
                            LOG.error("Failed to initialize the cache for OLAP connection " + name, t);
                        }
                    }
                    return null;
                }
            };

            if (isSecurityEnabled()) {
                SecurityHelper.getInstance().runAsSystem(call);
            } else {
                call.call();
            }

            // Sort it all.
            Collections.sort(cache, new Comparator<IOlapService.Catalog>() {
                public int compare(Catalog o1, Catalog o2) {
                    return o1.name.compareTo(o2.name);
                }
            });

        } catch (Throwable t) {

            LOG.error("Failed to initialize the connection cache", t);

            throw new IOlapServiceException(t);

        } finally {
            writeLock.unlock();
        }
    }
}

From source file:com.haulmont.cuba.web.security.idp.BaseIdpSessionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // send static files without authentication
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (StringUtils.startsWith(httpRequest.getRequestURI(), httpRequest.getContextPath() + "/VAADIN/")) {
        chain.doFilter(request, response);
        return;/*from w w  w  . ja v  a 2 s. com*/
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (Strings.isNullOrEmpty(idpBaseURL)) {
        log.error("Application property cuba.web.idp.url is not set");
        httpResponse.setStatus(500);
        return;
    }

    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }

    String requestUrl = httpRequest.getRequestURL().toString();
    if (StringUtils.startsWith(requestUrl, idpBaseURL)) {
        chain.doFilter(httpRequest, response);
        return;
    }

    HttpSession session = httpRequest.getSession(true);
    Lock sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    if (sessionLock == null) {
        sessionCheckLock.lock();
        try {
            sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
            if (sessionLock == null) {
                sessionLock = new ReentrantLock();
                session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            }
        } finally {
            sessionCheckLock.unlock();
        }
    }

    IdpSession boundIdpSession;
    sessionLock.lock();

    try {
        session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    } catch (IllegalStateException e) {
        // Someone might have invalidated the session between fetching the lock and acquiring it.
        sessionLock.unlock();

        log.debug("Invalidated session {}", session.getId());
        httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
        return;
    }

    try {
        if ("GET".equals(httpRequest.getMethod())
                && httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM) != null) {
            String idpTicket = httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM);

            IdpSession idpSession;
            try {
                idpSession = getIdpSession(idpTicket);
            } catch (IdpActivationException e) {
                log.error("Unable to obtain IDP session by ticket", e);
                httpResponse.setStatus(500);
                return;
            }

            if (idpSession == null) {
                log.warn("Used old IDP ticket {}, send redirect", idpTicket);
                // used old ticket, send redirect
                httpResponse.sendRedirect(getIdpRedirectUrl());
                return;
            }

            session.invalidate();

            session = httpRequest.getSession(true);
            session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            session.setAttribute(IDP_SESSION_ATTRIBUTE, idpSession);

            log.debug("IDP session {} obtained, redirect to application", idpSession);

            // redirect to application without parameters
            httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
            return;
        }

        if (session.getAttribute(IDP_SESSION_ATTRIBUTE) == null) {
            if ("GET".equals(httpRequest.getMethod()) && !StringUtils.startsWith(httpRequest.getRequestURI(),
                    httpRequest.getContextPath() + "/PUSH")) {
                httpResponse.sendRedirect(getIdpRedirectUrl());
            }
            return;
        }

        boundIdpSession = (IdpSession) session.getAttribute(IDP_SESSION_ATTRIBUTE);
    } finally {
        sessionLock.unlock();
    }

    HttpServletRequest authenticatedRequest = new IdpServletRequestWrapper(httpRequest,
            new IdpSessionPrincipalImpl(boundIdpSession));

    chain.doFilter(authenticatedRequest, response);
}