Example usage for java.lang InterruptedException getCause

List of usage examples for java.lang InterruptedException getCause

Introduction

In this page you can find the example usage for java.lang InterruptedException 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:com.couchbase.client.CouchbaseClient.java

/**
 * Set a value with durability options./*from www .j  av a  2 s  .  c  o  m*/
 *
 * To make sure that a value is stored the way you want it to in the
 * cluster, you can use the PersistTo and ReplicateTo arguments. The
 * operation will block until the desired state is satisfied or
 * otherwise an exception is raised. There are many reasons why this could
 * happen, the more frequent ones are as follows:
 *
 * - The given replication settings are invalid.
 * - The operation could not be completed within the timeout.
 * - Something goes wrong and a cluster failover is triggered.
 *
 * The client does not attempt to guarantee the given durability
 * constraints, it just reports whether the operation has been completed
 * or not. If it is not achieved, it is the responsibility of the
 * application code using this API to re-retrieve the items to verify
 * desired state, redo the operation or both.
 *
 * Note that even if an exception during the observation is raised,
 * this doesn't mean that the operation has failed. A normal set()
 * operation is initiated and after the OperationFuture has returned,
 * the key itself is observed with the given durability options (watch
 * out for Observed*Exceptions) in this case.
 *
 * @param key the key to store.
 * @param exp the expiry value to use.
 * @param value the value of the key.
 * @param req the amount of nodes the item should be persisted to before
 *            returning.
 * @param rep the amount of nodes the item should be replicated to before
 *            returning.
 * @return the future result of the set operation.
 */
public OperationFuture<Boolean> set(String key, int exp, Object value, PersistTo req, ReplicateTo rep) {

    OperationFuture<Boolean> setOp = set(key, exp, value);

    boolean setStatus = false;

    try {
        setStatus = setOp.get();
    } catch (InterruptedException e) {
        setOp.set(false, new OperationStatus(false, "Set get timed out"));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof CancellationException) {
            setOp.set(false, new OperationStatus(false, "Set get " + "cancellation exception "));
        } else {
            setOp.set(false, new OperationStatus(false, "Set get " + "execution exception "));
        }
    }
    if (!setStatus) {
        return setOp;
    }
    try {
        observePoll(key, setOp.getCas(), req, rep, false);
        setOp.set(true, setOp.getStatus());
    } catch (ObservedException e) {
        setOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedTimeoutException e) {
        setOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedModifiedException e) {
        setOp.set(false, new OperationStatus(false, e.getMessage()));
    }
    return setOp;
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
 * Add a value with durability options.//from   w w  w  .  j  a  v  a  2  s .  c  o m
 *
 * To make sure that a value is stored the way you want it to in the
 * cluster, you can use the PersistTo and ReplicateTo arguments. The
 * operation will block until the desired state is satisfied or
 * otherwise an exception is raised. There are many reasons why this could
 * happen, the more frequent ones are as follows:
 *
 * - The given replication settings are invalid.
 * - The operation could not be completed within the timeout.
 * - Something goes wrong and a cluster failover is triggered.
 *
 * The client does not attempt to guarantee the given durability
 * constraints, it just reports whether the operation has been completed
 * or not. If it is not achieved, it is the responsibility of the
 * application code using this API to re-retrieve the items to verify
 * desired state, redo the operation or both.
 *
 * Note that even if an exception during the observation is raised,
 * this doesn't mean that the operation has failed. A normal add()
 * operation is initiated and after the OperationFuture has returned,
 * the key itself is observed with the given durability options (watch
 * out for Observed*Exceptions) in this case.
 *
 * @param key the key to store.
 * @param exp the expiry value to use.
 * @param value the value of the key.
 * @param req the amount of nodes the item should be persisted to before
 *            returning.
 * @param rep the amount of nodes the item should be replicated to before
 *            returning.
 * @return the future result of the add operation.
 */
