Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:org.fourthline.cling.transport.impl.apache.HttpServerConnectionUpnpStream.java

public void run() {

    try {//from   w w  w . j  ava 2  s. c  o  m
        while (!Thread.interrupted() && connection.isOpen()) {
            log.fine("Handling request on open connection...");
            HttpContext context = new BasicHttpContext(null);
            httpService.handleRequest(connection, context);
        }
    } catch (ConnectionClosedException ex) {
        log.fine("Client closed connection");
        responseException(ex);
    } catch (SocketTimeoutException ex) {
        log.fine("Server-side closed socket (this is 'normal' behavior of Apache HTTP Core!): "
                + ex.getMessage());
    } catch (IOException ex) {
        log.warning("I/O exception during HTTP request processing: " + ex.getMessage());
        responseException(ex);
    } catch (HttpException ex) {
        throw new UnsupportedDataException("Request malformed: " + ex.getMessage(), ex);
    } finally {
        try {
            connection.shutdown();
        } catch (IOException ex) {
            log.fine("Error closing connection: " + ex.getMessage());
        }
    }
}

From source file:org.apache.tomee.jul.handler.rotating.LocalFileHandlerTest.java

@Test
public void logAndRotate() throws IOException {
    final File out = new File("target/LocalFileHandlerTest/logs/");
    if (out.exists()) {
        for (final File file : asList(out.listFiles(new FileFilter() {
            @Override//from  w w w  .  jav a2s .  c om
            public boolean accept(final File pathname) {
                return pathname.getName().startsWith("test");
            }
        }))) {
            if (!file.delete()) {
                file.deleteOnExit();
            }
        }
    }

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("day1");
    config.put("filenamePattern", "target/LocalFileHandlerTest/logs/test.%s.%d.log");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");
    config.put("formatter", MessageOnlyFormatter.class.getName());

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    final File[] logFiles = out.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File pathname) {
            return pathname.getName().startsWith("test");
        }
    });
    final Set<String> logFilesNames = new HashSet<>();
    for (final File f : logFiles) {
        logFilesNames.add(f.getName());
    }
    assertEquals(2, logFiles.length);
    assertEquals(new HashSet<>(asList("test.day1.0.log", "test.day1.1.log")), logFilesNames);

    try (final InputStream is = new FileInputStream(new File(out, "test.day1.1.log"))) {
        final List<String> lines = IOUtils.readLines(is);
        assertEquals(19, lines.size());
        assertEquals(string10chars, lines.iterator().next());
    }

    final long firstFileLen = new File(out, "test.day1.0.log").length();
    assertTrue(firstFileLen >= 1024 * 10 && firstFileLen < 1024 * 10 + (1 + string10chars.getBytes().length));

    // now change of day
    today.set("day2");
    try { // ensure we tets the date
        Thread.sleep(1500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    handler.publish(new LogRecord(Level.INFO, string10chars));
    assertTrue(new File(out, "test.day2.0.log").exists());

    handler.close();
}

From source file:com.offbynull.voip.ui.UiRunnable.java

@Override
public void run() {
    try {//from w  ww.  j av  a 2s  .c  o  m
        UiWebRegion webRegion = (UiWebRegion) webRegionSupplier.retainedReference(); // doesn't return until its created

        while (true) {
            // Poll for new messages
            List<Object> incomingObjects = bus.pull();
            Validate.notNull(incomingObjects);
            Validate.noNullElements(incomingObjects);

            for (Object incomingObj : incomingObjects) {
                if (incomingObj instanceof Message) {
                    Message msg = (Message) incomingObj;

                    Address src = msg.getSourceAddress();
                    Address dst = msg.getDestinationAddress();
                    Object payload = msg.getMessage();

                    LOG.debug("Processing incoming message from {} to {}: {}", src, dst, payload);
                    busToWebRegion.add(payload);
                } else if (incomingObj instanceof AddShuttle) {
                    AddShuttle addShuttle = (AddShuttle) incomingObj;
                    Shuttle shuttle = addShuttle.getShuttle();
                    Shuttle existingShuttle = outgoingShuttles.putIfAbsent(shuttle.getPrefix(), shuttle);
                    Validate.validState(existingShuttle == null);
                } else if (incomingObj instanceof RemoveShuttle) {
                    RemoveShuttle removeShuttle = (RemoveShuttle) incomingObj;
                    String prefix = removeShuttle.getPrefix();
                    Shuttle oldShuttle = outgoingShuttles.remove(prefix);
                    Validate.validState(oldShuttle != null);
                } else if (incomingObj instanceof UiAction) {
                    UiAction uiAction = (UiAction) incomingObj;
                    Object payload = uiAction.getMessage();
                    sendMessage(payload);
                } else {
                    throw new IllegalStateException("Unexpected message type: " + incomingObj);
                }
            }
        }
    } catch (InterruptedException ie) {
        LOG.debug("Audio gateway interrupted");
        Thread.interrupted();
    } catch (Exception e) {
        LOG.error("Internal error encountered", e);
    } finally {
        bus.close();
    }
}

From source file:org.fseek.simon.swing.util.TreeUtil.java

private static void fakeNode(LinkTreeNode node, DefaultTreeModel model) {
    Debug.println("Faking node: " + node.getUserObject().toString());
    deleteAllChilds(node, model, null);// w  w  w .j  ava 2  s  .com
    if (Thread.interrupted()) {
        return;
    }
    model.insertNodeInto(new DefaultMutableTreeNode(), node, 0);
}

From source file:org.marketcetera.util.except.ExceptUtilsTest.java

@Test
public void interruptionEmptyThrow() {
    Thread.currentThread().interrupt();
    try {// www.j a  v  a2s  .c  o m
        ExceptUtils.checkInterruption();
        fail();
    } catch (InterruptedException ex) {
        assertTrue(Thread.interrupted());
        assertEquals("Thread execution was interrupted", ex.getMessage());
        assertNull(ex.getCause());
    }
}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.StreamPumper.java

/**
 * Copies data from the input stream to the output stream.
 *
 * Terminates as soon as the input stream is closed or an error occurs.
 *///w  w w .  ja  v  a  2s  .  com
public void run() {
    synchronized (this) {
        started = true;
    }
    finished = false;
    finish = false;

    final byte[] buf = new byte[bufferSize];

    int length;
    try {
        while (true) {
            waitForInput(is);

            if (finish || Thread.interrupted()) {
                break;
            }

            length = is.read(buf);
            if (length <= 0 || finish || Thread.interrupted()) {
                break;
            }
            os.write(buf, 0, length);
            if (autoflush) {
                os.flush();
            }
        }
        os.flush();
    } catch (InterruptedException ie) {
        // likely PumpStreamHandler trying to stop us
    } catch (Exception e) {
        synchronized (this) {
            exception = e;
        }
    } finally {
        if (closeWhenExhausted) {
            try {
                os.close();
            } catch (IOException e) {
                LOG.warn("Error closing stream", e);
            }
        }
        finished = true;
        synchronized (this) {
            notifyAll();
        }
    }
}

From source file:net.wimpi.telnetd.util.Mutex.java

public boolean attempt(long msecs) throws InterruptedException {
    //log.debug("attempt()::" + Thread.currentThread().toString());
    if (Thread.interrupted())
        throw new InterruptedException();
    synchronized (this) {
        if (!inuse_) {
            inuse_ = true;/*  w  w w.j ava  2 s.c om*/
            return true;
        } else if (msecs <= 0)
            return false;
        else {
            long waitTime = msecs;
            long start = System.currentTimeMillis();
            try {
                for (;;) {
                    wait(waitTime);
                    if (!inuse_) {
                        inuse_ = true;
                        return true;
                    } else {
                        waitTime = msecs - (System.currentTimeMillis() - start);
                        if (waitTime <= 0)
                            return false;
                    }
                }
            } catch (InterruptedException ex) {
                notify();
                throw ex;
            }
        }
    }
}

From source file:com.subgraph.vega.internal.http.proxy.HttpProxy.java

private void proxyAcceptLoop() {
    while (!Thread.interrupted()) {
        Socket s;/*from   ww  w .  ja  v a  2  s . co m*/
        try {
            s = serverSocket.accept();
        } catch (IOException e) {
            if (!Thread.interrupted()) {
                logger.log(Level.WARNING, "IO error processing incoming connection: " + e.getMessage(), e);
            }
            break;
        }

        logger.fine("Connection accepted from " + s.getRemoteSocketAddress());
        VegaHttpServerConnection c = new VegaHttpServerConnection(params);
        try {
            c.bind(s, params);
        } catch (IOException e) {
            logger.log(Level.WARNING, "Unexpected error: " + e.getMessage(), e);
            continue;
        }

        final ConnectionTask task = new ConnectionTask(httpService, c, HttpProxy.this);
        synchronized (connectionList) {
            connectionList.add(task);
        }
        executor.execute(task);
    }

    synchronized (connectionList) {
        for (ConnectionTask task : connectionList) {
            task.shutdown();
        }
    }

    executor.shutdownNow();
}

From source file:org.apache.nifi.toolkit.cli.impl.command.nifi.pg.PGEnableControllerServices.java

@Override
public VoidResult doExecute(final NiFiClient client, final Properties properties)
        throws NiFiClientException, IOException, MissingOptionException, CommandException {

    final String pgId = getRequiredArg(properties, CommandOption.PG_ID);
    final FlowClient flowClient = client.getFlowClient();

    if (shouldPrint(properties)) {
        println();//ww w. j  a va2 s. c  om
    }

    int count = 0;
    int prevNumEnabled = -1;
    int enablingIterations = 1;

    // request to enable services until the number of enabled services is no longer changing, which means either all
    // services have been enabled, or the rest of the services are invalid and can't be enabled
    while (count < MAX_ATTEMPTS) {

        // retrieve the current states of the services in the given pg
        final ControllerServiceStateCounts states = getControllerServiceStates(flowClient, pgId);

        // if any services are currently enabling then sleep and loop again
        if (states.getEnabling() > 0) {
            if (enablingIterations < MAX_ENABLING_ITERATIONS) {
                if (shouldPrint(properties)) {
                    println("Currently " + states.getEnabling()
                            + " services are enabling, waiting to finish before " + "proceeding ("
                            + enablingIterations + " of " + MAX_ENABLING_ITERATIONS + ")");
                }
                try {
                    Thread.sleep(ENABLING_DELAY_MS);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }

                enablingIterations++;
                continue;
            } else {
                if (shouldPrint(properties)) {
                    printServicesStillEnabling(flowClient, pgId);
                }

                // throw an exception so stand-alone mode will exit with a non-zero status code
                throw new CommandException(
                        "One or more services are stuck enabling, run command with -verbose to obtain more details");
            }
        }

        // reset the enabling iteration count since we got past the above block without breaking
        enablingIterations = 1;

        // if no services are enabling and the number of enabled services equals the number of enabled services from
        // last iteration, then we know there are no more that we can enable so break
        if (states.getEnabled() == prevNumEnabled && states.getEnabling() == 0) {
            if (shouldPrint(properties)) {
                println();
                println("Finished with " + states.getEnabled() + " enabled services and " + states.getDisabled()
                        + " disabled services");
            }

            if (states.getDisabled() > 0 || states.getDisabling() > 0) {
                if (shouldPrint(properties)) {
                    printServicesNotEnabled(flowClient, pgId);
                    println();
                }

                // throw an exception so stand-alone mode will exit with a non-zero status code
                throw new CommandException(
                        "One or more services could not be enabled, run command with -verbose to obtain more details");
            } else {
                if (shouldPrint(properties)) {
                    println();
                }

                // just break here to proceed with normal completion (i.e. will have a zero status code)
                break;
            }
        }

        // if we didn't break then store the number that were enabled to compare with next time
        prevNumEnabled = states.getEnabled();

        if (shouldPrint(properties)) {
            println("Currently " + states.getEnabled() + " enabled services and " + states.getDisabled()
                    + " disabled services, attempting to enable services...");
        }

        // send the request to enable services
        final ActivateControllerServicesEntity enableEntity = new ActivateControllerServicesEntity();
        enableEntity.setId(pgId);
        enableEntity.setState(ActivateControllerServicesEntity.STATE_ENABLED);

        flowClient.activateControllerServices(enableEntity);
        count++;
    }

    return VoidResult.getInstance();
}

From source file:at.alladin.rmbt.android.util.CheckIpTask.java

@Override
protected void onPostExecute(final JSONArray newsList) {

    try {/* w  ww.j a v a2 s  .c  om*/
        Log.d(DEBUG_TAG, "News: " + newsList);
        int ipv = 4;

        if (newsList != null && newsList.length() > 0 && !serverConn.hasError()) {
            for (int i = 0; i < newsList.length(); i++) {
                if (!isCancelled() && !Thread.interrupted()) {
                    try {

                        final JSONObject newsItem = newsList.getJSONObject(i);

                        if (newsItem.has("v")) {
                            ipv = newsItem.getInt("v");

                            if (ipv == 6) {
                                try {
                                    publicIpv6 = newsItem.getString("ip");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                try {
                                    publicIpv4 = newsItem.getString("ip");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (final JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (onCompleteListener != null && !needsRetry) {
                onCompleteListener.onComplete(NetworkInfoCollector.FLAG_PRIVATE_IPV6, privateIpv6);
                onCompleteListener.onComplete(NetworkInfoCollector.FLAG_PRIVATE_IPV4, privateIpv4);
                onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IPV4, publicIpv4);
                onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IPV6, publicIpv6);
                onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IP_TASK_COMPLETED, null);
            } else if (onCompleteListener != null) {
                onCompleteListener.onComplete(OnCompleteListener.ERROR,
                        NetworkInfoCollector.FLAG_IP_TASK_NEEDS_RETRY);
            }

        } else {
            ConfigHelper.setLastIp(activity.getApplicationContext(), null);
            if (onCompleteListener != null) {
                onCompleteListener.onComplete(OnCompleteListener.ERROR, null);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //        finally {
    //           if (onCompleteListener != null) {
    //              onCompleteListener.onComplete(NetworkInfoCollector.FLAG_IP_TASK_COMPLETED, null);
    //           }
    //        }
}