Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadExecutor.

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * Start FTP upload./*from   ww w.  jav  a2s.  c  o m*/
 *
 * @param hostname      ftp host
 * @param port          ftp port
 * @param uri           upload uri
 * @param fileSizeOctet file size in octet
 * @param user          username
 * @param password      password
 */
public void startFtpUpload(final String hostname, final int port, final String uri, final int fileSizeOctet,
        final String user, final String password) {

    mSpeedTestMode = SpeedTestMode.UPLOAD;

    mUploadFileSize = new BigDecimal(fileSizeOctet);
    mForceCloseSocket = false;
    mErrorDispatched = false;

    if (mWriteExecutorService == null || mWriteExecutorService.isShutdown()) {
        mWriteExecutorService = Executors.newSingleThreadExecutor();
    }

    mWriteExecutorService.execute(new Runnable() {
        @Override
        public void run() {

            final FTPClient ftpClient = new FTPClient();
            final RandomGen randomGen = new RandomGen();

            RandomAccessFile uploadFile = null;

            try {
                ftpClient.connect(hostname, port);
                ftpClient.login(user, password);
                ftpClient.enterLocalPassiveMode();
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

                byte[] fileContent = new byte[] {};

                if (mSocketInterface.getUploadStorageType() == UploadStorageType.RAM_STORAGE) {
                    /* generate a file with size of fileSizeOctet octet */
                    fileContent = randomGen.generateRandomArray(fileSizeOctet);
                } else {
                    uploadFile = randomGen.generateRandomFile(fileSizeOctet);
                    uploadFile.seek(0);
                }

                mFtpOutputstream = ftpClient.storeFileStream(uri);

                if (mFtpOutputstream != null) {

                    mUploadTempFileSize = 0;

                    final int uploadChunkSize = mSocketInterface.getUploadChunkSize();

                    final int step = fileSizeOctet / uploadChunkSize;
                    final int remain = fileSizeOctet % uploadChunkSize;

                    mTimeStart = System.currentTimeMillis();
                    mTimeEnd = 0;

                    if (mRepeatWrapper.isFirstUpload()) {
                        mRepeatWrapper.setFirstUploadRepeat(false);
                        mRepeatWrapper.setStartDate(mTimeStart);
                    }

                    if (mRepeatWrapper.isRepeatUpload()) {
                        mRepeatWrapper.updatePacketSize(mUploadFileSize);
                    }

                    if (mForceCloseSocket) {
                        SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "");
                    } else {
                        for (int i = 0; i < step; i++) {

                            final byte[] chunk = SpeedTestUtils.readUploadData(
                                    mSocketInterface.getUploadStorageType(), fileContent, uploadFile,
                                    mUploadTempFileSize, uploadChunkSize);

                            mFtpOutputstream.write(chunk, 0, uploadChunkSize);

                            mUploadTempFileSize += uploadChunkSize;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(uploadChunkSize);
                            }

                            if (!mReportInterval) {

                                final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                                for (int j = 0; j < mListenerList.size(); j++) {
                                    mListenerList.get(j).onUploadProgress(report.getProgressPercent(), report);
                                }
                            }
                        }

                        if (remain != 0) {

                            final byte[] chunk = SpeedTestUtils.readUploadData(
                                    mSocketInterface.getUploadStorageType(), fileContent, uploadFile,
                                    mUploadTempFileSize, remain);

                            mFtpOutputstream.write(chunk, 0, remain);

                            mUploadTempFileSize += remain;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(remain);
                            }
                        }
                        if (!mReportInterval) {
                            final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                            for (int j = 0; j < mListenerList.size(); j++) {
                                mListenerList.get(j).onUploadProgress(SpeedTestConst.PERCENT_MAX.floatValue(),
                                        report);

                            }
                        }
                        mTimeEnd = System.currentTimeMillis();
                    }
                    mFtpOutputstream.close();

                    mReportInterval = false;
                    final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                    for (int i = 0; i < mListenerList.size(); i++) {
                        mListenerList.get(i).onUploadFinished(report);
                    }

                    if (!mRepeatWrapper.isRepeatUpload()) {
                        closeExecutors();
                    }

                } else {
                    mReportInterval = false;
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, "cant create stream "
                            + "from uri " + uri + " with reply code : " + ftpClient.getReplyCode());
                }
            } catch (SocketTimeoutException e) {
                //e.printStackTrace();
                mReportInterval = false;
                mErrorDispatched = true;
                if (!mForceCloseSocket) {
                    SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, false,
                            SpeedTestConst.SOCKET_WRITE_ERROR);
                } else {
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                }
                closeSocket();
                closeExecutors();
            } catch (IOException e) {
                //e.printStackTrace();
                mReportInterval = false;
                mErrorDispatched = true;
                SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                closeExecutors();
            } finally {
                mErrorDispatched = false;
                mSpeedTestMode = SpeedTestMode.NONE;
                disconnectFtp(ftpClient);
                if (uploadFile != null) {
                    try {
                        uploadFile.close();
                        randomGen.deleteFile();
                    } catch (IOException e) {
                        //e.printStackTrace();
                    }
                }
            }
        }
    });
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

