public void testExecuteWithException() { final RuntimeException exp = new RuntimeException(); Task<String, String> task = new Task<String, String>() { @Override public void run(String value) { throw exp; } @Override public void onFailed(Bundle value, Exception exp) { mValue = exp; } }; task.execute( "aaa", new MockPromiseContext() { @Override public State getState() { return State.ALIVE; } @Override public void fail(Bundle value, Exception exp) { mIsFailed = true; } }, 0); assertTrue(mIsFailed); assertEquals(exp, mValue); }
@SuppressWarnings("unchecked") public <E> void dispatch( Object key, E event, Registry<Consumer<?>> consumerRegistry, Consumer<Throwable> errorConsumer, Router router, Consumer<E> completionConsumer, boolean isInContext) { Assert.isTrue(alive(), "This Dispatcher has been shut down."); try { Task task; if (isInContext) { task = allocateRecursiveTask(); } else { task = allocateTask(); } task.setKey(key) .setData(event) .setConsumerRegistry(consumerRegistry) .setErrorConsumer(errorConsumer) .setRouter(router); if (completionConsumer != null) task.setCompletionConsumer((Consumer<Object>) completionConsumer); if (!isInContext) { execute(task); } } catch (Exception e) { throw new IllegalStateException(e.getMessage() + " " + Thread.currentThread(), e); } }
/** * Inference between a compound term and a statement * * @param compound The compound term * @param index The location of the current term in the compound * @param statement The statement * @param side The location of the current term in the statement * @param beliefTerm The content of the belief * @param memory Reference to the memory */ private static void compoundAndStatement( CompoundTerm compound, short index, Statement statement, short side, Term beliefTerm, Memory memory) { Term component = compound.componentAt(index); Task task = memory.currentTask; if (component.getClass() == statement.getClass()) { if ((compound instanceof Conjunction) && (memory.currentBelief != null)) { if (Variable.unify(Symbols.VAR_DEPENDENT, component, statement, compound, statement)) { SyllogisticRules.elimiVarDep(compound, component, statement.equals(beliefTerm), memory); } else if (task.getSentence().isJudgment()) { CompositionalRules.introVarInner(statement, (Statement) component, compound, memory); } } } else { if (!task.isStructural() && task.getSentence().isJudgment()) { if (statement instanceof Inheritance) { StructuralRules.structuralCompose1(compound, index, statement, memory); // if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) // { if (!(compound instanceof SetExt || compound instanceof SetInt || compound instanceof Negation)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A --> B, A @ (A&C)} |- (A&C) --> (B&C) } else if ((statement instanceof Similarity) && !(compound instanceof Conjunction)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A <-> B, A @ (A&C)} |- (A&C) <-> (B&C) } } }
private void handleInterruptBegin(final TypedCircularMessage message, final long ts) { // TODO: rewrite code so it handles nested interrupts // get interrupt id from message // get task from map // switch from last task to this task (write to file) // push task on stack // pop out-task from stack // peek in-task // switch from out task to in task final Long taskId = -((Long) getValue(message, SRLEventReader.FN_INT_ID)); Task task = getTaskFromId(taskId); Long prio = interruptMap.get(taskId); if (prio == null) { prio = new Long(-777); } else { prio = -prio; } task.setPriority(prio.intValue()); client.eventRead( new TaskSwitchEventInfo( ts, taskId.intValue(), lastTaskId, prio.intValue(), EventFactory.TASK_SWITCH_EVENT_TYPE_ID, new FieldValues())); }
/** Reheap to make polling easier */ private void reheap(int rootIndex) { // initialize boolean done = false; Task orphan = heap[rootIndex]; int leftIndex = 2 * rootIndex; // while not at end and not done while (!done && (leftIndex <= lastIndex)) { // get the smaller child // assume it's the left int smallIndex = leftIndex; int midIndex = leftIndex + 1; int rightIndex = leftIndex + 2; // change the smaller child as needed if (rightIndex <= lastIndex && heap[rightIndex].compareTo(heap[smallIndex]) < 0) { smallIndex = rightIndex; } else if (rightIndex <= lastIndex && heap[midIndex].compareTo(heap[smallIndex]) < 0) { smallIndex = midIndex; } // compare to the smallest child- if it's larger, move it down and continue if (orphan.compareTo(heap[smallIndex]) > 0) { heap[rootIndex] = heap[smallIndex]; rootIndex = smallIndex; leftIndex = 2 * rootIndex; } else { // if it's smaller, we're done done = true; } } heap[rootIndex] = orphan; }
private void changeStatus(int status) { task.setStatus(status); com.zavitz.mytasks.functions.PersistentUtils.save(); this.status.setSelected(status); percent_complete.setTextQuiet(task.getPercentComplete() + "%"); }
private List<String> GetTasksJSONs(Collection<Task> tasks, String state) { List<String> tasksJSONs = new ArrayList<String>(); for (Task task : tasks) { tasksJSONs.add(task.SerializeToJSON(state)); } return tasksJSONs; }
@Override public void run() { if (logger.isDebugEnabled()) { logger.debug("Create task manager thread."); } do { logger.info("TaskManager: current task index: " + Integer.toString(currentTaskIndex)); try { String output = currentTask.Run(); logger.info("Task {[]} output: {[]}", currentTask.id(), output); logger.info("Task [" + currentTask.id() + "] output: " + output); } catch (IOException ex) { logger.error("TaskManager: IOException"); } catch (InterruptedException ex) { logger.error("TaskManager: Interrupted Exception"); } currentTask = GetNextTask(); } while (null != currentTask); DeleteMappingRequest req = new DeleteMappingRequest("_river"); req.type(river.riverName().name()); DeleteMappingResponse resp = client.admin().indices().deleteMapping(req).actionGet(); logger.info("TaskManager: delete request: " + resp.toString()); }
private void setMarkersOptions(Location loc) { boolean visible = true; if (markersOnMap == null) { markersOnMap = new ArrayList<Marker>(); } for (Task task : TaskList.getInstance(getApplicationContext()).getTasks()) { LatLng temp = getLatLngIfPossible(task.getLocation()); if (temp != null) { Location tloc = new Location(task.getLocation()); tloc.setLatitude(temp.latitude); tloc.setLongitude(temp.longitude); float dist = tloc.distanceTo(loc); Marker tempMarker = map.addMarker( new MarkerOptions() .position(temp) .visible(visible) .title(String.valueOf(task.getTask_id())) .icon(BitmapDescriptorFactory.fromResource(R.drawable.marke_65px))); if (dist > sbRadOuter.getProgress() * 100) { tempMarker.setVisible(false); } markersOnMap.add(tempMarker); } } }
@Override protected IStatus run(final IProgressMonitor monitor) { while (true) { Task task; synchronized (fTasksLock) { final IModelElement element = (!fTaskQueue.isEmpty()) ? fTaskQueue.removeFirst() : null; if (element == null || fStop) { fWorking = false; return Status.OK_STATUS; } fWorking = true; task = fTaskDetail.remove(element); } try { task.run(); } catch (final Throwable e) { LTKCorePlugin.log( new Status( IStatus.ERROR, LTK.PLUGIN_ID, -1, "An error occurred when firing model event for " + fModelManager.getModelTypeId() + ".", //$NON-NLS-1$ e)); } } }
private void InitTasks() throws Exception { QueryBuilder builder = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", "_meta")); SearchRequestBuilder search = client.prepareSearch("_river"); search.setTypes(river.riverName().name()); search.setQuery(builder); SearchResponse resp = search.execute().actionGet(); int hitCount = 0; for (SearchHit hit : resp.hits().getHits()) { logger.info( "Task Manager: Query response hits[ " + Integer.toString(hitCount) + "]: " + hit.sourceAsString()); hitCount++; Map<String, Object> sourceMap = hit.sourceAsMap(); Map<String, Object> my = (Map<String, Object>) sourceMap.get("my"); ArrayList arr = (ArrayList) my.get("tasks"); for (Object taskObj : arr) { Task newTask = new Task((Map<String, String>) taskObj, client, river.riverName().name()); taskArr.add(newTask); taskMap.put(newTask.id(), newTask); } } currentTaskIndex = 0; currentTask = (Task) taskArr.get(currentTaskIndex); }
public List<Task> doTaskSearch(String query, int user_id) { List<TaskEntry> list = taskEntryRepository.findByTitleOrDescription(query, query); List<Task> ret = new ArrayList<>(); for (TaskEntry entry : list) { System.out.println( "entry userID = " + entry.getUser_id() + " required UserID = " + Integer.toString(user_id)); System.out.println(entry.getType()); String type = entry.getType(); if ((type.equals("task") || type.equals("taskItem")) && entry.getUser_id().equals(Integer.toString(user_id))) { if (type.equals("task")) { Task task = OrganizerDAO.getTaskByTitle(user_id, entry.getTitle()); ret.add(task); } if (type.equals("taskItem")) { TaskItem item = OrganizerDAO.getTaskId(Integer.parseInt(entry.getObj_id())); Task task = OrganizerDAO.getTaskById(item.getTask_id()); List<TaskItem> taskList = OrganizerDAO.getTaskItems(task.getId()); if (taskList != null) { task.setTaskList(taskList); task.setTaskListSize(taskList.size()); } ret.add(task); } } } return ret; }
private Task mapTask( PuzzleDto puzzle, ChallengeTemplate challengeTemplate, Organization organization, Map<String, ByteArrayOutputStream> files, Duration gameDuration, Runner runner, Endpoint endpoint, Set<Language> languages) throws IOException { Task task = new Task(); task.setCanonicalName( fixCanonicalName(challengeTemplate.getCanonicalName() + "-" + puzzle.getCanonicalName())); task.setName(puzzle.getCanonicalName()); task.setEndpoint(endpoint); task.setDescription(puzzle.getCanonicalName()); task.setInstructions( storage.uploadPublic( instructionsBucket, instructionsFileName(challengeTemplate, puzzle.getInstructionsFile()), new ByteArrayInputStream(files.get(puzzle.getInstructionsFile()).toByteArray()), "application/pdf")); task.setDuration(gameDuration); task.setRunner(runner); task.setLanguages(languages); task.setOrganization(organization); return task; }
public static void main(String[] args) throws Exception { // 8、创建ForkJoinPool对象 ForkJoinPool pool = new ForkJoinPool(); // 9、创建元素有10000个的int数组 int array[] = new int[10000]; // 10、创建一个新的任务,处理整个数组 Task task1 = new Task(array, 0, array.length); // 11、使用execute()方法将任务发给pool执行, pool.execute(task1); // 12、当任务未结束时,调用showLog()方法输出ForkJoinPool类的状态信息,并使线程睡眠1秒 while (!task1.isDone()) { showLog(pool); TimeUnit.SECONDS.sleep(1); } // 13、使用shutDown()y方法关闭pool pool.shutdown(); // 14、使用awaitTermination()方法等待pool结束 pool.awaitTermination(1, TimeUnit.DAYS); // 15、调用showLog()方法,输出ForkJoinPool类的状态信息,并输出程序执行结束的信息 showLog(pool); System.out.printf("Main: End of the program.\n"); }
/** * Fired when a task finishes building, this adds the time taken and any error stacktrace to the * appropriate task element in the log. * * @param event An event with any relevant extra information. Will not be <code>null</code>. */ public void taskFinished(BuildEvent event) { Task task = event.getTask(); TimedElement taskElement = (TimedElement) tasks.get(task); if (taskElement != null) { long totalTime = System.currentTimeMillis() - taskElement.startTime; // taskElement.element.setAttribute(TIME_ATTR, // DefaultLogger.formatTime(totalTime)); Target target = task.getOwningTarget(); TimedElement targetElement = null; if (target != null) { targetElement = (TimedElement) targets.get(target); } if (targetElement == null) { buildElement.element.appendChild(taskElement.element); } else { targetElement.element.appendChild(taskElement.element); } Stack threadStack = getStack(); if (!threadStack.empty()) { TimedElement poppedStack = (TimedElement) threadStack.pop(); if (poppedStack != taskElement) { throw new RuntimeException( "Mismatch - popped element = " + poppedStack + " finished task element = " + taskElement); } } tasks.remove(task); } else { throw new RuntimeException("Unknown task " + task + " not in " + tasks); } }
public void handleJobEvent(JobEvent event) { if (event instanceof BeginPhaseEvent) { Phase phase = event.phase(); if (phase == Phase.LOOKUP) { currentTask = new Task("Connecting to repository", 1); } else if (phase == Phase.PLAN) { currentTask = new Task("Calculating changes\t", 1); } else if (phase == Phase.FILL_CACHE) { currentTask = new Task("Updating cache\t"); } else if (phase == Phase.PROCESS) { currentTask = new Task("Applying changes\t"); } } else if (event instanceof EndPhaseEvent) { currentTask.status = Status.OK; currentTask.worked = currentTask.totalSteps; } else if (event instanceof PhaseProgressEvent) { PhaseProgressEvent workEvent = (PhaseProgressEvent) event; currentTask.totalSteps = workEvent.totalSteps(); currentTask.worked = workEvent.workedSteps(); } currentTask.print(); }
// WARN Watch this code, see if we can do better, maybe leverage @UnitOfWorkRetry @Override public void run() { System.out.println("Running Schedule"); Usecase usecase = UsecaseBuilder.newUsecase("ScheduleRunner"); UnitOfWork uow = module.newUnitOfWork(usecase); try { Schedule schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity); Task task = schedule.task().get(); schedule = uow.get(Schedule.class, this.schedule.scheduleIdentity); try { schedule.taskStarting(); task.run(); schedule.taskCompletedSuccessfully(); } catch (RuntimeException ex) { schedule.taskCompletedWithException(ex); } schedulerMixin.dispatchForExecution(schedule); uow.complete(); } catch (UnitOfWorkCompletionException ex) { } finally { // What should we do if we can't manage the Running flag?? if (uow.isOpen()) { uow.discard(); } } }
/** Run a command and wait for it's successful completion. */ protected void runCommand(ExecutorDriver driver, Task task, String command) { reloadConfig(); try { log.info(String.format("About to run command: %s", command)); ProcessBuilder processBuilder = new ProcessBuilder("sh", "-c", command); Process init = processBuilder.start(); redirectProcess(init); int exitCode = init.waitFor(); if (exitCode == 0) { log.info("Finished running command, exited with status " + exitCode); } else { log.error("Unable to run command: " + command); if (task.getProcess() != null) { task.getProcess().destroy(); } sendTaskFailed(driver, task); } } catch (InterruptedException | IOException e) { log.error("Unable to run command:", e); if (task.getProcess() != null) { task.getProcess().destroy(); } sendTaskFailed(driver, task); } }
@Test public void find_findsTaskInDatabase_true() { Task myTask = new Task("Mow the lawn", 1); myTask.save(); Task savedTask = Task.find(myTask.getId()); assertTrue(myTask.equals(savedTask)); }
/* * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setFillInTask(boolean)' */ public void testSetFillInTask() { progtask.setFillInTask(true); assert (progtask.isFillInTask()); progtask.setFillInTask(false); assert (progtask.isProgrammingTask()); }
public int getTasksPowerNeed() { int ret = 0; for (Task taskIt : tasks) { ret += taskIt.get_time_needed(); } return ret; }
/* * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setValidateByModel(boolean)' */ public void testSetValidateByModel() { progtask.setValidateByModel(true); assert (progtask.isValidateByModel()); progtask.setValidateByModel(false); assert (!progtask.isValidateByModel()); }
protected String getReceiverID(Task task) { String receiverID; Object receiver = task.getPrepositionalPhrase(Constants.Preposition.FOR); if (receiver != null) receiver = ((PrepositionalPhrase) receiver).getIndirectObject(); // Add field with recipient if (receiver == null) { receiverID = UNKNOWN; _gp.getLoggingService() .error("Filler.addContentsInfo - Task " + task.getUID() + " had no FOR prep."); } else if (receiver instanceof String) { receiverID = (String) receiver; } else if (!(receiver instanceof Asset)) { receiverID = UNKNOWN; } else { ItemIdentificationPG itemIdentificationPG = ((Asset) receiver).getItemIdentificationPG(); if ((itemIdentificationPG == null) || (itemIdentificationPG.getItemIdentification() == null) || (itemIdentificationPG.getItemIdentification().equals(""))) { receiverID = UNKNOWN; } else { receiverID = itemIdentificationPG.getItemIdentification(); } } return receiverID; }
/* * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setHasSucceeded(boolean)' */ public void testSetHasSucceeded() { progtask.setHasSucceeded(true); assert (progtask.isHasSucceeded()); progtask.setHasSucceeded(false); assert (!progtask.isHasSucceeded()); }
private void removeCompletedTasks() { ArrayList<Long> removedTaskIds = new ArrayList<>(); for (int i = 0, count = mTaskAdapter.getCount(); i < count; ) { Task task = mTaskAdapter.getItem(i); if (task.getDone()) { removedTaskIds.add(task.getId()); mTaskAdapter.remove(task); count--; } else { i++; } } if (removedTaskIds.isEmpty()) return; boolean first = true; String idsStr = ""; for (long id : removedTaskIds) { if (first) { first = false; } else { idsStr += ","; } idsStr += "" + id; } SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.delete(Task.TABLE_NAME, String.format("%s IN (%s)", Task._ID, idsStr), new String[] {}); db.close(); }
@Override public TaskRunResult run(Task task) { OperationResult result = task.getResult().createSubresult(WaitForTasksTaskHandler.class.getName() + ".run"); result.recordInProgress(); LOGGER.info("WaitForTasksTaskHandler run starting; in task " + task.getName()); try { // todo resolve this brutal hack taskManagerImpl.pauseTask(task, TaskWaitingReason.OTHER, result); task.startWaitingForTasksImmediate(result); } catch (SchemaException e) { throw new SystemException( "Couldn't mark task as waiting for prerequisite tasks", e); // should not occur; will be handled by task runner } catch (ObjectNotFoundException e) { throw new SystemException( "Couldn't mark task as waiting for prerequisite tasks", e); // should not occur; will be handled by task runner } LOGGER.info("WaitForTasksTaskHandler run finishing; in task " + task.getName()); result.computeStatus(); TaskRunResult runResult = new TaskRunResult(); runResult.setOperationResult(result); runResult.setProgress(task.getProgress()); // not to overwrite task's progress runResult.setRunResultStatus(TaskRunResultStatus.FINISHED); return runResult; }
@Test public void testDynamicFetch() { Session s = openSession(); s.beginTransaction(); Date now = new Date(); User me = new User("me"); User you = new User("you"); Resource yourClock = new Resource("clock", you); Task task = new Task(me, "clean", yourClock, now); // :) s.save(me); s.save(you); s.save(yourClock); s.save(task); s.getTransaction().commit(); s.close(); StatelessSession ss = sessionFactory().openStatelessSession(); ss.beginTransaction(); Task taskRef = (Task) ss.createQuery("from Task t join fetch t.resource join fetch t.user").uniqueResult(); assertTrue(taskRef != null); assertTrue(Hibernate.isInitialized(taskRef)); assertTrue(Hibernate.isInitialized(taskRef.getUser())); assertTrue(Hibernate.isInitialized(taskRef.getResource())); assertFalse(Hibernate.isInitialized(taskRef.getResource().getOwner())); ss.getTransaction().commit(); ss.close(); cleanup(); }
/* ------------------------------------------------------------ */ private void link(Task task) { Task next_next = _next; _next._prev = task; _next = task; _next._next = next_next; _next._prev = this; }
@SuppressWarnings("deprecation") public CoronaJobTrackerRunner( TaskTracker.TaskInProgress tip, Task task, TaskTracker tracker, JobConf ttConf, CoronaSessionInfo info, String originalPath, String releasePath) throws IOException { super(tip, task, tracker, ttConf); this.coronaSessionInfo = info; this.originalPath = originalPath; this.releasePath = releasePath; LocalDirAllocator lDirAlloc = new LocalDirAllocator("mapred.local.dir"); workDir = new File( lDirAlloc .getLocalPathForWrite( TaskTracker.getLocalTaskDir( task.getJobID().toString(), task.getTaskID().toString(), task.isTaskCleanupTask()) + Path.SEPARATOR + MRConstants.WORKDIR, conf) .toString()); if (!workDir.mkdirs()) { if (!workDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + workDir.toString()); } } localizeTaskConfiguration(tracker, ttConf, workDir.toString(), task, task.getJobID()); }
public void testExecuteWithFail() { final Bundle bundle = new Bundle(); Task<String, String> task = new Task<String, String>() { @Override public void run(String value) { fail(bundle); } @Override public void onFailed(Bundle value, Exception exp) { mIsFailed = true; mValue = value; } }; task.execute( "aaa", new MockPromiseContext() { @Override public State getState() { return State.ALIVE; } @Override public void done(Object value) { mIsDone = true; } }, 0); assertTrue(mIsFailed); assertEquals(bundle, mValue); }