001/*
002 * JPPF.
003 * Copyright (C) 2005-2015 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 java.util.*;
022
023import org.jppf.client.*;
024import org.jppf.jca.cci.*;
025import org.jppf.node.protocol.Task;
026
027/**
028 * Instances of this class encapsulate a simple call to the JPPF resource adapter.
029 * @author Laurent Cohen
030 */
031public class J2EEDemo {
032  /**
033   * JNDI name of the JPPFConnectionFactory.
034   */
035  private final String jndiBinding;
036
037  /**
038   * Initialize this test object with a specified jndi location for the connection factory.
039   * @param jndiBinding JNDI name of the JPPFConnectionFactory.
040   */
041  public J2EEDemo(final String jndiBinding) {
042    this.jndiBinding = jndiBinding;
043  }
044
045  /**
046   * Perform a simple call to the JPPF resource adapter.
047   * @param duration the duration of the task to submit.
048   * @return a string reporting either the task execution result or an error message.
049   * @throws Exception if the call to JPPF failed.
050   */
051  public String testConnector(final int duration) throws Exception {
052    JPPFConnection connection = null;
053    String id = null;
054    try {
055      connection = JPPFHelper.getConnection(jndiBinding);
056      JPPFJob job = new JPPFJob();
057      job.add(new DemoTask(duration));
058      id = connection.submit(job);
059    } finally {
060      if (connection != null) JPPFHelper.closeConnection(connection);
061    }
062    return id;
063  }
064
065  /**
066   * Perform a simple call to the JPPF resource adapter.
067   * @param jobId the name given to the job.
068   * @param duration the duration of the task to submit.
069   * @param nbTasks the number of tasks to submit.
070   * @return a string reporting either the task execution result or an error message.
071   * @throws Exception if the call to JPPF failed.
072   */
073  public String testConnector(final String jobId, final long duration, final int nbTasks) throws Exception {
074    JPPFConnection connection = null;
075    JPPFJob job = null;
076    String id = null;
077    try {
078      connection = JPPFHelper.getConnection(jndiBinding);
079      job = new JPPFJob();
080      job.setName(jobId);
081      for (int i=1; i<=nbTasks; i++) {
082        DemoTask task = new DemoTask(duration);
083        task.setId(jobId + " task #" + (i + 1));
084        job.add(task);
085      }
086      id = connection.submit(job);
087    } finally {
088      if (connection != null) JPPFHelper.closeConnection(connection);
089    }
090    JPPFHelper.getStatusMap().put(id, job);
091    return id;
092  }
093
094  /**
095   * Perform a simple call to the JPPF resource adapter.
096   * @param nbJobs the number of jobs to submit.
097   * @param jobNamePrefix the prefix of the name given to each job.
098   * @param duration the duration of each task to submit.
099   * @param nbTasks the number of tasks to submit for each job.
100   * @param blocking whether th jobs are blocking or not.
101   * @return a string reporting either the task execution result or an error message.
102   * @throws Exception if the call to JPPF failed.
103   */
104  public String testMultipleJobs(final int nbJobs, final String jobNamePrefix, final long duration, final int nbTasks, final boolean blocking) throws Exception {
105    if (nbJobs <= 0) return "Error: the number of jobs must be >= 1";
106    if (nbTasks <= 0) return "Error: the number of tasks must be >= 1";
107    if (duration <= 0L) return "Error: the duration must be >= 1";
108    String prefix = (jobNamePrefix == null) ? "(No name)" : jobNamePrefix;
109    JPPFConnection connection = null;
110    String id = null;
111    List<String> idList = new ArrayList<>();
112    try {
113      JPPFConnectionFactory factory = JPPFHelper.getConnectionFactory(jndiBinding);
114      boolean available = factory.isJPPFDriverAvailable();
115      // enable local execution, depending on whether a remote connection is available or not.
116      if (!available) System.out.println("No available JPPF driver, jobs will be executed locally");
117      factory.enableLocalExecution(!available);
118      connection = (JPPFConnection) factory.getConnection();
119      for (int n=1; n<=nbJobs; n++) {
120        JPPFJob job = new JPPFJob();
121        String name = jobNamePrefix + ' ' + n;
122        job.setName(name);
123        job.setBlocking(false);
124        for (int i=1; i<=nbTasks; i++) job.add(new DemoTask(duration)).setId(name + " task " + i);
125        id = connection.submit(job);
126        idList.add(id);
127        JPPFHelper.getStatusMap().put(id, job);
128        if (blocking) connection.awaitResults(id);
129      }
130    } finally {
131      if (connection != null) JPPFHelper.closeConnection(connection);
132    }
133    return "success";
134  }
135
136  /**
137   * Perform a simple call to the JPPF resource adapter.
138   * This method blocks until all job results have been received.
139   * @param jobId the name given to the job.
140   * @param duration the duration of the task to submit.
141   * @param nbTasks the number of tasks to submit.
142   * @return a string reporting either the task execution result or an error message.
143   * @throws Exception if the call to JPPF failed.
144   */
145  public String testConnectorBlocking(final String jobId, final long duration, final int nbTasks) throws Exception {
146    JPPFConnection connection = null;
147    JPPFJob job = null;
148    String id = null;
149    try {
150      connection = JPPFHelper.getConnection(jndiBinding);
151      job = new JPPFJob();
152      job.setName(jobId);
153      for (int i=1; i<=nbTasks; i++) {
154        DemoTask task = new DemoTask(duration);
155        task.setId(jobId + " task #" + i);
156        job.add(task);
157      }
158      id = connection.submit(job);
159      List<Task<?>> results = connection.awaitResults(id);
160      System.out.println("received " + results.size() + " results for job '" + job.getName() + "'");
161    } finally {
162      if (connection != null) JPPFHelper.closeConnection(connection);
163    }
164    JPPFHelper.getStatusMap().put(id, job);
165    return id;
166  }
167
168  /**
169   * Get the map of job uuids to their corresponding job status.
170   * @return a map of ids to statuses as strings.
171   * @throws Exception if the call to JPPF failed.
172   */
173  public Map getStatusMap() throws Exception {
174    Map<String, String> map = new HashMap<>();
175    JPPFConnection connection = null;
176    try {
177      connection = JPPFHelper.getConnection(jndiBinding);
178      Collection<String> coll = connection.getAllJobIds();
179      for (String id : coll) {
180        JobStatus status = connection.getJobStatus(id);
181        String s = (status == null) ? "Unknown" : status.toString();
182        map.put(id, s);
183      }
184    } finally {
185      if (connection != null) JPPFHelper.closeConnection(connection);
186    }
187    return map;
188  }
189
190  /**
191   * Get the resulting message from a submission.
192   * @param id the id of the submission to retrieve.
193   * @return a string reporting either the task execution result or an error message.
194   * @throws Exception if the call to JPPF failed.
195   */
196  public String getMessage(final String id) throws Exception {
197    JPPFConnection connection = null;
198    String msg = null;
199    try {
200      connection = JPPFHelper.getConnection(jndiBinding);
201      List<Task<?>> results = connection.getResults(id);
202      if (results == null) msg = "submission is not in queue anymore";
203      else {
204        StringBuilder sb = new StringBuilder();
205        for (Task task : results) {
206          if (task.getThrowable() == null) sb.append(task.getResult());
207          else sb.append("task [").append(task.getId()).append("] ended in error: ").append(task.getThrowable().getMessage());
208          sb.append("<br/>");
209        }
210        msg = sb.toString();
211      }
212    } finally {
213      if (connection != null) JPPFHelper.closeConnection(connection);
214    }
215    return msg;
216  }
217}