public void importExternalStyleIntoProject(final File file, ProgressHandler progressHandler) {
    final String targetPath = currentWorkingPath + "/" + currentProjectVO.projectName + "/assets/orig/styles";
    FileHandle fileHandle = Gdx.files.absolute(file.getAbsolutePath());
    final MySkin skin = new MySkin(fileHandle);
    handler = progressHandler;//  ww w. j a va  2 s  .c om
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < skin.fontFiles.size(); i++) {
                File copyFontFile = new File(file.getParentFile(), skin.fontFiles.get(i) + ".fnt");
                File copyImageFile = new File(file.getParentFile(), skin.fontFiles.get(i) + ".png");
                if (file.isFile() && file.exists() && copyFontFile.isFile() && copyFontFile.exists()
                        && copyImageFile.isFile() && copyImageFile.exists()) {
                    File fileTarget = new File(targetPath + "/" + file.getName());
                    File fontTarget = new File(targetPath + "/" + copyFontFile.getName());
                    File imageTarget = new File(targetPath + "/" + copyImageFile.getName());
                    try {
                        FileUtils.copyFile(file, fileTarget);
                        FileUtils.copyFile(copyFontFile, fontTarget);
                        FileUtils.copyFile(copyImageFile, imageTarget);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("SOME FILES ARE MISSING");
                }
            }
        }
    });
    executor.execute(new Runnable() {
        @Override
        public void run() {
            changePercentBy(100 - currentPercent);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.progressComplete();
        }
    });
    executor.shutdown();
}

From source file:ca.uhn.hl7v2.testpanel.controller.Controller.java

public void start() {
    ourLog.info("Starting TestPanel Controller...");

    myExecutor = Executors.newSingleThreadExecutor();
    for (Runnable next : myQueuedTasks) {
        myExecutor.execute(next);//from w ww  .ja  va2  s .  c  o m
    }
    myQueuedTasks = null;

    myView = new TestPanelWindow(this);
    myView.getFrame().setVisible(true);

    String leftItemId = Prefs.getInstance().getMostRecentlySelectedItemId();
    if (isNotBlank(leftItemId)) {
        Object leftItem = myMessagesList.getWithId(leftItemId);
        leftItem = (leftItem != null) ? leftItem : myOutboundConnectionList.getWithId(leftItemId);
        leftItem = (leftItem != null) ? leftItem : myInboundConnectionList.getWithId(leftItemId);
        if (leftItem != null) {
            setLeftSelectedItem(leftItem);
        }
    }

    if (getLeftSelectedItem() == null) {
        if (myMessagesList.getMessages().size() > 0) {
            setLeftSelectedItem(myMessagesList.getMessages().get(0));
        } else {
            setLeftSelectedItem(myNothingSelectedMarker);
        }
    }

    new VersionChecker().start();

    Prefs.getInstance().setController(this);

}

