Example usage for java.lang InterruptedException getLocalizedMessage

List of usage examples for java.lang InterruptedException getLocalizedMessage

Introduction

In this page you can find the example usage for java.lang InterruptedException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.serotonin.modbus4j.ip.listener.TcpListener.java

private void terminateListener() {
    executorService.shutdown();//from ww w .j  a  va 2 s .c  o m
    try {
        executorService.awaitTermination(300, TimeUnit.MILLISECONDS);
        LOG.debug("Handler Thread terminated,  Port: " + ipParameters.getPort());
    } catch (InterruptedException e) {
        LOG.debug("Error terminating executorService - " + e.getLocalizedMessage());
        getExceptionHandler().receivedException(e);
    }
    handler = null;
}

From source file:com.freedomotic.plugins.devices.ethrly.DevantechEthRly.java

@Override
protected void onRun() {
    // select all boards in the devices hashmap and evaluate the status
    Set<String> keySet = devices.keySet();
    for (String key : keySet) {
        Board board = devices.get(key);/*  www .  j  ava2s. co m*/
        evaluateDiffs(getXMLStatusFile(board), board);
    }
    try {
        Thread.sleep(POLLING_TIME);
    } catch (InterruptedException ex) {
        LOG.error(ex.getLocalizedMessage());
    }
}

From source file:org.apache.pig.tools.grunt.GruntParser.java

public static int runSQLCommand(String hcatBin, String cmd, boolean mInteractive) throws IOException {
    List<String> tokensList = new ArrayList<String>();
    if (hcatBin.endsWith(".py")) {
        tokensList.add("python");
        tokensList.add(hcatBin);//from w  w  w. j  a  va 2  s.c  o m
    } else {
        tokensList.add(hcatBin);
    }
    cmd = cmd.trim();
    if (!cmd.substring(0, 3).toLowerCase().equals("sql")) {
        // Should never happen
        throw new IOException("sql command not start with sql keyword");
    }
    cmd = cmd.substring(3).trim();
    tokensList.add("-e");
    tokensList.add(cmd.replaceAll("\n", " "));
    String[] tokens = tokensList.toArray(new String[] {});

    // create new environment = environment - HADOOP_CLASSPATH
    // This is because of antlr version conflict between Pig and Hive
    Map<String, String> envs = System.getenv();
    Set<String> envSet = new HashSet<String>();
    for (Map.Entry<String, String> entry : envs.entrySet()) {
        if (!entry.getKey().equals("HADOOP_CLASSPATH")) {
            envSet.add(entry.getKey() + "=" + entry.getValue());
        }
    }

    log.info("Going to run hcat command: " + tokens[tokens.length - 1]);
    Process executor = Runtime.getRuntime().exec(tokens, envSet.toArray(new String[0]));
    StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, System.out);
    StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, System.err);

    outPrinter.start();
    errPrinter.start();

    int ret;
    try {
        ret = executor.waitFor();

        outPrinter.join();
        errPrinter.join();
        if (ret != 0 && !mInteractive) {
            throw new IOException("sql command '" + cmd + "' failed. ");
        }
    } catch (InterruptedException e) {
        log.warn("Exception raised from sql command " + e.getLocalizedMessage());
    }
    return 0;
}

From source file:org.apache.solr.client.solrj.impl.StreamingUpdateSolrServer.java

