Example usage for java.util Timer cancel

List of usage examples for java.util Timer cancel

Introduction

In this page you can find the example usage for java.util Timer cancel.

Prototype

public void cancel() 

Source Link

Document

Terminates this timer, discarding any currently scheduled tasks.

Usage

From source file:net.sf.taverna.t2.reference.ReferenceServiceTest.java

@Test
/**//from   ww  w .j a v  a  2 s  .  co m
 * Test multiple concurrent read / write cycles to the database, producing
 * some rather informal profiling information at the end.
 */
public void testSaturatedReadWriteCycle() throws MalformedURLException {
    int concurrentThreads = 5;
    final int jobsPerThread = 200;
    int joinPoints = 5;
    final URL testUrl = new URL("http://www.ebi.ac.uk/~tmo/patterns.xml");
    ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
            "referenceServiceTestContext.xml");
    //      ApplicationContext context = new RavenAwareClassPathXmlApplicationContext(
    //      "inMemoryReferenceServiceTestContext.xml");
    final ReferenceService rs = (ReferenceService) context.getBean("t2reference.service.referenceService");
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private int lastCount = getCount();
        private long lastTime = System.currentTimeMillis();

        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            long interval = currentTime - lastTime;
            lastTime = currentTime;
            int newCount = getCount();
            long jobsProcessed = (long) (newCount - lastCount);
            lastCount = newCount;
            if (interval == 0) {
                System.out.println("(infinity) " + jobsProcessed);
            } else {
                System.out.println((int) (jobsProcessed * 1000 / interval));
            }
        }
    }, 1000, 1000);
    long testStartTime = System.currentTimeMillis();
    for (int i = 0; i < joinPoints; i++) {
        Thread[] threads = new Thread[concurrentThreads];
        for (int j = 0; j < concurrentThreads; j++) {
            threads[j] = new Thread() {
                @Override
                public void run() {
                    for (int k = 0; k < jobsPerThread; k++) {
                        try {
                            //                        T2Reference ref = rs.register("test", 0, true,
                            //                              dummyContext);
                            T2Reference ref = rs.register(testUrl, 0, true, dummyContext);
                            @SuppressWarnings("unused")
                            ReferenceSet refSet = (ReferenceSet) rs.resolveIdentifier(ref, null, dummyContext);
                            incrementRequestsProcessed();
                        } catch (ReferenceServiceException rse) {
                            System.out.println(rse);
                        }
                    }
                }
            };
            threads[j].start();
        }
        for (int j = 0; j < concurrentThreads; j++) {
            try {
                threads[j].join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    timer.cancel();
    System.out.println("Test completed, using " + concurrentThreads + " threads, " + getCount() + " at "
            + (long) ((getCount() * 1000) / (System.currentTimeMillis() - testStartTime))
            + " jobs per second averaged over test run");
    System.out.println((System.currentTimeMillis() - testStartTime));
    System.out.println((System.currentTimeMillis() - testStartTime) / (float) (jobsPerThread * joinPoints));
}

From source file:com.easemob.chatui.adapter.MessageAdapter.java

/**
 * ?/* www.  j  av  a  2s.co  m*/
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult((new Intent(activity, ContextMenu.class))
                    .putExtra("position", position).putExtra("type", EMMessage.Type.IMAGE.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    // ??
    if (message.direct == Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.drawable.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                if (TextUtils.isEmpty(thumbRemoteUrl) && !TextUtils.isEmpty(remotePath)) {
                    thumbRemoteUrl = remotePath;
                }
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(R.string.send_fail)
                                    + activity.getString(R.string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}

From source file:org.apache.flink.runtime.state.StateBackendTestBase.java

/**
 * Tests {@link ValueState#value()} and {@link InternalKvState#getSerializedValue(byte[])}
 * accessing the state concurrently. They should not get in the way of each
 * other.// www  .j a  va 2  s  .  c  o  m
 */
@Test
@SuppressWarnings("unchecked")
public void testValueStateRace() throws Exception {
    final AbstractKeyedStateBackend<Integer> backend = createKeyedBackend(IntSerializer.INSTANCE);
    final Integer namespace = 1;

    final ValueStateDescriptor<String> kvId = new ValueStateDescriptor<>("id", String.class);
    kvId.initializeSerializerUnlessSet(new ExecutionConfig());

    final TypeSerializer<Integer> keySerializer = IntSerializer.INSTANCE;
    final TypeSerializer<Integer> namespaceSerializer = IntSerializer.INSTANCE;
    final TypeSerializer<String> valueSerializer = kvId.getSerializer();

    final ValueState<String> state = backend.getPartitionedState(namespace, IntSerializer.INSTANCE, kvId);

    @SuppressWarnings("unchecked")
    final InternalKvState<Integer> kvState = (InternalKvState<Integer>) state;

    /**
     * 1) Test that ValueState#value() before and after
     * KvState#getSerializedValue(byte[]) return the same value.
     */

    // set some key and namespace
    final int key1 = 1;
    backend.setCurrentKey(key1);
    kvState.setCurrentNamespace(2);
    state.update("2");
    assertEquals("2", state.value());

    // query another key and namespace
    assertNull(
            getSerializedValue(kvState, 3, keySerializer, namespace, IntSerializer.INSTANCE, valueSerializer));

    // the state should not have changed!
    assertEquals("2", state.value());

    // re-set values
    kvState.setCurrentNamespace(namespace);

    /**
     * 2) Test two threads concurrently using ValueState#value() and
     * KvState#getSerializedValue(byte[]).
     */

    // some modifications to the state
    final int key2 = 10;
    backend.setCurrentKey(key2);
    assertNull(state.value());
    assertNull(
            getSerializedValue(kvState, key2, keySerializer, namespace, namespaceSerializer, valueSerializer));
    state.update("1");

    final CheckedThread getter = new CheckedThread("State getter") {
        @Override
        public void go() throws Exception {
            while (!isInterrupted()) {
                assertEquals("1", state.value());
            }
        }
    };

    final CheckedThread serializedGetter = new CheckedThread("Serialized state getter") {
        @Override
        public void go() throws Exception {
            while (!isInterrupted() && getter.isAlive()) {
                final String serializedValue = getSerializedValue(kvState, key2, keySerializer, namespace,
                        namespaceSerializer, valueSerializer);
                assertEquals("1", serializedValue);
            }
        }
    };

    getter.start();
    serializedGetter.start();

    // run both threads for max 100ms
    Timer t = new Timer("stopper");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            getter.interrupt();
            serializedGetter.interrupt();
            this.cancel();
        }
    }, 100);

    // wait for both threads to finish
    try {
        // serializedGetter will finish if its assertion fails or if
        // getter is not alive any more
        serializedGetter.sync();
        // if serializedGetter crashed, getter will not know -> interrupt just in case
        getter.interrupt();
        getter.sync();
        t.cancel(); // if not executed yet
    } finally {
        // clean up
        backend.dispose();
    }
}

From source file:com.aibasis.parent.adapter.MessageAdapter.java

/**
 * ?//from   w w  w  . j a va  2  s .  c  o m
 * 
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // final File image=new File(PathUtil.getInstance().getVideoPath(),
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", EMMessage.Type.VIDEO.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(R.drawable.video_download_btn_nor);

    if (message.direct == EMMessage.Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == EMMessage.Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(R.drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(R.string.send_fail)
                                    + activity.getString(R.string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

From source file:cn.hbm.superwechat.adapter.MessageAdapter.java

/**
 * ?//from  w  ww.  ja v a2s .  c  om
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", EMMessage.Type.VIDEO.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(R.drawable.video_download_btn_nor);

    if (message.direct == EMMessage.Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == EMMessage.Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(R.drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

From source file:cn.ucai.superwechat.adapter.MessageAdapter.java

/**
 * ?// ww  w.  j a  va 2 s .  com
 * 
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // final File image=new File(PathUtil.getInstance().getVideoPath(),
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", EMMessage.Type.VIDEO.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(cn.ucai.superwechat.R.drawable.video_download_btn_nor);

    if (message.direct == EMMessage.Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == EMMessage.Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(cn.ucai.superwechat.R.drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(cn.ucai.superwechat.R.drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(cn.ucai.superwechat.R.string.send_fail) + activity
                                            .getString(cn.ucai.superwechat.R.string.connect_failuer_toast),
                                    Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

From source file:com.shengtao.chat.chatUI.adapter.MessageAdapter.java

/**
 * ?//w  w w. j  av  a 2  s .  c  o m
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleImageMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {
    holder.pb.setTag(position);
    holder.iv.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult((new Intent(activity, ContextMenu.class))
                    .putExtra("position", position).putExtra("type", Type.IMAGE.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    // ??
    if (message.direct == Direct.RECEIVE) {
        // "it is receive msg";
        if (message.status == EMMessage.Status.INPROGRESS) {
            // "!!!! back receive";
            holder.iv.setImageResource(drawable.default_image);
            showDownloadImageProgress(message, holder);
            // downloadImage(message, holder);
        } else {
            // "!!!! not back receive, show image directly");
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(drawable.default_image);
            ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
            if (imgBody.getLocalUrl() != null) {
                // String filePath = imgBody.getLocalUrl();
                String remotePath = imgBody.getRemoteUrl();
                String filePath = ImageUtils.getImagePath(remotePath);
                String thumbRemoteUrl = imgBody.getThumbnailUrl();
                if (TextUtils.isEmpty(thumbRemoteUrl) && !TextUtils.isEmpty(remotePath)) {
                    thumbRemoteUrl = remotePath;
                }
                String thumbnailPath = ImageUtils.getThumbnailImagePath(thumbRemoteUrl);
                showImageView(thumbnailPath, holder.iv, filePath, imgBody.getRemoteUrl(), message);
            }
        }
        return;
    }

    // ???
    // process send message
    // send pic, show the pic directly
    ImageMessageBody imgBody = (ImageMessageBody) message.getBody();
    String filePath = imgBody.getLocalUrl();
    if (filePath != null && new File(filePath).exists()) {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, null, message);
    } else {
        showImageView(ImageUtils.getThumbnailImagePath(filePath), holder.iv, filePath, IMAGE_DIR, message);
    }

    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        holder.staus_iv.setVisibility(View.GONE);
        holder.pb.setVisibility(View.VISIBLE);
        holder.tv.setVisibility(View.VISIBLE);
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(string.send_fail)
                                    + activity.getString(string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        sendPictureMessage(message, holder);
    }
}

From source file:com.easemob.chatui.adapter.MessageAdapter.java

/**
 * ?/*from  w  ww . j  a  v  a  2s  .  com*/
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleVideoMessage(final EMMessage message, final ViewHolder holder, final int position,
        View convertView) {

    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
    // final File image=new File(PathUtil.getInstance().getVideoPath(),
    // videoBody.getFileName());
    String localThumb = videoBody.getLocalThumb();

    holder.iv.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            activity.startActivityForResult(new Intent(activity, ContextMenu.class)
                    .putExtra("position", position).putExtra("type", EMMessage.Type.VIDEO.ordinal()),
                    ChatActivity.REQUEST_CODE_CONTEXT_MENU);
            return true;
        }
    });

    if (localThumb != null) {

        showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
    }
    if (videoBody.getLength() > 0) {
        String time = DateUtils.toTimeBySecond(videoBody.getLength());
        holder.timeLength.setText(time);
    }
    holder.playBtn.setImageResource(R.drawable.video_download_btn_nor);

    if (message.direct == Direct.RECEIVE) {
        if (videoBody.getVideoFileLength() > 0) {
            String size = TextFormater.getDataSize(videoBody.getVideoFileLength());
            holder.size.setText(size);
        }
    } else {
        if (videoBody.getLocalUrl() != null && new File(videoBody.getLocalUrl()).exists()) {
            String size = TextFormater.getDataSize(new File(videoBody.getLocalUrl()).length());
            holder.size.setText(size);
        }
    }

    if (message.direct == Direct.RECEIVE) {

        // System.err.println("it is receive msg");
        if (message.status == EMMessage.Status.INPROGRESS) {
            // System.err.println("!!!! back receive");
            holder.iv.setImageResource(R.drawable.default_image);
            showDownloadImageProgress(message, holder);

        } else {
            // System.err.println("!!!! not back receive, show image directly");
            holder.iv.setImageResource(R.drawable.default_image);
            if (localThumb != null) {
                showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
            }

        }

        return;
    }
    holder.pb.setTag(position);

    // until here ,deal with send video msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.GONE);
        holder.tv.setVisibility(View.GONE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.GONE);
                            holder.tv.setVisibility(View.GONE);
                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                            // message.setProgress(0);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity, activity.getString(R.string.send_fail)
                                    + activity.getString(R.string.connect_failuer_toast), 0).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // sendMsgInBackground(message, holder);
        sendPictureMessage(message, holder);

    }

}

