public void createRandomIndividuals(int numIndividuals, KTH kth) { Map<Integer, Room> rooms = kth.getRooms(); int numRooms = kth.getRooms().size(); for (int i = 0; i < numIndividuals; i++) { // register all available timeslots ArrayList<TimeSlot> availableTimeSlots = new ArrayList<TimeSlot>(); for (int roomId : rooms.keySet()) { for (int d = 0; d < RoomTimeTable.NUM_DAYS; d++) { for (int t = 0; t < RoomTimeTable.NUM_TIMESLOTS; t++) { availableTimeSlots.add(new TimeSlot(roomId, d, t)); } } } TimeTable tt = new TimeTable(numRooms); for (int roomId : rooms.keySet()) { Room room = rooms.get(roomId); RoomTimeTable rtt = new RoomTimeTable(room); tt.putRoomTimeTable(roomId, rtt); } // index variables int rttId = 0; int day = 0; int timeSlot = 0; // assign all event to any randomly selected available timeslot Random rand = new Random(System.currentTimeMillis()); for (Event e : kth.getEvents().values()) { TimeSlot availableTimeSlot = availableTimeSlots.get(rand.nextInt(availableTimeSlots.size())); RoomTimeTable rtt = tt.getRoomTimeTables()[availableTimeSlot.roomId]; rtt.setEvent(availableTimeSlot.day, availableTimeSlot.timeSlot, e.getId()); availableTimeSlots.remove(availableTimeSlot); /* DEBUG System.out.println("=============="); System.out.println("ROOM TIME TABLE ID: " + rtt.getRoom().getName()); System.out.println("Day: " + availableTimeSlot.day + " Timeslot: " + availableTimeSlot.timeSlot + " Event ID: " + e.getId()); */ } individuals.add(tt); availableTimeSlots.clear(); } }
public void deleteEvent(Event event) { List<User> list = getUsers(); Collection<Activity> activities = event.getActivities(); Set<Activity> tmpActivities = new HashSet<Activity>(); for (Activity activityEntity : activities) { tmpActivities.add(activityEntity); } for (User user : list) { boolean userUpdated = false; if (user.getEvents().contains(event)) { for (Activity activity : tmpActivities) { user.getActivities().remove(activity); event.getActivities().remove(activity); } user.getEvents().remove(event); userUpdated = true; } if (userUpdated) { updateObject(user); } } deleteObject(event); // for (Activity activity : tmpActivities) { // deleteObject(activity); // } }
public List<Activity> getActivities(Event parent) { List<Activity> result = new ArrayList<Activity>(); Session session = SessionFactoryUtil.getInstance().getCurrentSession(); try { Transaction transaction = session.beginTransaction(); Object event = session .createQuery("from Event as event where event.idevent= " + parent.getIdevent()) .uniqueResult(); transaction.commit(); if (event != null) { Event eventEntity = (Event) event; Collection<Activity> activityList = eventEntity.getActivities(); for (Activity activity : activityList) { result.add(activity); } } } finally { if (session.isOpen()) { session.flush(); session.disconnect(); session.close(); } } return result; }
private void populateTrainingSessions() { if (null == sessions) { sessions = new HashSet<TrainingSession>(); } Set<Event> events = getSubscribedEvents(); for (Event ev : events) { TrainingSession ts1 = new TrainingSession( ev.getId(), this, new java.util.Date(1227817411), "a workout desc", true, "something for now", "something"); TrainingSession ts2 = new TrainingSession( ev.getId(), this, new java.util.Date(1229459011), "a workout desc", true, "something for now", "something"); UserRegistry.getCurrentInstance().userEJB.addTrainingSession(ts1); UserRegistry.getCurrentInstance().userEJB.addTrainingSession(ts2); sessions.add(ts1); sessions.add(ts2); } UserRegistry.getCurrentInstance().updateUser(this); }
/** * Find a matching client SUBSCRIBE to the incoming notify. NOTIFY requests are matched to such * SUBSCRIBE requests if they contain the same "Call-ID", a "To" header "tag" parameter which * matches the "From" header "tag" parameter of the SUBSCRIBE, and the same "Event" header field. * Rules for comparisons of the "Event" headers are described in section 7.2.1. If a matching * NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates a new * subscription and a new dialog (unless they have already been created by a matching response, as * described above). * * @param notifyMessage */ public SIPClientTransaction findSubscribeTransaction(SIPRequest notifyMessage) { synchronized (clientTransactions) { Iterator<SIPClientTransaction> it = clientTransactions.iterator(); String thisToTag = notifyMessage.getTo().getTag(); if (thisToTag == null) return null; Event eventHdr = (Event) notifyMessage.getHeader(EventHeader.NAME); if (eventHdr == null) return null; while (it.hasNext()) { SIPClientTransaction ct = (SIPClientTransaction) it.next(); // SIPRequest sipRequest = ct.getOriginalRequest(); String fromTag = ct.from.getTag(); Event hisEvent = ct.event; // Event header is mandatory but some slopply clients // dont include it. if (hisEvent == null) continue; if (ct.method.equals(Request.SUBSCRIBE) && fromTag.equalsIgnoreCase(thisToTag) && hisEvent != null && eventHdr.match(hisEvent) && notifyMessage.getCallId().getCallId().equalsIgnoreCase(ct.callId.getCallId())) return ct; } } return null; }
public static void main(String[] args) { EventManager mgr = new EventManager(); if (args[0].equals("store")) { mgr.createAndStoreEvent("My Event", new Date()); } else if (args[0].equals("list")) { List events = mgr.listEvents(); for (int i = 0; i < events.size(); i++) { Event theEvent = (Event) events.get(i); System.out.println("Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()); } } else if (args[0].equals("addpersontoevent")) { Long eventId = mgr.createAndStoreEvent("My Event", new Date()); Long personId = mgr.createAndStorePerson("Foo", "Bar"); mgr.addPersonToEvent(personId, eventId); System.out.println("Added person " + personId + " to event " + eventId); } else if (args[0].equals("addemailtoperson")) { Long personId = mgr.createAndStorePerson("Foozy", "Beary"); mgr.addEmailToPerson(personId, "foo@bar"); mgr.addEmailToPerson(personId, "bar@foo"); System.out.println( "Added two email addresses (value typed objects) to person entity : " + personId); } HibernateUtil.getSessionFactory().close(); }
public Object up(Event evt) { switch (evt.getType()) { case Event.MSG: Message msg = (Message) evt.getArg(); LockingHeader hdr = (LockingHeader) msg.getHeader(id); if (hdr == null) break; Request req = (Request) msg.getObject(); if (log.isTraceEnabled()) log.trace("[" + local_addr + "] <-- [" + msg.getSrc() + "] " + req); switch (req.type) { case GRANT_LOCK: case RELEASE_LOCK: handleLockRequest(req); break; case LOCK_GRANTED: handleLockGrantedResponse(req.lock_name, req.owner, msg.getSrc()); break; case LOCK_DENIED: handleLockDeniedResponse(req.lock_name, req.owner); break; case CREATE_LOCK: handleCreateLockRequest(req.lock_name, req.owner); break; case DELETE_LOCK: handleDeleteLockRequest(req.lock_name); break; case COND_SIG: case COND_SIG_ALL: handleSignalRequest(req); break; case LOCK_AWAIT: handleAwaitRequest(req.lock_name, req.owner); handleLockRequest(req); break; case DELETE_LOCK_AWAIT: handleDeleteAwaitRequest(req.lock_name, req.owner); break; case SIG_RET: handleSignalResponse(req.lock_name, req.owner); break; case CREATE_AWAITER: handleCreateAwaitingRequest(req.lock_name, req.owner); break; case DELETE_AWAITER: handleDeleteAwaitingRequest(req.lock_name, req.owner); break; default: log.error("Request of type " + req.type + " not known"); break; } return null; case Event.VIEW_CHANGE: handleView((View) evt.getArg()); break; } return up_prot.up(evt); }
private void updateExistingProfilesForSegment(Segment segment) { long t = System.currentTimeMillis(); Condition segmentCondition = new Condition(); segmentCondition.setConditionType( definitionsService.getConditionType("profilePropertyCondition")); segmentCondition.setParameter("propertyName", "segments"); segmentCondition.setParameter("comparisonOperator", "equals"); segmentCondition.setParameter("propertyValue", segment.getItemId()); if (segment.getMetadata().isEnabled()) { List<Profile> previousProfiles = persistenceService.query(segmentCondition, null, Profile.class); List<Profile> newProfiles = persistenceService.query(segment.getCondition(), null, Profile.class); List<Profile> add = new ArrayList<>(newProfiles); add.removeAll(previousProfiles); previousProfiles.removeAll(newProfiles); for (Profile profileToAdd : add) { profileToAdd.getSegments().add(segment.getItemId()); persistenceService.update( profileToAdd.getItemId(), null, Profile.class, "segments", profileToAdd.getSegments()); Event profileUpdated = new Event("profileUpdated", null, profileToAdd, null, null, profileToAdd, new Date()); profileUpdated.setPersistent(false); eventService.send(profileUpdated); } for (Profile profileToRemove : previousProfiles) { profileToRemove.getSegments().remove(segment.getItemId()); persistenceService.update( profileToRemove.getItemId(), null, Profile.class, "segments", profileToRemove.getSegments()); Event profileUpdated = new Event( "profileUpdated", null, profileToRemove, null, null, profileToRemove, new Date()); profileUpdated.setPersistent(false); eventService.send(profileUpdated); } } else { List<Profile> previousProfiles = persistenceService.query(segmentCondition, null, Profile.class); for (Profile profileToRemove : previousProfiles) { profileToRemove.getSegments().remove(segment.getItemId()); persistenceService.update( profileToRemove.getItemId(), null, Profile.class, "segments", profileToRemove.getSegments()); } } logger.info("Profiles updated in {}", System.currentTimeMillis() - t); }
public Object up(Event evt) { switch (evt.getType()) { case Event.VIEW_CHANGE: handleView(evt.getArg()); break; } return up_prot.up(evt); }
/** * Sends an event down the protocol stack. Note that - contrary to {@link #send(Message)}, if the * event is a message, no checks are performed whether the channel is closed or disconnected. * * @param evt the message to send down, encapsulated in an event */ public Object down(Event evt) { if (evt == null) return null; if (stats && evt.getType() == Event.MSG) { sent_msgs++; sent_bytes += ((Message) evt.getArg()).getLength(); } return prot_stack.down(evt); }
/** This is the heart of the event manager, which processes the events for a robot. */ public void processEvents() { // Remove old events eventQueue.clear(getTime() - MAX_EVENT_STACK); // Process custom events for (Condition customEvent : customEvents) { boolean conditionSatisfied = callUserCode(customEvent); if (conditionSatisfied) { addImpl(new CustomEvent(customEvent)); } } // Sort the events based on the time and priority of the events eventQueue.sort(); // Process event queue here Event currentEvent; while ((currentEvent = (eventQueue.size() > 0) ? eventQueue.get(0) : null) != null && currentEvent.getPriority() >= currentTopEventPriority) { if (currentEvent.getPriority() == currentTopEventPriority) { if (currentTopEventPriority > Integer.MIN_VALUE && isInterruptible(currentTopEventPriority)) { setInterruptible(currentTopEventPriority, false); // we're going to restart it, so reset. // We are already in an event handler, took action, and a new event was generated. // So we want to break out of the old handler to process it here. throw new EventInterruptedException(currentEvent.getPriority()); } break; } int oldTopEventPriority = currentTopEventPriority; currentTopEventPriority = currentEvent.getPriority(); currentTopEvent = currentEvent; eventQueue.remove(currentEvent); try { dispatch(currentEvent); setInterruptible(currentTopEventPriority, false); } catch (EventInterruptedException e) { currentTopEvent = null; } catch (RuntimeException e) { currentTopEvent = null; throw e; } catch (Error e) { currentTopEvent = null; throw e; } finally { currentTopEventPriority = oldTopEventPriority; } } }
/** * Returns the priority of events belonging to a specific class. * * @param eventClass is a string with the full class name of the event type to get the priority * from. * @return the event priority of the specified event class. * @see robocode.Event#getPriority() */ public int getEventPriority(String eventClass) { if (eventClass == null) { return -1; } final Event event = eventNames.get(eventClass); if (event == null) { return -1; } return event.getPriority(); }
@RequestMapping( value = "/events/{eventName}/additional-field/swap-position/{id1}/{id2}", method = POST) public void swapAdditionalFieldPosition( @PathVariable("eventName") String eventName, @PathVariable("id1") int id1, @PathVariable("id2") int id2, Principal principal) { Event event = eventManager.getSingleEvent(eventName, principal.getName()); eventManager.swapAdditionalFieldPosition(event.getId(), id1, id2); }
public Object down(Event evt) { switch (evt.getType()) { case Event.TMP_VIEW: case Event.VIEW_CHANGE: handleViewChange((View) evt.getArg()); break; case Event.GET_STATE: Address target; StateTransferInfo info = (StateTransferInfo) evt.getArg(); if (info.target == null) { target = determineCoordinator(); } else { target = info.target; if (target.equals(local_addr)) { log.error("%s: cannot fetch state from myself", local_addr); target = null; } } if (target == null) { log.debug("%s: first member (no state)", local_addr); up_prot.up(new Event(Event.GET_STATE_OK, new StateTransferInfo())); } else { Message state_req = new Message(target) .putHeader(this.id, new StateHeader(StateHeader.STATE_REQ)) .setFlag(Message.Flag.DONT_BUNDLE, Message.Flag.OOB, Message.Flag.SKIP_BARRIER); log.debug("%s: asking %s for state", local_addr, target); // suspend sending and handling of message garbage collection gossip messages, // fixes bugs #943480 and #938584). Wake up when state has been received /*if(log.isDebugEnabled()) log.debug("passing down a SUSPEND_STABLE event"); down_prot.down(new Event(Event.SUSPEND_STABLE, new Long(info.timeout)));*/ waiting_for_state_response = true; start = System.currentTimeMillis(); down_prot.down(new Event(Event.MSG, state_req)); } return null; // don't pass down any further ! case Event.CONFIG: Map<String, Object> config = (Map<String, Object>) evt.getArg(); if (config != null && config.containsKey("flush_supported")) { flushProtocolInStack = true; } break; case Event.SET_LOCAL_ADDRESS: local_addr = (Address) evt.getArg(); break; } return down_prot.down(evt); // pass on to the layer below us }
public Event overwrite(Event e) { this.data = e.getData(); this.accessors = e.getAccessors(); this.cancelled = e.isCancelled(); try { this.timestamp = e.getTimestamp(); } catch (IOException exception) { this.timestamp = new Timestamp(); } return this; }
public String toString() { String string = "event set, policy:" + suspendPolicy + ", count:" + this.size() + " = {"; boolean first = true; for (Event event : this) { if (!first) { string += ", "; } string += event.toString(); first = false; } string += "}"; return string; }
/** * Dispatches an event for a robot. * * <p>Too old events will not be dispatched and a critical event is always dispatched. * * @param event the event to dispatch to the robot. */ private void dispatch(Event event) { if (robot != null && event != null) { try { // skip too old events if ((event.getTime() > getTime() - MAX_EVENT_STACK) || HiddenAccess.isCriticalEvent(event)) { HiddenAccess.dispatch( event, robot, robotProxy.getStatics(), robotProxy.getGraphicsImpl()); } } catch (Exception ex) { robotProxy.println("SYSTEM: Exception occurred on " + event.getClass().getName()); ex.printStackTrace(robotProxy.getOut()); } } }
/** * Get the next queued item. Must be called after hasNext(). * * @return The next item in the queue to process. * @exception FrameworkException Thrown on errors. */ public Event next() throws FrameworkException { if (queue.size() == 0) { throw new FrameworkException("ERROR: Attempt was made to retrieve event from empty queue."); } Event event = (Event) queue.get(0); if (Debug.isLevelEnabled(Debug.MSG_STATUS)) Debug.log( Debug.MSG_STATUS, "QUEUE OPERATION: Retrieving the following event from the database queue:\n" + event.describe()); return event; }
/** * handle the UP event. * * @param evt - the event being send from the stack */ public void up(Event evt) { passUp(evt); switch (evt.getType()) { case Event.CONFIG: passUp(evt); if (Trace.trace) { Trace.info("UDP.up()", "received CONFIG event: " + evt.getArg()); } handleConfigEvent((HashMap) evt.getArg()); return; } passUp(evt); }
private Long createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); return theEvent.getId(); }
public EventNumberOfPassesRequest getEventPassesRequest(User user, Event event) { Session session = SessionFactoryUtil.getInstance().getCurrentSession(); try { Transaction transaction = session.beginTransaction(); List result = session .createQuery( "from EventNumberOfPassesRequest as eventNumberOfPassesRequest " + "where eventNumberOfPassesRequest.idevent=" + event.getIdevent() + " and eventNumberOfPassesRequest.iduser=" + user.getIduser()) .list(); transaction.commit(); if (result != null && result.size() > 0) { return (EventNumberOfPassesRequest) result.get(0); } } finally { if (session.isOpen()) { session.disconnect(); session.close(); } } return null; }
/** * Adds an event to the event queue. * * @param event is the event to add to the event queue. */ public void add(Event event) { if (!HiddenAccess.isCriticalEvent(event)) { final int priority = getEventPriority(event.getClass().getName()); HiddenAccess.setEventPriority(event, priority); } addImpl(event); }
@RequestMapping(value = "/events/{eventName}/categories-containing-tickets", method = GET) public List<TicketCategoryModification> getCategoriesWithTickets( @PathVariable("eventName") String eventName, Principal principal) { Event event = loadEvent(eventName, principal); return eventStatisticsManager .loadTicketCategoriesWithStats(event) .stream() .filter(tc -> !tc.getTickets().isEmpty()) .map( tc -> TicketCategoryModification.fromTicketCategory( tc.getTicketCategory(), ticketCategoryDescriptionRepository.findByTicketCategoryId(tc.getId()), event.getZoneId())) .collect(Collectors.toList()); }
/** * @param ev * @param alphabet * @param bs * @param sup * @param seqDB * @param posDB * @param sInd * @param eInd */ protected void verifyContentGeneralAcceptance( Event ev, Vector<Element> alphabet, BitSet bs, long[] sup, Vector<Integer>[] seqDB, Vector<Integer>[] posDB, int sInd, int eInd) { ItemSet set = ev.getSet(); for (int i = 0; i < set.size(); i++) { Element el = set.elementAt(i); int found = alphabet.indexOf(el); if (-1 != found) { // If current sequence did not contribute to the support of // this element yet, increment its support if (!bs.get(found)) { sup[found]++; bs.set(found); } // In any case, add another object to projecyed db seqDB[found].addElement(new Integer(sInd)); posDB[found].addElement(new Integer(eInd)); } } }
public Dialog getPreviousPoppedDialog(int time) { Dialog d = null; listIt = eventList.listIterator(); while (listIt.hasNext()) { Event temp = listIt.next(); if (temp.getTimeStamp() > time) { break; } if (temp.getType() == DIA_TIME) { d = (Dialog) temp; } } return d; }
/** * type check this rule * * @throws TypeException if the ruele contains type errors */ public void typeCheck() throws TypeException { String helperName = ruleScript.getTargetHelper(); // ensure that we have a valid helper class if (helperName != null) { try { helperClass = loader.loadClass(helperName); } catch (ClassNotFoundException e) { throw new TypeException( "Rule.typecheck : unknown helper class " + helperName + " for rule " + getName()); } } else { helperClass = Helper.class; } if (triggerExceptions != null) { // ensure that the type group includes the exception types typeGroup.addExceptionTypes(triggerExceptions); } // try to resolve all types in the type group to classes typeGroup.resolveTypes(); // use the descriptor to derive the method argument types and type any bindings for them // that are located in the bindings list installParameters((triggerAccess & Opcodes.ACC_STATIC) != 0, triggerClass); event.typeCheck(Type.VOID); condition.typeCheck(Type.Z); action.typeCheck(Type.VOID); }
public boolean handle(Thing h, Event e) { int time = e.getStat("Time"); Hero.action(h, time); Being.recover(h, time); return false; }
/** * Registers the full and simple class name of the specified event and sets the default priority * of the event class. * * @param event an event belonging to the event class to register the class name for etc. */ private void registerEventNames(Event event) { if (!HiddenAccess.isCriticalEvent(event)) { HiddenAccess.setDefaultPriority(event); } final Class<?> type = event.getClass(); eventNames.put(type.getName(), event); // full name with package name eventNames.put(type.getSimpleName(), event); // only the class name }
private double getDemandUplift(LocalDate dt) { Map<LocalDate, List<Event>> currEventMap = eventsMap.get(Years.years(dt.getYear())); if (currEventMap == null) { return 1.0; } List<Event> events = currEventMap.get(dt); return Event.calculateDemandUplift(events); }
public Object down(Event evt) { if (channel != null) { if (evt.getType() == Event.MSG && !(channel.isConnected() || channel.isConnecting())) throw new IllegalStateException("channel is not connected"); return channel.down(evt); } return null; }