@Override
public NamedList<Object> request(final SolrRequest request) throws SolrServerException, IOException {
    if (!(request instanceof UpdateRequest)) {
        return super.request(request);
    }//from w  w  w.ja v  a2 s  .  c o m
    UpdateRequest req = (UpdateRequest) request;

    // this happens for commit...
    if (req.getDocuments() == null || req.getDocuments().isEmpty()) {
        blockUntilFinished();
        return super.request(request);
    }

    SolrParams params = req.getParams();
    if (params != null) {
        // check if it is waiting for the searcher
        if (params.getBool(UpdateParams.WAIT_SEARCHER, false)) {
            log.info("blocking for commit/optimize");
            blockUntilFinished(); // empty the queue
            return super.request(request);
        }
    }

    try {
        CountDownLatch tmpLock = lock;
        if (tmpLock != null) {
            tmpLock.await();
        }

        boolean success = queue.offer(req);

        for (;;) {
            synchronized (runners) {
                if (runners.isEmpty() || (queue.remainingCapacity() < queue.size() // queue is half full and we can add more runners
                        && runners.size() < threadCount)) {
                    // We need more runners, so start a new one.
                    Runner r = new Runner();
                    runners.add(r);
                    scheduler.execute(r);
                } else {
                    // break out of the retry loop if we added the element to the queue successfully, *and*
                    // while we are still holding the runners lock to prevent race conditions.
                    // race conditions.
                    if (success)
                        break;
                }
            }

            // Retry to add to the queue w/o the runners lock held (else we risk temporary deadlock)
            // This retry could also fail because
            // 1) existing runners were not able to take off any new elements in the queue
            // 2) the queue was filled back up since our last try
            // If we succeed, the queue may have been completely emptied, and all runners stopped.
            // In all cases, we should loop back to the top to see if we need to start more runners.
            //
            if (!success) {
                success = queue.offer(req, 100, TimeUnit.MILLISECONDS);
            }

        }

    } catch (InterruptedException e) {
        log.error("interrupted", e);
        throw new IOException(e.getLocalizedMessage());
    }

    // RETURN A DUMMY result
    NamedList<Object> dummy = new NamedList<Object>();
    dummy.add("NOTE", "the request is processed in a background stream");
    return dummy;
}

From source file:net.sf.logsaw.ui.impl.LogResourceManagerImpl.java

@Override
public void close() throws CoreException {
    // Wait for all jobs to finish
    List<Job> l = new ArrayList<Job>(syncInProgressMap.values());
    for (Job job : l) {
        job.cancel();//from www  .j a  v  a  2  s.  c om
        try {
            job.join();
        } catch (InterruptedException e) {
            logger.error(e.getLocalizedMessage(), e);
        }
    }
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.utils.commands.TagAndPushHandler.java

@Override
protected Object internalExecute(ExecutionEvent event) throws Exception {
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
    final Shell shell = HandlerUtil.getActiveShell(event);

    List<Repository> repositories = new ArrayList<Repository>();

    //acquire the list of repositories
    for (Object o : selection.toArray()) {
        RepositoryNode node = (RepositoryNode) o;
        repositories.add(node.getRepository());
        assert node.getRepository() != null;
    }/*from w ww  . j a va  2s .  c o  m*/

    //configure tagging operation
    TagAndPushDialog tagAndPushConfigDialog = new TagAndPushDialog(shell, repositories);
    if (tagAndPushConfigDialog.open() != IDialogConstants.OK_ID) {
        return null;
    }
    //perform tagging operation
    try {
        ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell);
        final TagAndPushOperation op = new TagAndPushOperation(progressDialog.getShell(), repositories,
                tagAndPushConfigDialog.getSettings());
        progressDialog.run(true, true, op);
        shell.getDisplay().asyncExec(new Runnable() {

            public void run() {
                if (op.getResult().getSeverity() >= IStatus.WARNING) {
                    Policy.getStatusHandler().show(op.getResult(), "Results of the operation");
                } else {
                    MessageDialog.openInformation(shell, "Create and Push Tag",
                            "Repositories has been successfully tagged.");
                }
            }
        });
    } catch (InterruptedException e) {
        //ignore
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().getLog()
                .log(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, e.getLocalizedMessage(), e));
        MessageDialog.openError(shell, "Create and Push Tag", e.getLocalizedMessage());
    }

    return null;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

/**
 * Imports a spreadsheet of leads or custom objects into the target instance
 *
 * POST /bulk/v1/leads/import.json//  w ww .j a v a  2 s. co  m
 *
 * POST /bulk/v1/customobjects/{apiName}/import.json
 *
 * @param parameters
 * @return
 */