public OperationFuture<Boolean> add(String key, int exp, Object value, PersistTo req, ReplicateTo rep) {

    OperationFuture<Boolean> addOp = add(key, exp, value);

    boolean addStatus = false;

    try {
        addStatus = addOp.get();
    } catch (InterruptedException e) {
        addOp.set(false, new OperationStatus(false, "Add get timed out"));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof CancellationException) {
            addOp.set(false, new OperationStatus(false, "Add get " + "cancellation exception "));
        } else {
            addOp.set(false, new OperationStatus(false, "Add get " + "execution exception "));
        }
    }
    if (!addStatus) {
        return addOp;
    }
    try {
        observePoll(key, addOp.getCas(), req, rep, false);
        addOp.set(true, addOp.getStatus());
    } catch (ObservedException e) {
        addOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedTimeoutException e) {
        addOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedModifiedException e) {
        addOp.set(false, new OperationStatus(false, e.getMessage()));
    }
    return addOp;
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
 * Delete a value with durability options.
 *
 * The durability options here operate similarly to those documented in
 * the set method./*from  w  w w.j  a v a2  s. co  m*/
 *
 * @param key the key to set
 * @param req the Persistence to Master value
 * @param rep the Persistence to Replicas
 * @return whether or not the operation was performed
 */
public OperationFuture<Boolean> delete(String key, PersistTo req, ReplicateTo rep) {

    OperationFuture<Boolean> deleteOp = delete(key);
    boolean deleteStatus = false;

    try {
        deleteStatus = deleteOp.get();
    } catch (InterruptedException e) {
        deleteOp.set(false, new OperationStatus(false, "Delete get timed out"));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof CancellationException) {
            deleteOp.set(false, new OperationStatus(false, "Delete get " + "cancellation exception "));
        } else {
            deleteOp.set(false, new OperationStatus(false, "Delete get " + "execution exception "));
        }
    }
    if (!deleteStatus) {
        return deleteOp;
    }
    try {
        observePoll(key, deleteOp.getCas(), req, rep, true);
        deleteOp.set(true, deleteOp.getStatus());
    } catch (ObservedException e) {
        deleteOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedTimeoutException e) {
        deleteOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedModifiedException e) {
        deleteOp.set(false, new OperationStatus(false, e.getMessage()));
    }
    return deleteOp;
}

From source file:com.couchbase.client.CouchbaseClient.java

/**
 * Replace a value with durability options.
 *
 * To make sure that a value is stored the way you want it to in the
 * cluster, you can use the PersistTo and ReplicateTo arguments. The
 * operation will block until the desired state is satisfied or
 * otherwise an exception is raised. There are many reasons why this could
 * happen, the more frequent ones are as follows:
 *
 * - The given replication settings are invalid.
 * - The operation could not be completed within the timeout.
 * - Something goes wrong and a cluster failover is triggered.
 *
 * The client does not attempt to guarantee the given durability
 * constraints, it just reports whether the operation has been completed
 * or not. If it is not achieved, it is the responsibility of the
 * application code using this API to re-retrieve the items to verify
 * desired state, redo the operation or both.
 *
 * Note that even if an exception during the observation is raised,
 * this doesn't mean that the operation has failed. A normal replace()
 * operation is initiated and after the OperationFuture has returned,
 * the key itself is observed with the given durability options (watch
 * out for Observed*Exceptions) in this case.
 *
 * @param key the key to store.//from   w  w  w.  ja v a  2s.com
 * @param exp the expiry value to use.
 * @param value the value of the key.
 * @param req the amount of nodes the item should be persisted to before
 *            returning.
 * @param rep the amount of nodes the item should be replicated to before
 *            returning.
 * @return the future result of the replace operation.
 */
public OperationFuture<Boolean> replace(String key, int exp, Object value, PersistTo req, ReplicateTo rep) {

    OperationFuture<Boolean> replaceOp = replace(key, exp, value);

    boolean replaceStatus = false;

    try {
        replaceStatus = replaceOp.get();
    } catch (InterruptedException e) {
        replaceOp.set(false, new OperationStatus(false, "Replace get timed out"));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof CancellationException) {
            replaceOp.set(false, new OperationStatus(false, "Replace get " + "cancellation exception "));
        } else {
            replaceOp.set(false, new OperationStatus(false, "Replace get " + "execution exception "));
        }
    }
    if (!replaceStatus) {
        return replaceOp;
    }
    try {
        observePoll(key, replaceOp.getCas(), req, rep, false);
        replaceOp.set(true, replaceOp.getStatus());
    } catch (ObservedException e) {
        replaceOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedTimeoutException e) {
        replaceOp.set(false, new OperationStatus(false, e.getMessage()));
    } catch (ObservedModifiedException e) {
        replaceOp.set(false, new OperationStatus(false, e.getMessage()));
    }
    return replaceOp;

}