From source file:com.hangum.tadpole.rdb.core.editors.main.composite.ResultSetComposite.java

/**
 *  ./*from  w w  w .  j a  va  2 s . c om*/
 * 
 * @param reqQuery
 * @param queryTimeOut
 * @param strUserEmail
 * @param intSelectLimitCnt
 * @param intStartCnt
 * @param strNullValue 
 * @return
 * @throws Exception
 */
public QueryExecuteResultDTO runSelect(final RequestQuery reqQuery, final int queryTimeOut,
        final String strUserEmail, final int intSelectLimitCnt, final int intStartCnt) throws Exception {
    String strSQL = reqQuery.getSql();
    if (!PermissionChecker.isExecute(getDbUserRoleType(), getUserDB(), strSQL)) {
        throw new Exception(Messages.get().MainEditor_21);
    }
    if (logger.isDebugEnabled())
        logger.debug("==> real execute query : " + strSQL);

    tadpole_system_message = "";
    QueryExecuteResultDTO queryResultDAO = null;

    //  ??   ???  .
    IMainEditorExtension[] extensions = getRdbResultComposite().getMainEditor().getMainEditorExtions();
    if (extensions != null) {
        for (IMainEditorExtension iMainEditorExtension : extensions) {
            String strCostumSQL = iMainEditorExtension.sqlCostume(strSQL);
            if (!strCostumSQL.equals(strSQL)) {
                if (logger.isDebugEnabled())
                    logger.debug("** extension costume sql is : " + strCostumSQL); //$NON-NLS-1$
                strSQL = strCostumSQL;
            }
        }
    }

    //  ??   ???  .
    ResultSet resultSet = null;
    java.sql.Connection javaConn = null;
    Statement statement = null;
    PreparedStatement preparedStatement = null;

    try {
        if (DBGroupDefine.TAJO_GROUP == getUserDB().getDBGroup()) {
            javaConn = ConnectionPoolManager.getDataSource(getUserDB()).getConnection();
        } else {
            if (reqQuery.isAutoCommit()) {
                SqlMapClient client = TadpoleSQLManager.getInstance(getUserDB());
                javaConn = client.getDataSource().getConnection();
            } else {
                javaConn = TadpoleSQLTransactionManager.getInstance(strUserEmail, getUserDB());
            }
        }
        if (javaConn == null) {
            throw new Exception("Cann't create session. Please check system.");
        }

        // if statement type is prepared statement?
        if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.NONE) {
            statement = javaConn.createStatement();

            statement.setFetchSize(intSelectLimitCnt);
            if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) {
                statement.setQueryTimeout(queryTimeOut);
                statement.setMaxRows(intSelectLimitCnt);
            }

            // check stop thread
            esCheckStop = Executors.newSingleThreadExecutor();
            CheckStopThread cst = new CheckStopThread(statement);
            cst.setName("TDB Query Stop checker"); //$NON-NLS-1$
            esCheckStop.execute(cst);

            // execute query
            execServiceQuery = Executors.newSingleThreadExecutor();
            if (intStartCnt == 0) {
                resultSet = _runSQLSelect(statement, strSQL);
            } else {
                strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt);

                if (logger.isDebugEnabled())
                    logger.debug("part sql called : " + strSQL);
                resultSet = _runSQLSelect(statement, strSQL);
            }

        } else if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.PREPARED_STATEMENT) {
            preparedStatement = javaConn.prepareStatement(strSQL);

            preparedStatement.setFetchSize(intSelectLimitCnt);
            if (DBGroupDefine.HIVE_GROUP != getUserDB().getDBGroup()) {
                preparedStatement.setQueryTimeout(queryTimeOut);
                preparedStatement.setMaxRows(intSelectLimitCnt);
            }

            // check stop thread
            esCheckStop = Executors.newSingleThreadExecutor();
            CheckStopThread cst = new CheckStopThread(preparedStatement);
            cst.setName("TDB Query Stop checker"); //$NON-NLS-1$
            esCheckStop.execute(cst);

            // execute query
            execServiceQuery = Executors.newSingleThreadExecutor();
            if (intStartCnt == 0) {
                resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter());
            } else {
                strSQL = PartQueryUtil.makeSelect(getUserDB(), strSQL, intStartCnt, intSelectLimitCnt);

                if (logger.isDebugEnabled())
                    logger.debug("part sql called : " + strSQL);
                resultSet = _runSQLSelect(preparedStatement, reqQuery.getStatementParameter());
            }
        }

        queryResultDAO = new QueryExecuteResultDTO(getUserDB(), reqQuery.getSql(), true, resultSet,
                intSelectLimitCnt, intStartCnt);
        if (resultSet == null) {
            if (StringUtils.isEmpty(StringUtils.deleteWhitespace(tadpole_system_message))) {
                tadpole_system_message = CMD_COMPLETE_MSG;
            }

        }
        queryResultDAO.setQueryMsg(tadpole_system_message);

    } catch (Exception e) {
        throw e;
    } finally {
        isCheckRunning = false;
        try {
            if (preparedStatement != null)
                preparedStatement.close();
        } catch (Exception e) {
        }
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (resultSet != null)
                resultSet.close();
        } catch (Exception e) {
        }

        if (reqQuery.isAutoCommit()) {
            try {
                if (javaConn != null)
                    javaConn.close();
            } catch (Exception e) {
            }
        }
    }

    return queryResultDAO;
}