public MarketoRecordResult bulkImport(TMarketoBulkExecProperties parameters) {
    String importFilename = parameters.bulkFilePath.getValue();
    String format = parameters.bulkFileFormat.getValue().name();
    Integer pollWaitTime = parameters.pollWaitTime.getValue();
    String logDownloadPath = parameters.logDownloadPath.getValue();
    String lookupField;
    Integer listId;
    String partitionName;
    String customObjectName;
    current_uri = new StringBuilder(bulkPath);
    Boolean isImportingLeads = parameters.bulkImportTo.getValue().equals(BulkImportTo.Leads);
    if (isImportingLeads) {
        lookupField = parameters.lookupField.getValue().name();
        listId = parameters.listId.getValue();
        partitionName = parameters.partitionName.getValue();
        current_uri.append(API_PATH_BULK_LEADS)//
                .append(fmtParams(FIELD_ACCESS_TOKEN, accessToken, true))//
                .append(fmtParams(FIELD_LOOKUP_FIELD, lookupField));
        if (listId != null) {
            current_uri.append(fmtParams(FIELD_LIST_ID, listId));
        }
        if (!StringUtils.isEmpty(partitionName)) {
            current_uri.append(fmtParams(FIELD_PARTITION_NAME, partitionName));
        }
    } else {
        customObjectName = parameters.customObjectName.getValue();
        current_uri.append(String.format(API_PATH_BULK_CUSTOMOBJECTS, customObjectName))//
                .append(fmtParams(FIELD_ACCESS_TOKEN, accessToken, true));
    }
    current_uri.append(fmtParams(FIELD_FORMAT, format));
    //
    MarketoRecordResult mkto = new MarketoRecordResult();
    try {
        LOG.debug("bulkImport {}.", current_uri);
        BulkImportResult rs = executePostFileRequest(BulkImportResult.class, importFilename);
        LOG.debug("rs = {}.", rs);
        mkto.setRequestId(REST + "::" + rs.getRequestId());
        mkto.setSuccess(rs.isSuccess());
        if (!mkto.isSuccess()) {
            mkto.setRecordCount(0);
            mkto.setErrors(Arrays.asList(new MarketoError(REST, rs.getErrors().get(0).getCode(),
                    messages.getMessage("bulkimport.error.import", rs.getErrors().get(0).getMessage()))));
            return mkto;
        }
        BulkImport bulkResult = rs.getResult().get(0);
        if (bulkResult.getStatus().equals(BULK_STATUS_FAILED)) { // request Failed
            String err = messages.getMessage("bulkimport.status.failed", bulkResult.getMessage());
            LOG.error("{}.", err);
            mkto.setSuccess(false);
            mkto.setErrors(Arrays.asList(new MarketoError(REST, err)));
        } else if (bulkResult.getStatus().equals(BULK_STATUS_COMPLETE)) { // already Complete
            bulkResult = getStatusesForBatch(bulkResult, logDownloadPath);
        } else { // Importing, Queued
            while (true) {
                try {
                    LOG.warn(messages.getMessage("bulkimport.status.waiting", pollWaitTime));
                    Thread.sleep(pollWaitTime * 1000L);
                    current_uri = new StringBuilder(bulkPath);
                    if (bulkResult.isBulkLeadsImport()) {
                        current_uri.append(
                                String.format(API_PATH_BULK_LEADS_RESULT_STATUS, bulkResult.getBatchId()));
                    } else {
                        current_uri.append(String.format(API_PATH_BULK_CUSTOMOBJECTS_RESULT,
                                bulkResult.getObjectApiName(), bulkResult.getBatchId(), "status"));
                    }
                    current_uri.append(fmtParams(FIELD_ACCESS_TOKEN, accessToken, true));
                    LOG.debug("status = {}.", current_uri);
                    rs = (BulkImportResult) executeGetRequest(BulkImportResult.class);
                    if (rs.isSuccess() && rs.getResult().get(0).getStatus().equals(BULK_STATUS_COMPLETE)) {
                        bulkResult = getStatusesForBatch(rs.getResult().get(0), logDownloadPath);
                        break;
                    } else {
                        LOG.warn(messages.getMessage("bulkimport.status.current",
                                rs.getResult().get(0).getStatus()));
                    }
                } catch (InterruptedException e) {
                    LOG.error("Sleep interrupted : {}", e);
                    throw new MarketoException(REST, "Sleep interrupted : " + e.getLocalizedMessage());
                }
            }
        }
        mkto.setRecords(Arrays.asList(bulkResult.toIndexedRecord()));
        mkto.setRecordCount(1);
        mkto.setRemainCount(0);
    } catch (MarketoException e) {
        mkto.setSuccess(false);
        mkto.setErrors(Arrays.asList(e.toMarketoError()));
    }
    return mkto;
}

From source file:se.trixon.jota.client.Client.java