From source file:org.apache.manifoldcf.crawler.connectors.cmis.CmisRepositoryConnector.java

/** Set up a session */
protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (session == null) {
        // Check for parameter validity

        if (StringUtils.isEmpty(binding))
            throw new ManifoldCFException("Parameter " + CmisConfig.BINDING_PARAM + " required but not set");

        if (StringUtils.isEmpty(username))
            throw new ManifoldCFException("Parameter " + CmisConfig.USERNAME_PARAM + " required but not set");

        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("CMIS: Username = '" + username + "'");

        if (StringUtils.isEmpty(password))
            throw new ManifoldCFException("Parameter " + CmisConfig.PASSWORD_PARAM + " required but not set");

        Logging.connectors.debug("CMIS: Password exists");

        if (StringUtils.isEmpty(protocol))
            throw new ManifoldCFException("Parameter " + CmisConfig.PROTOCOL_PARAM + " required but not set");

        if (StringUtils.isEmpty(server))
            throw new ManifoldCFException("Parameter " + CmisConfig.SERVER_PARAM + " required but not set");

        if (StringUtils.isEmpty(port))
            throw new ManifoldCFException("Parameter " + CmisConfig.PORT_PARAM + " required but not set");

        if (StringUtils.isEmpty(path))
            throw new ManifoldCFException("Parameter " + CmisConfig.PATH_PARAM + " required but not set");

        long currentTime;
        GetSessionThread t = new GetSessionThread();
        try {//from w  w w  . j av  a2s  .co  m
            t.start();
            t.join();
            Throwable thr = t.getException();
            if (thr != null) {
                if (thr instanceof java.net.MalformedURLException)
                    throw (java.net.MalformedURLException) thr;
                else if (thr instanceof NotBoundException)
                    throw (NotBoundException) thr;
                else if (thr instanceof RemoteException)
                    throw (RemoteException) thr;
                else if (thr instanceof CmisConnectionException)
                    throw new ManifoldCFException(
                            "CMIS: Error during getting a new session: " + thr.getMessage(), thr);
                else if (thr instanceof CmisPermissionDeniedException)
                    throw new ManifoldCFException(
                            "CMIS: Wrong credentials during getting a new session: " + thr.getMessage(), thr);
                else
                    throw (Error) thr;
            }
        } catch (InterruptedException e) {
            t.interrupt();
            throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
        } catch (java.net.MalformedURLException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        } catch (NotBoundException e) {
            // Transient problem: Server not available at the moment.
            Logging.connectors.warn("CMIS: Server not up at the moment: " + e.getMessage(), e);
            currentTime = System.currentTimeMillis();
            throw new ServiceInterruption(e.getMessage(), currentTime + 60000L);
        } catch (RemoteException e) {
            Throwable e2 = e.getCause();
            if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
                throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
            // Treat this as a transient problem
            Logging.connectors.warn("CMIS: Transient remote exception creating session: " + e.getMessage(), e);
            currentTime = System.currentTimeMillis();
            throw new ServiceInterruption(e.getMessage(), currentTime + 60000L);
        }

    }

    lastSessionFetch = System.currentTimeMillis();
}

From source file:voldemort.store.routed.ThreadPoolRoutedStore.java