From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java

/**
 * ?// w  w w . j  a va  2s  . c o  m
 *
 * @param message
 * @param holder
 * @param position
 * @param convertView
 */
private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position,
        View convertView) {
    final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
    final String filePath = fileMessageBody.getLocalUrl();
    holder.tv_file_name.setText(fileMessageBody.getFileName());
    holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize()));
    holder.ll_container.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            File file = new File(filePath);
            if (file != null && file.exists()) {
                // 
                FileUtils.openFile(file, (Activity) context);
            } else {
                // 
                context.startActivity(
                        new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody));
            }
            if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                    && message.getChatType() != ChatType.GroupChat
                    && message.getChatType() != ChatType.ChatRoom) {
                try {
                    EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                    message.isAcked = true;
                } catch (EaseMobException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });
    String st1 = context.getResources().getString(R.string.Have_downloaded);
    String st2 = context.getResources().getString(R.string.Did_not_download);
    if (message.direct == EMMessage.Direct.RECEIVE) { // ?
        EMLog.d(TAG, "it is receive msg");
        File file = new File(filePath);
        if (file != null && file.exists()) {
            holder.tv_file_download_state.setText(st1);
        } else {
            holder.tv_file_download_state.setText(st2);
        }
        return;
    }

    // until here, deal with send voice msg
    switch (message.status) {
    case SUCCESS:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        holder.staus_iv.setVisibility(View.INVISIBLE);
        break;
    case FAIL:
        holder.pb.setVisibility(View.INVISIBLE);
        holder.tv.setVisibility(View.INVISIBLE);
        holder.staus_iv.setVisibility(View.VISIBLE);
        break;
    case INPROGRESS:
        if (timers.containsKey(message.getMsgId()))
            return;
        // set a timer
        final Timer timer = new Timer();
        timers.put(message.getMsgId(), timer);
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        holder.pb.setVisibility(View.VISIBLE);
                        holder.tv.setVisibility(View.VISIBLE);
                        holder.tv.setText(message.progress + "%");
                        if (message.status == EMMessage.Status.SUCCESS) {
                            holder.pb.setVisibility(View.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            timer.cancel();
                        } else if (message.status == EMMessage.Status.FAIL) {
                            holder.pb.setVisibility(View.INVISIBLE);
                            holder.tv.setVisibility(View.INVISIBLE);
                            holder.staus_iv.setVisibility(View.VISIBLE);
                            Toast.makeText(activity,
                                    activity.getString(R.string.send_fail)
                                            + activity.getString(R.string.connect_failuer_toast),
                                    Toast.LENGTH_LONG).show();
                            timer.cancel();
                        }

                    }
                });

            }
        }, 0, 500);
        break;
    default:
        // ???
        sendMsgInBackground(message, holder);
    }

}