public boolean serverStart() throws URISyntaxException, IOException, NotBoundException {
    boolean serverProbablyStarted = false;
    Xlog.timedOut(Dict.SERVER_START.toString());

    StringBuilder java = new StringBuilder();
    java.append(System.getProperty("java.home")).append(SystemUtils.FILE_SEPARATOR).append("bin")
            .append(SystemUtils.FILE_SEPARATOR).append("java");

    if (SystemUtils.IS_OS_WINDOWS) {
        java.append(".exe");
    }/*from   www. ja  va2 s  . c o  m*/

    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    File jarFile = new File(codeSource.getLocation().toURI().getPath());
    if (jarFile.getAbsolutePath().endsWith(".jar")) {
        ArrayList<String> command = new ArrayList<>();
        command.add(java.toString());
        command.add("-cp");
        command.add(jarFile.getAbsolutePath());
        command.add("Server");
        command.add("--port");
        command.add(String.valueOf(mOptions.getAutostartServerPort()));

        Xlog.timedOut(StringUtils.join(command, " "));
        ProcessBuilder processBuilder = new ProcessBuilder(command).inheritIO();
        processBuilder.start();

        try {
            Thread.sleep(mOptions.getAutostartServerConnectDelay());
        } catch (InterruptedException ex) {
            Xlog.timedErr(ex.getLocalizedMessage());
        }

        serverProbablyStarted = true;
    } else {
        Xlog.timedErr(mBundle.getString("autostart_info"));
    }

    return serverProbablyStarted;
}

From source file:org.jenkinsci.plugins.mber.MberDownloader.java

