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 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      final 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=0; i<nbTasks; i++) {
082        final 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    JPPFConnection connection = null;
109    String id = null;
110    final List<String> idList = new ArrayList<>();
111    try {
112      final JPPFConnectionFactory factory = JPPFHelper.getConnectionFactory(jndiBinding);
113      final boolean available = factory.isJPPFDriverAvailable();
114      // enable local execution, depending on whether a remote connection is available or not.
115      if (!available) System.out.println("No available JPPF driver, jobs will be executed locally");
116      factory.enableLocalExecution(!available);
117      connection = (JPPFConnection) factory.getConnection();
118      for (int n=1; n<=nbJobs; n++) {
119        final JPPFJob job = new JPPFJob();
120        final String name = jobNamePrefix + ' ' + n;
121        job.setName(name);
122        job.setBlocking(false);
123        for (int i=1; i<=nbTasks; i++) job.add(new DemoTask(duration)).setId(name + " task " + i);
124        id = connection.submit(job);
125        idList.add(id);
126        JPPFHelper.getStatusMap().put(id, job);
127        if (blocking) connection.awaitResults(id);
128      }
129    } finally {
130      if (connection != null) JPPFHelper.closeConnection(connection);
131    }
132    return "success";
133  }
134
135  /**
136   * Perform a simple call to the JPPF resource adapter.
137   * This method blocks until all job results have been received.
138   * @param jobId the name given to the job.
139   * @param duration the duration of the task to submit.
140   * @param nbTasks the number of tasks to submit.
141   * @return a string reporting either the task execution result or an error message.
142   * @throws Exception if the call to JPPF failed.
143   */
144  public String testConnectorBlocking(final String jobId, final long duration, final int nbTasks) throws Exception {
145    JPPFConnection connection = null;
146    JPPFJob job = null;
147    String id = null;
148    try {
149      connection = JPPFHelper.getConnection(jndiBinding);
150      job = new JPPFJob();
151      job.setName(jobId);
152      for (int i=0; i<nbTasks; i++) {
153        final DemoTask task = new DemoTask(duration);
154        task.setId(jobId + " task #" + (i + 1));
155        job.add(task);
156      }
157      id = connection.submit(job);
158      final List<Task<?>> results = connection.awaitResults(id);
159      System.out.println("received " + results.size() + " results for job '" + job.getName() + "'");
160    } finally {
161      if (connection != null) JPPFHelper.closeConnection(connection);
162    }
163    JPPFHelper.getStatusMap().put(id, job);
164    return id;
165  }
166
167  /**
168   * Get the map of job uuids to their corresponding job status.
169   * @return a map of ids to statuses as strings.
170   * @throws Exception if the call to JPPF failed.
171   */
172  public Map<String, String> getStatusMap() throws Exception {
173    final Map<String, String> map = new HashMap<>();
174    JPPFConnection connection = null;
175    try {
176      connection = JPPFHelper.getConnection(jndiBinding);
177      final Collection<String> coll = connection.getAllJobIds();
178      for (final String id: coll) {
179        final JobStatus status = connection.getJobStatus(id);
180        final String s = (status == null) ? "Unknown" : status.toString();
181        map.put(id, s);
182      }
183    } finally {
184      if (connection != null) JPPFHelper.closeConnection(connection);
185    }
186    return map;
187  }
188
189  /**
190   * Get the resulting message from a submission.
191   * @param id the id of the submission to retrieve.
192   * @return a string reporting either the task execution result or an error message.
193   * @throws Exception if the call to JPPF failed.
194   */
195  public String getMessage(final String id) throws Exception {
196    JPPFConnection connection = null;
197    String msg = null;
198    try {
199      connection = JPPFHelper.getConnection(jndiBinding);
200      final List<Task<?>> results = connection.getResults(id);
201      if (results == null) msg = "submission is not in queue anymore";
202      else {
203        final StringBuilder sb = new StringBuilder();
204        for (final Task<?> task: results) {
205          if (task.getThrowable() == null) sb.append(task.getResult());
206          else sb.append("task [").append(task.getId()).append("] ended in error: ").append(task.getThrowable().getMessage());
207          sb.append("<br/>");
208        }
209        msg = sb.toString();
210      }
211    } finally {
212      if (connection != null) JPPFHelper.closeConnection(connection);
213    }
214    return msg;
215  }
216}