001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.jca.demo;
020
021import org.jppf.node.protocol.AbstractTask;
022
023/**
024 * Demonstration task to test the resource adaptor.
025 * @author Laurent Cohen
026 */
027public class DemoTask extends AbstractTask<String> {
028  /**
029   * Explicit serialVersionUID.
030   */
031  private static final long serialVersionUID = -6106765904127535863L;
032  /**
033   * Duration of this task in milliseconds.
034   */
035  private final long duration;
036
037  /**
038   * Initialize this task withe specified duration.
039   * @param duration duration of this task in milliseconds.
040   */
041  public DemoTask(final long duration) {
042    this.duration = duration < 1L ? 1L : duration;
043  }
044
045  /**
046   * Run this task.
047   */
048  @Override
049  public void run() {
050    final String execType = isInNode() ? "remotely" : "locally";
051    final long start = System.nanoTime();
052    try {
053      synchronized(this) {
054        wait(duration);
055      }
056      final double elapsed = (System.nanoTime() - start) / 1e9d;
057      final String s = String.format("JPPF task [%s] successfully completed %s after %.3f seconds", getId(), execType, elapsed);
058      System.out.println(s);
059      setResult(s);
060    } catch (final InterruptedException e) {
061      final double elapsed = (System.nanoTime() - start) / 1e9d;
062      setThrowable(e);
063      final String s = String.format("Exception for task [%s] executed %s after %.3f seconds : %s: %s", getId(), execType, elapsed, e.getClass().getName(), e.getMessage());
064      setResult(s);
065      System.out.println(s);
066    }
067  }
068}