@Override
public boolean perform(final AbstractBuild build, final Launcher launcher, final BuildListener listener) {
    // Users can set custom workspaces and inadvertantly invalidate the build's workspace.
    final FilePath workspace = build.getWorkspace();
    if (workspace == null) {
        log(listener, "Files will not be downloaded because a workspace for this build was not found.");
        return isOptional();
    }// w w  w  . j a  va 2  s .  co m

    // Set up a Mber client and log in so we get an access token.
    final MberClient mber = new Retryable<MberClient>(listener.getLogger(), getAttempts()) {
        @Override
        public MberClient call() {
            // The global configuration may be modified while the job's running.
            final MberAccessProfile accessProfile = MberNotifier.getAccessProfile(getAccessProfileName());
            if (accessProfile == null) {
                throw new RetryException(String.format(
                        "An access profile named '%s' was not found. Make sure it hasn't been deleted from the global configuration.",
                        getAccessProfileName()));
            }

            // The access profile may have invalid credentials if it's being modified.
            final MberClient mber = makeMberClient(listener, accessProfile);
            log(listener, "Connecting to Mber at " + mber.getURL());
            final JSONObject response = mber.login(accessProfile.getUsername(),
                    accessProfile.getPassword().getPlainText());
            if (!MberJSON.isSuccess(response)) {
                throw new RetryException(
                        String.format("Failed to connect to Mber. Check your configuration settings.",
                                getAccessProfileName()));
            }

            return mber;
        }
    }.run();

    // Downloads require access tokens, so bail if we didn't get one.
    if (mber == null) {
        return isOptional();
    }

    // Resolve environment variables in file identifiers.
    final String[] fileIdentifiers = resolveFileIdentifiers(build, listener);
    if (fileIdentifiers == null) {
        return isOptional();
    }

    ArrayList<JSONObject> documents = new ArrayList<JSONObject>();
    if (!isUseTags()) {
        // Look for files with matching IDs.
        for (final String documentId : fileIdentifiers) {
            final JSONObject response = new Retryable<JSONObject>(listener.getLogger(), getAttempts()) {
                @Override
                public JSONObject call() {
                    final JSONObject result = mber.readDocument(documentId);
                    // Only retry failures. Semi-successful responses like NotFound, won't retry.
                    if (MberJSON.isFailed(result)) {
                        throw new RetryException(MberJSON.getString(result, "error"));
                    }
                    return result;
                }
            }.run();

            // Let the user know we couldn't find their file. The Retryable handles exceptions e.g. network connectivity issues.
            if (!MberJSON.isSuccess(response)) {
                log(listener,
                        "A file with ID %s was not found in Mber. Check that you spelled the file identifier correctly.",
                        documentId);
                return isOptional();
            }

            // Make sure the document is flagged as downloadable so we can use it in the download API.
            final JSONObject document = MberJSON.getObject(response, "result");
            if (!MberJSON.getBooleanOrFalse(document, "canDownload")) {
                log(listener,
                        "The file with ID %s is not downloadable from Mber. Check that the file has been uploaded or synced to a CDN.",
                        documentId);
                return isOptional();
            }

            documents.add(document);
        }
    } else {
        // Look for files with matching tags.
        final JSONObject response = new Retryable<JSONObject>(listener.getLogger(), getAttempts()) {
            @Override
            public JSONObject call() {
                final JSONObject result = mber.findDocumentsWithTags(fileIdentifiers);
                // Document indexing isn't instant, so retry if nothing's found.
                if (!MberJSON.isSuccess(result)) {
                    throw new RetryException(MberJSON.getString(result, "error"));
                }
                if (MberJSON.getArray(result, "results").isEmpty()) {
                    throw new RetryException("Failed to find files with tags: %s",
                            StringUtils.join(fileIdentifiers, ", "));
                }
                return result;
            }
        }.run();

        // Let the user know we couldn't find any files. The Retryable handles exceptions e.g. network connectivity issues.
        if (!MberJSON.isSuccess(response) || MberJSON.getArray(response, "results").isEmpty()) {
            log(listener, "Failed to find files with tags: %s", StringUtils.join(fileIdentifiers, ", "));
            return isOptional();
        }

        // Make sure all the found documents as downloadable so we can use them in the download API.
        final JSONArray results = MberJSON.getArray(response, "results");
        final Iterator<JSONObject> itr = results.iterator();
        while (itr.hasNext()) {
            final JSONObject document = itr.next();
            if (!MberJSON.getBooleanOrFalse(document, "canDownload")) {
                final String documentId = document.getString("documentId");
                log(listener,
                        "The file with ID %s is not downloadable from Mber. Check that the file has been uploaded or synced to a CDN.",
                        documentId);
                return isOptional();
            }
            documents.add(document);
        }
    }

    // The user specified files to download but we didn't find any in Mber.
    if (fileIdentifiers.length > 0 && documents.isEmpty()) {
        log(listener,
                "No dowloadable files where found in Mber. Check that you spelled the file identifiers correctly.");
        return isOptional();
    }

    for (final JSONObject document : documents) {
        final String name = document.getString("name");
        final FilePath file = workspace.child(name);

        // Check for existing files before downloading new ones that overwrite them.
        try {
            if (!isOverwriteExistingFiles() && file.exists()) {
                log(listener, "A file named %s already exists in the workspace.", name);
                return isOptional();
            }
        } catch (final InterruptedException e) {
            log(listener, e.getLocalizedMessage());
            return isOptional();
        } catch (final IOException e) {
            log(listener, e.getLocalizedMessage());
            return isOptional();
        }

        // Download the file from Mber, retrying as necessary.
        final String documentId = document.getString("documentId");
        log(listener, "Dowloading file %s", name);
        final JSONObject response = new Retryable<JSONObject>(listener.getLogger(), getAttempts()) {
            @Override
            public JSONObject call() {
                final JSONObject response = mber.download(file, documentId, isShowProgress());
                if (!MberJSON.isSuccess(response) && !MberJSON.isAborted(response)) {
                    throw new RetryException(response.getString("error"));
                }
                return response;
            }
        }.run();

        // The download's already been retried, so bail if it's not successful.
        if (!MberJSON.isSuccess(response)) {
            log(listener, "Failed to download file %s", file);
            log(listener, response.getString("error"));
            return isOptional();
        }
    }

    return true;
}

From source file:org.tvheadend.tvhclient.fragments.TimerRecordingListFragment.java

/**
 * Calls the service to remove the scheduled recordings. The service is
 * called in a certain interval to prevent too many calls to the interface.
 *//*  ww  w.  j  av a 2s.  c o  m*/
private void removeAllRecordings() {
    new Thread() {
        public void run() {
            for (int i = 0; i < adapter.getCount(); ++i) {
                final TimerRecording rec = adapter.getItem(i);
                if (rec != null) {
                    final Intent intent = new Intent(activity, HTSService.class);
                    intent.setAction(Constants.ACTION_DELETE_TIMER_REC_ENTRY);
                    intent.putExtra("id", rec.id);
                    activity.startService(intent);
                }
                try {
                    sleep(Constants.THREAD_SLEEPING_TIME);
                } catch (InterruptedException e) {
                    Log.d(TAG, "Error removing all manual recordings, " + e.getLocalizedMessage());
                }
            }
        }
    }.start();
}