From source file:com.example.android.cardreader.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alternate_main_fragment);

    //TODO Stop Executing Eden
    //Globals.executeEden();
    getUsers(1);/*from  ww  w.  ja  v  a  2s  .c om*/

    instance = this;
    final ActionBar actionBar = getActionBar();
    actionBar.setTitle("           TartanHacks");
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg));
    actionBar.setStackedBackgroundDrawable(getResources().getDrawable(R.drawable.tab_bg));
    actionBar.setDisplayShowHomeEnabled(true);

    frags.add(new PersonListFrag(Globals.pending));
    frags.add(new PersonListFrag(Globals.allUsers));
    frags.add(new PersonListFrag(Globals.checkedIn));

    mAdapter = new FragmentAdapter(getFragmentManager());

    fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View dialogView = View.inflate(instance, R.layout.dialog_signup, null);

            idField = (EditText) dialogView.findViewById(R.id.andrewIdField);
            pb = (ProgressBar) dialogView.findViewById(R.id.progress);
            nameField = (TextView) dialogView.findViewById(R.id.name);
            scanView = (TextView) dialogView.findViewById(R.id.scan_view);

            idField.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String id = s.toString();
                    pb.setVisibility(View.VISIBLE);
                    queryId(id);

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });

            AlertDialog.Builder builder;
            builder = new AlertDialog.Builder(instance);
            builder.setView(dialogView);
            builder.setCancelable(true);
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    Globals.adding = false;
                }
            });

            signupDialog = builder.show();
        }
    });

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOffscreenPageLimit(0);
    mViewPager.setAdapter(mAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When swiping between different app sections, select the corresponding tab.
            // We can also use ActionBar.Tab#select() to do this if we have a reference to the
            // Tab.
            actionBar.setSelectedNavigationItem(position);
        }
    });

    actionBar.addTab(actionBar.newTab().setText("Pending").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("All").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText("Checked In").setTabListener(this));

    mLoyaltyCardReader = new LoyaltyCardReader(this);

    // Disable Android Beam and register our card reader callback
    enableReaderMode();

    new UpdateThread().executeOnExecutor(Executors.newSingleThreadExecutor());
}

From source file:de.mendelson.comm.as2.client.AS2Gui.java

/**Starts a dialog that allows to send files manual to a partner
  *///from  www  .  ja  v  a  2s  .c o  m