private <R> List<R> get(final ByteArray key, final byte[] transforms, StoreOp<R> fetcher,
        Function<List<GetResult<R>>, Void> preReturnProcedure) throws VoldemortException {
    StoreUtils.assertValidKey(key);/*www . j  a v a 2 s . com*/
    final List<Node> nodes = availableNodes(routingStrategy.routeRequest(key.get()));

    // quickly fail if there aren't enough nodes to meet the requirement
    checkRequiredReads(nodes);

    final List<GetResult<R>> retrieved = Lists.newArrayList();

    // A count of the number of successful operations
    int successes = 0;
    // A list of thrown exceptions, indicating the number of failures
    final List<Throwable> failures = Lists.newArrayListWithCapacity(3);

    // Do the preferred number of reads in parallel
    int attempts = Math.min(this.storeDef.getPreferredReads(), nodes.size());
    int nodeIndex = 0;
    List<Callable<GetResult<R>>> callables = Lists.newArrayListWithCapacity(attempts);
    for (; nodeIndex < attempts; nodeIndex++) {
        final Node node = nodes.get(nodeIndex);
        callables.add(new GetCallable<R>(node, key, transforms, fetcher));
    }

    List<Future<GetResult<R>>> futures;
    long timeoutMs = (fetcher == VERSION_OP)
            ? timeoutConfig.getOperationTimeout(VoldemortOpCode.GET_VERSION_OP_CODE)
            : timeoutConfig.getOperationTimeout(VoldemortOpCode.GET_OP_CODE);
    try {
        futures = executor.invokeAll(callables, timeoutMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new InsufficientOperationalNodesException("Get operation interrupted!", e);
    }

    for (Future<GetResult<R>> f : futures) {
        if (f.isCancelled()) {
            logger.warn("Get operation timed out after " + timeoutMs + " ms.");
            continue;
        }
        try {
            GetResult<R> getResult = f.get();
            if (getResult.exception != null) {
                if (getResult.exception instanceof VoldemortApplicationException) {
                    throw (VoldemortException) getResult.exception;
                }
                failures.add(getResult.exception);
                continue;
            }
            ++successes;
            retrieved.add(getResult);
        } catch (InterruptedException e) {
            throw new InsufficientOperationalNodesException("Get operation interrupted!", e);
        } catch (ExecutionException e) {
            // We catch all Throwable subclasses apart from Error in the
            // callable, so the else
            // part should never happen.
            if (e.getCause() instanceof Error)
                throw (Error) e.getCause();
            else
                logger.error(e.getMessage(), e);
        }
    }

    // Now if we had any failures we will be short a few reads. Do serial
    // reads to make up for these.
    while (successes < this.storeDef.getPreferredReads() && nodeIndex < nodes.size()) {
        Node node = nodes.get(nodeIndex);
        long startNs = System.nanoTime();
        try {
            retrieved.add(new GetResult<R>(node, key,
                    fetcher.execute(innerStores.get(node.getId()), key, transforms), null));
            ++successes;
            recordSuccess(node, startNs);
        } catch (UnreachableStoreException e) {
            failures.add(e);
            recordException(node, startNs, e);
        } catch (VoldemortApplicationException e) {
            throw e;
        } catch (Exception e) {
            logger.warn("Error in GET on node " + node.getId() + "(" + node.getHost() + ")", e);
            failures.add(e);
        }
        nodeIndex++;
    }

    if (logger.isTraceEnabled())
        logger.trace("GET retrieved the following node values: " + formatNodeValues(retrieved));

    if (preReturnProcedure != null)
        preReturnProcedure.apply(retrieved);

    if (successes >= this.storeDef.getRequiredReads()) {
        List<R> result = Lists.newArrayListWithExpectedSize(retrieved.size());
        for (GetResult<R> getResult : retrieved)
            result.addAll(getResult.retrieved);
        return result;
    } else
        throw new InsufficientOperationalNodesException(
                this.storeDef.getRequiredReads() + " reads required, but " + successes + " succeeded.",
                failures);
}

From source file:voldemort.store.routed.RoutedStore.java

private <R> List<R> get(final ByteArray key, StoreOp<R> fetcher,
        Function<List<GetResult<R>>, Void> preReturnProcedure) throws VoldemortException {
    StoreUtils.assertValidKey(key);// w  w w  .j a va 2 s .c o  m
    final List<Node> nodes = availableNodes(routingStrategy.routeRequest(key.get()));

    // quickly fail if there aren't enough nodes to meet the requirement
    checkRequiredReads(nodes);

    final List<GetResult<R>> retrieved = Lists.newArrayList();

    // A count of the number of successful operations
    int successes = 0;
    // A list of thrown exceptions, indicating the number of failures
    final List<Throwable> failures = Lists.newArrayListWithCapacity(3);

    // Do the preferred number of reads in parallel
    int attempts = Math.min(this.storeDef.getPreferredReads(), nodes.size());
    int nodeIndex = 0;
    List<Callable<GetResult<R>>> callables = Lists.newArrayListWithCapacity(attempts);
    for (; nodeIndex < attempts; nodeIndex++) {
        final Node node = nodes.get(nodeIndex);
        callables.add(new GetCallable<R>(node, key, fetcher));
    }

    List<Future<GetResult<R>>> futures;
    try {
        futures = executor.invokeAll(callables, timeoutMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new InsufficientOperationalNodesException("Get operation interrupted!", e);
    }

    for (Future<GetResult<R>> f : futures) {
        if (f.isCancelled()) {
            logger.warn("Get operation timed out after " + timeoutMs + " ms.");
            continue;
        }
        try {
            GetResult<R> getResult = f.get();
            if (getResult.exception != null) {
                if (getResult.exception instanceof VoldemortApplicationException) {
                    throw (VoldemortException) getResult.exception;
                }
                failures.add(getResult.exception);
                continue;
            }
            ++successes;
            retrieved.add(getResult);
        } catch (InterruptedException e) {
            throw new InsufficientOperationalNodesException("Get operation interrupted!", e);
        } catch (ExecutionException e) {
            // We catch all Throwable subclasses apart from Error in the
            // callable, so the else
            // part should never happen.
            if (e.getCause() instanceof Error)
                throw (Error) e.getCause();
            else
                logger.error(e.getMessage(), e);
        }
    }

    // Now if we had any failures we will be short a few reads. Do serial
    // reads to make up for these.
    while (successes < this.storeDef.getPreferredReads() && nodeIndex < nodes.size()) {
        Node node = nodes.get(nodeIndex);
        long startNs = System.nanoTime();
        try {
            retrieved.add(
                    new GetResult<R>(node, key, fetcher.execute(innerStores.get(node.getId()), key), null));
            ++successes;
            recordSuccess(node, startNs);
        } catch (UnreachableStoreException e) {
            failures.add(e);
            recordException(node, startNs, e);
        } catch (VoldemortApplicationException e) {
            throw e;
        } catch (Exception e) {
            logger.warn("Error in GET on node " + node.getId() + "(" + node.getHost() + ")", e);
            failures.add(e);
        }
        nodeIndex++;
    }

    if (logger.isTraceEnabled())
        logger.trace("GET retrieved the following node values: " + formatNodeValues(retrieved));

    if (preReturnProcedure != null)
        preReturnProcedure.apply(retrieved);

    if (successes >= this.storeDef.getRequiredReads()) {
        List<R> result = Lists.newArrayListWithExpectedSize(retrieved.size());
        for (GetResult<R> getResult : retrieved)
            result.addAll(getResult.retrieved);
        if (logger.isTraceEnabled())
            logger.trace("return " + result.size() + "items from routedstore");
        return result;
    } else
        throw new InsufficientOperationalNodesException(
                this.storeDef.getRequiredReads() + " reads required, but " + successes + " succeeded.",
                failures);
}

From source file:com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void interruptTest() throws Exception {

    // Pull image
    sut.pull(BUSYBOX_LATEST);// w  w  w.j a v a  2s .com

    // Create container
    final ContainerConfig config = ContainerConfig.builder().image(BUSYBOX_LATEST)
            .cmd("sh", "-c", "while :; do sleep 1; done").build();
    final String name = randomName();
    final ContainerCreation creation = sut.createContainer(config, name);
    final String id = creation.id();

    // Start container
    sut.startContainer(id);

    // Wait for container on a thread
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    final SettableFuture<Boolean> started = SettableFuture.create();
    final SettableFuture<Boolean> interrupted = SettableFuture.create();

    final Future<ContainerExit> exitFuture = executorService.submit(new Callable<ContainerExit>() {
        @Override
        public ContainerExit call() throws Exception {
            try {
                started.set(true);
                return sut.waitContainer(id);
            } catch (InterruptedException e) {
                interrupted.set(true);
                throw e;
            }
        }
    });

    // Interrupt waiting thread
    started.get();
    executorService.shutdownNow();
    try {
        exitFuture.get();
        fail();
    } catch (ExecutionException e) {
        assertThat(e.getCause(), instanceOf(InterruptedException.class));
    }

    // Verify that the thread was interrupted
    assertThat(interrupted.get(), is(true));
}

From source file:org.dllearner.scripts.evaluation.EnrichmentEvaluation.java

private void evaluateDataProperties(SparqlEndpointKS ks)
        throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, ComponentInitException, InterruptedException {
    Set<DatatypeProperty> properties = new SPARQLTasks(ks.getEndpoint()).getAllDataProperties();
    logger.info("Evaluating " + properties.size() + " data properties...");
    for (Class<? extends AxiomLearningAlgorithm> algorithmClass : dataPropertyAlgorithms) {
        int dataProperties = 0;
        Thread.sleep(5000);//from w  w w  . j av  a 2s. c o  m
        String algName = "";
        for (DatatypeProperty property : properties) {
            Thread.sleep(1000);
            try {
                // dynamically invoke constructor with SPARQL knowledge source
                AxiomLearningAlgorithm learner = algorithmClass.getConstructor(SparqlEndpointKS.class)
                        .newInstance(ks);
                ((AbstractAxiomLearningAlgorithm) learner).setReasoner(sparqlReasoner);
                ((AbstractAxiomLearningAlgorithm) learner).addFilterNamespace(NAMESPACE);
                ConfigHelper.configure(learner, "propertyToDescribe", property.toString());
                ConfigHelper.configure(learner, "maxExecutionTimeInSeconds", maxExecutionTimeInSeconds);
                learner.init();
                // learner.setPropertyToDescribe(property);
                // learner.setMaxExecutionTimeInSeconds(10);
                algName = AnnComponentManager.getName(learner);

                boolean emptyEntity = sparqlReasoner.getPopularity(property) == 0;
                if (emptyEntity) {
                    logger.warn("Empty entity: " + property);
                }
                if (emptyEntity) {
                    writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "EMPTY_ENTITY", 0,
                            0, false);
                } else {
                    int attempt = 0;
                    long startTime = 0;
                    boolean timeout = true;
                    while (((AbstractAxiomLearningAlgorithm) learner).isTimeout() && attempt++ < maxAttempts) {
                        if (attempt > 1) {
                            try {
                                logger.warn("Got timeout. Waiting " + delayInMilliseconds + " ms ...");
                                Thread.sleep(delayInMilliseconds);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        logger.info(
                                "Applying " + algName + " on " + property + " ... (Attempt " + attempt + ")");
                        startTime = System.currentTimeMillis();
                        try {
                            ((AbstractAxiomLearningAlgorithm) learner)
                                    .setForceSPARQL_1_0_Mode(attempt > nrOfAttemptsBeforeForceToSPARQL1_0_Mode);
                            learner.start();
                            timeout = ((AbstractAxiomLearningAlgorithm) learner).isTimeout();
                        } catch (Exception e) {
                            if (e.getCause() instanceof SocketTimeoutException) {

                            } else {
                                e.printStackTrace();
                            }
                        }
                    }

                    long runTime = System.currentTimeMillis() - startTime;
                    List<EvaluatedAxiom> learnedAxioms = learner
                            .getCurrentlyBestEvaluatedAxioms(nrOfAxiomsToLearn);
                    if (timeout && learnedAxioms.isEmpty()) {
                        writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "TIMEOUT", 0,
                                runTime, false);
                    } else if (learnedAxioms == null || learnedAxioms.isEmpty()) {
                        writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "NULL", 0,
                                runTime, false);
                    } else {
                        for (EvaluatedAxiom learnedAxiom : learnedAxioms) {
                            double score = learnedAxiom.getScore().getAccuracy();
                            if (Double.isNaN(score)) {
                                score = -1;
                            }
                            writeToDB(property.toManchesterSyntaxString(baseURI, prefixes).toString(), algName,
                                    learnedAxiom.getAxiom().toManchesterSyntaxString(baseURI, prefixes), score,
                                    runTime, isEntailed(learnedAxiom));
                        }
                    }
                }

                dataProperties++;
                if (maxDataProperties != 0 && dataProperties == maxDataProperties) {
                    break;
                }

            } catch (Exception e) {
                logger.error(
                        "Error occured for data property " + property.getName() + " with algorithm " + algName,
                        e);
            }
        }
    }
}

From source file:org.dllearner.scripts.evaluation.EnrichmentEvaluation.java

private void evaluateObjectProperties(SparqlEndpointKS ks)
        throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, ComponentInitException, InterruptedException {
    Set<ObjectProperty> properties = new SPARQLTasks(ks.getEndpoint()).getAllObjectProperties();
    logger.info("Evaluating " + properties.size() + " object properties...");

    for (Class<? extends AxiomLearningAlgorithm> algorithmClass : objectPropertyAlgorithms) {
        int objectProperties = 0;
        Thread.sleep(5000);/*  w  ww  . j  a  v  a2 s  .  c om*/
        String algName = "";
        for (ObjectProperty property : properties) {

            try {
                // dynamically invoke constructor with SPARQL knowledge source
                AxiomLearningAlgorithm learner = algorithmClass.getConstructor(SparqlEndpointKS.class)
                        .newInstance(ks);
                ((AbstractAxiomLearningAlgorithm) learner).setReasoner(sparqlReasoner);
                ((AbstractAxiomLearningAlgorithm) learner).addFilterNamespace(NAMESPACE);
                ConfigHelper.configure(learner, "propertyToDescribe", property.toString());
                ConfigHelper.configure(learner, "maxExecutionTimeInSeconds", maxExecutionTimeInSeconds);
                learner.init();
                // learner.setPropertyToDescribe(property);
                // learner.setMaxExecutionTimeInSeconds(10);
                algName = AnnComponentManager.getName(learner);

                boolean emptyEntity = sparqlReasoner.getPopularity(property) == 0;
                if (emptyEntity) {
                    logger.warn("Empty entity: " + property);
                }

                if (emptyEntity) {
                    writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "EMPTY_ENTITY", 0,
                            0, false);
                } else {
                    int attempt = 0;
                    long startTime = 0;
                    boolean timeout = true;
                    while (((AbstractAxiomLearningAlgorithm) learner).isTimeout() && attempt++ < maxAttempts) {
                        if (attempt > 1) {
                            try {
                                logger.warn("Got timeout. Waiting " + delayInMilliseconds + " ms ...");
                                Thread.sleep(delayInMilliseconds);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        logger.info(
                                "Applying " + algName + " on " + property + " ... (Attempt " + attempt + ")");
                        startTime = System.currentTimeMillis();
                        try {
                            ((AbstractAxiomLearningAlgorithm) learner)
                                    .setForceSPARQL_1_0_Mode(attempt > nrOfAttemptsBeforeForceToSPARQL1_0_Mode);
                            learner.start();
                            timeout = ((AbstractAxiomLearningAlgorithm) learner).isTimeout();
                        } catch (Exception e) {
                            if (e.getCause() instanceof SocketTimeoutException) {

                            } else {
                                e.printStackTrace();
                            }
                        }
                    }

                    long runTime = System.currentTimeMillis() - startTime;
                    List<EvaluatedAxiom> learnedAxioms = learner
                            .getCurrentlyBestEvaluatedAxioms(nrOfAxiomsToLearn);
                    if (timeout && learnedAxioms.isEmpty()) {
                        writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "TIMEOUT", 0,
                                runTime, false);
                    } else if (learnedAxioms == null || learnedAxioms.isEmpty()) {
                        writeToDB(property.toManchesterSyntaxString(baseURI, prefixes), algName, "NULL", 0,
                                runTime, false);
                    } else {
                        for (EvaluatedAxiom learnedAxiom : learnedAxioms) {
                            double score = learnedAxiom.getScore().getAccuracy();
                            if (Double.isNaN(score)) {
                                score = -1;
                            }
                            writeToDB(property.toManchesterSyntaxString(baseURI, prefixes).toString(), algName,
                                    learnedAxiom.getAxiom().toManchesterSyntaxString(baseURI, prefixes), score,
                                    runTime, isEntailed(learnedAxiom));
                        }
                    }
                }

                objectProperties++;
                if (maxObjectProperties != 0 && objectProperties == maxObjectProperties) {
                    break;
                }

            } catch (Exception e) {
                logger.error("Error occured for object property " + property.getName() + " with algorithm "
                        + algName, e);
            }
        }

    }
}