From source file:org.apache.hadoop.chukwa.inputtools.mdl.TorqueInfoProcessor.java

private void getHodJobInfo() throws IOException {
    StringBuffer sb = new StringBuffer();
    sb.append(torqueBinDir).append("/qstat -a");

    String[] getQueueInfoCommand = new String[3];
    getQueueInfoCommand[0] = "ssh";
    getQueueInfoCommand[1] = torqueServer;
    getQueueInfoCommand[2] = sb.toString();

    String command = getQueueInfoCommand[0] + " " + getQueueInfoCommand[1] + " " + getQueueInfoCommand[2];
    ProcessBuilder pb = new ProcessBuilder(getQueueInfoCommand);

    Process p = pb.start();//from   www .ja v a2  s .com

    Timer timeout = new Timer();
    TorqueTimerTask torqueTimerTask = new TorqueTimerTask(p, command);
    timeout.schedule(torqueTimerTask, TorqueTimerTask.timeoutInterval * 1000);

    BufferedReader result = new BufferedReader(new InputStreamReader(p.getInputStream()));
    ErStreamHandler errorHandler = new ErStreamHandler(p.getErrorStream(), command, true);
    errorHandler.start();

    String line = null;
    boolean start = false;
    TreeSet<String> jobsInTorque = new TreeSet<String>();
    while ((line = result.readLine()) != null) {
        if (line.startsWith("---")) {
            start = true;
            continue;
        }

        if (start) {
            String[] items = line.split("\\s+");
            if (items.length >= 10) {
                String hodIdLong = items[0];
                String hodId = hodIdLong.split("[.]")[0];
                String userId = items[1];
                String numOfMachine = items[5];
                String status = items[9];
                jobsInTorque.add(hodId);
                if (!currentHodJobs.containsKey(hodId)) {
                    TreeMap<String, String> aJobData = new TreeMap<String, String>();

                    aJobData.put("userId", userId);
                    aJobData.put("numOfMachine", numOfMachine);
                    aJobData.put("traceCheckCount", "0");
                    aJobData.put("process", "0");
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } else {
                    TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
                    aJobData.put("status", status);
                    currentHodJobs.put(hodId, aJobData);
                } // if..else
            }
        }
    } // while

    try {
        errorHandler.join();
    } catch (InterruptedException ie) {
        log.error(ie.getMessage());
    }
    timeout.cancel();

    Set<String> currentHodJobIds = currentHodJobs.keySet();
    Iterator<String> currentHodJobIdsIt = currentHodJobIds.iterator();
    TreeSet<String> finishedHodIds = new TreeSet<String>();
    while (currentHodJobIdsIt.hasNext()) {
        String hodId = currentHodJobIdsIt.next();
        if (!jobsInTorque.contains(hodId)) {
            TreeMap<String, String> aJobData = currentHodJobs.get(hodId);
            String process = aJobData.get("process");
            if (process.equals("0") || process.equals("1")) {
                aJobData.put("status", "C");
            } else {
                finishedHodIds.add(hodId);
            }
        }
    } // while

    Iterator<String> finishedHodIdsIt = finishedHodIds.iterator();
    while (finishedHodIdsIt.hasNext()) {
        String hodId = finishedHodIdsIt.next();
        currentHodJobs.remove(hodId);
    }

}