private void sendFileManualFromSelectedTransaction() {
    if (this.configConnection == null) {
        return;
    }
    int requestValue = JOptionPane.showConfirmDialog(this, this.rb.getResourceString("dialog.resend.message"),
            this.rb.getResourceString("dialog.resend.title"), JOptionPane.YES_NO_OPTION);
    if (requestValue != JOptionPane.YES_OPTION) {
        return;
    }
    final String uniqueId = this.getClass().getName() + ".sendFileManualFromSelectedTransaction."
            + System.currentTimeMillis();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            File tempFile = null;
            try {
                AS2Gui.this.as2StatusBar.startProgressIndeterminate(
                        AS2Gui.this.rb.getResourceString("menu.file.resend"), uniqueId);
                int selectedRow = AS2Gui.this.jTableMessageOverview.getSelectedRow();
                if (selectedRow >= 0) {
                    //download the payload for the selected message
                    MessageAccessDB messageAccess = new MessageAccessDB(AS2Gui.this.configConnection,
                            AS2Gui.this.runtimeConnection);
                    JDialogManualSend dialog = new JDialogManualSend(AS2Gui.this, AS2Gui.this.configConnection,
                            AS2Gui.this.runtimeConnection, AS2Gui.this.getBaseClient(),
                            AS2Gui.this.as2StatusBar, AS2Gui.this.rb.getResourceString("uploading.to.server"));
                    AS2Message message = ((TableModelMessageOverview) AS2Gui.this.jTableMessageOverview
                            .getModel()).getRow(selectedRow);
                    if (message != null) {
                        AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
                        PartnerAccessDB partnerAccess = new PartnerAccessDB(AS2Gui.this.configConnection,
                                AS2Gui.this.runtimeConnection);
                        Partner sender = partnerAccess.getPartner(info.getSenderId());
                        Partner receiver = partnerAccess.getPartner(info.getReceiverId());
                        List<AS2Payload> payloads = messageAccess.getPayload(info.getMessageId());
                        for (AS2Payload payload : payloads) {
                            message.addPayload(payload);
                        }
                        if (message.getPayloadCount() > 0) {
                            AS2Payload payload = message.getPayload(0);
                            //request the payload file from the server
                            TransferClientWithProgress transferClient = new TransferClientWithProgress(
                                    AS2Gui.this.getBaseClient(), AS2Gui.this.as2StatusBar.getProgressPanel());
                            DownloadRequestFile request = new DownloadRequestFile();
                            request.setFilename(payload.getPayloadFilename());
                            InputStream inStream = null;
                            OutputStream outStream = null;
                            try {
                                DownloadResponseFile response = (DownloadResponseFile) transferClient
                                        .download(request);
                                if (response.getException() != null) {
                                    throw response.getException();
                                }
                                String tempFilename = "as2.bin";
                                if (payload.getOriginalFilename() != null) {
                                    tempFilename = payload.getOriginalFilename();
                                }
                                tempFile = AS2Tools.createTempFile(tempFilename, "");
                                outStream = new FileOutputStream(tempFile);
                                inStream = response.getDataStream();
                                AS2Gui.this.copyStreams(inStream, outStream);
                                outStream.flush();
                            } catch (Throwable e) {
                                AS2Gui.this.logger.severe(e.getMessage());
                                return;
                            } finally {
                                if (inStream != null) {
                                    try {
                                        inStream.close();
                                    } catch (Exception e) {
                                    }
                                }
                                if (outStream != null) {
                                    try {
                                        outStream.close();
                                    } catch (Exception e) {
                                    }
                                }
                            }
                            dialog.initialize(sender, receiver, tempFile.getAbsolutePath());
                        }
                        dialog.performSend();
                        info.setResendCounter(info.getResendCounter() + 1);
                        messageAccess.updateResendCounter(info);
                        Logger.getLogger(AS2Server.SERVER_LOGGER_NAME).log(Level.INFO,
                                AS2Gui.this.rb.getResourceString("resend.performed"), info);
                    }
                    AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                }
            } catch (Throwable e) {
                //nop
            } finally {
                AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                if (tempFile != null) {
                    tempFile.delete();
                }
            }

        }
    };
    Executors.newSingleThreadExecutor().submit(runnable);
}

From source file:de.mendelson.comm.as2.client.AS2Gui.java

private void displayPartnerDialog() {
    final String uniqueId = this.getClass().getName() + ".displayPartnerDialog." + System.currentTimeMillis();
    Runnable runnable = new Runnable() {

        @Override//  www .  j a  va 2  s .c  o  m
        public void run() {
            JDialogPartnerConfig dialog = null;
            try {
                //display wait indicator
                AS2Gui.this.as2StatusBar.startProgressIndeterminate(
                        AS2Gui.this.rb.getResourceString("menu.file.partner"), uniqueId);
                dialog = new JDialogPartnerConfig(AS2Gui.this, AS2Gui.this.configConnection,
                        AS2Gui.this.runtimeConnection, AS2Gui.this, AS2Gui.this.as2StatusBar);
                dialog.setDisplayNotificationPanel(false);
                dialog.setDisplayHttpHeaderPanel(false);
            } finally {
                AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                if (dialog != null) {
                    dialog.setVisible(true);
                }
            }
        }
    };
    Executors.newSingleThreadExecutor().submit(runnable);
}

From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java

public final Page getInsecurePage(String url) throws IOException, ExecutionException, TimeoutException {
    final WebRequest req = insecurePageInitialization(url);
    long processingTime = System.currentTimeMillis();
    ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<Page> f = ex.submit(new Callable<Page>() {
        @Override/*from   w  w w .j  av  a 2 s . c om*/
        public Page call() throws IOException {
            ctx.addTimeAttribute("download_time_start", System.currentTimeMillis());
            Page page = wc.getPage(req);
            ctx.addTimeAttribute("download_time_end", System.currentTimeMillis());
            return page;
        }
    });
    Page page = null;
    try {
        if (!interruptProcessing) {
            if (taskParams.getPageTimeoutMillis() <= 0) {
                page = f.get();
            } else {
                page = f.get(taskParams.getPageTimeoutMillis(), TimeUnit.MILLISECONDS);
            }
        }
    } catch (InterruptedException e) {
        LOGGER.warn("Gathering {} interrupted", url);
        Thread.currentThread().interrupt();
    } catch (java.util.concurrent.TimeoutException e) {
        throw new TimeoutException(
                "Timeout when gathering (" + taskParams.getPageTimeoutMillis() + " ms):" + url, e);
    } finally {
        if (f != null) {
            f.cancel(true);
        }
        closeExecutorWithJSDisabled(ex);
    }
    processingTime = System.currentTimeMillis() - processingTime;
    insecurePagePostprocessing(url, processingTime, page);
    return page;
}

From source file:de.mendelson.comm.as2.client.AS2Gui.java

private void displayHelpSystem() {
    if (this.helpHasBeenDisplayed) {
        this.help.setVisible(true);
    } else {//ww  w  .j  a v  a  2s . c o m
        final String uniqueId = this.getClass().getName() + ".displayHelpSystem." + System.currentTimeMillis();
        Runnable test = new Runnable() {

            @Override
            public void run() {
                try {
                    //display wait indicator
                    AS2Gui.this.as2StatusBar.startProgressIndeterminate(
                            AS2Gui.this.rb.getResourceString("menu.help.helpsystem"), uniqueId);
                    AS2Gui.this.help.showTopic(AS2Gui.this.helpSet, "as2_main");
                } finally {
                    AS2Gui.this.as2StatusBar.stopProgressIfExists(uniqueId);
                    AS2Gui.this.helpHasBeenDisplayed = true;
                }
            }
        };
        Executors.newSingleThreadExecutor().submit(test);
    }
}