List of usage examples for java.util Collection containsAll
boolean containsAll(Collection<?> c);
From source file:org.sakaiproject.announcement.tool.AnnouncementAction.java
/** * post or save draft of a message?/*from w ww .java2 s.co m*/ */ protected void postOrSaveDraft(RunData rundata, Context context, boolean post) { // tracking changes boolean titleChanged = false; boolean accessChanged = false; boolean availabilityChanged = false; // retrieve the state from state object AnnouncementActionState state = (AnnouncementActionState) getState(context, rundata, AnnouncementActionState.class); final String peid = ((JetspeedRunData) rundata).getJs_peid(); final SessionState sstate = ((JetspeedRunData) rundata).getPortletSessionState(peid); // get the channel and message id information from state object final String channelId = state.getChannelId(); // these are values that will be have been set if coming // from Preview final String subject = state.getTempSubject(); final String body = state.getTempBody(); final Time tempReleaseDate = state.getTempReleaseDate(); final Time tempRetractDate = state.getTempRetractDate(); final Boolean tempHidden = state.getTempHidden(); // announce to public? final String announceTo = state.getTempAnnounceTo(); // there is any error message caused by empty subject or body if (sstate.getAttribute(STATE_MESSAGE) != null) { state.setIsListVM(false); state.setStatus("stayAtRevise"); // disable auto-updates while in view mode disableObservers(sstate); } else { // read the notification options String notification = (String) sstate.getAttribute(AnnouncementAction.SSTATE_NOTI_VALUE); int noti = NotificationService.NOTI_OPTIONAL; if ("r".equals(notification)) { noti = NotificationService.NOTI_REQUIRED; } else if ("n".equals(notification)) { noti = NotificationService.NOTI_NONE; } try { AnnouncementChannel channel = null; AnnouncementMessageEdit msg = null; // if a new created announcement to be posted if (state.getIsNewAnnouncement()) { // get the channel id throught announcement service channel = AnnouncementService.getAnnouncementChannel(channelId); msg = channel.addAnnouncementMessage(); } else { // get the message object through service // AnnouncementMessageEdit msg = channel.editAnnouncementMessage( messageId ); msg = state.getEdit(); // get the channel id throught announcement service channel = AnnouncementService .getAnnouncementChannel(this.getChannelIdFromReference(msg.getReference())); } msg.setBody(body); AnnouncementMessageHeaderEdit header = msg.getAnnouncementHeaderEdit(); String oSubject = header.getSubject(); header.setSubject(subject); if (StringUtils.trimToNull(oSubject) != null && StringUtils.trimToNull(subject) != null && !oSubject.equals(subject)) { // announcement title changed titleChanged = true; } // header.setDraft(!post); // v2.4: Hidden in UI becomes Draft 'behind the scenes' boolean oDraft = header.getDraft(); if (oDraft != tempHidden) { // draft status changed availabilityChanged = true; } header.setDraft(tempHidden); header.replaceAttachments(state.getAttachments()); header.setFrom(UserDirectoryService.getCurrentUser()); // values stored here if saving from Add/Revise page ParameterParser params = rundata.getParameters(); // get release/retract dates final String specify = params.getString(HIDDEN); final boolean use_start_date = params.getBoolean("use_start_date"); final boolean use_end_date = params.getBoolean("use_end_date"); Time releaseDate = null; Time retractDate = null; String oReleaseDate = msg.getPropertiesEdit().getProperty(AnnouncementService.RELEASE_DATE); String oRetractDate = msg.getPropertiesEdit().getProperty(AnnouncementService.RETRACT_DATE); if (use_start_date && SPECIFY_DATES.equals(specify)) { int begin_year = params.getInt("release_year"); int begin_month = params.getInt("release_month"); int begin_day = params.getInt("release_day"); int begin_hour = hourAmPmConvert(params, "release_hour", "release_ampm"); int begin_min = params.getInt("release_minute"); releaseDate = TimeService.newTimeLocal(begin_year, begin_month, begin_day, begin_hour, begin_min, 0, 0); // in addition to setting release date property, also set Date to release date so properly sorted msg.getPropertiesEdit().addProperty(AnnouncementService.RELEASE_DATE, releaseDate.toString()); // this date is important as the message-api will pick up on it and create a delayed event if in future // the delayed event will then notify() to send the message at the proper time header.setDate(releaseDate); } else if (tempReleaseDate != null) // saving from Preview page { // in addition to setting release date property, also set Date to release date so properly sorted msg.getPropertiesEdit().addProperty(AnnouncementService.RELEASE_DATE, tempReleaseDate.toString()); header.setDate(tempReleaseDate); } else { // they are not using release date so remove if (msg.getProperties().getProperty(AnnouncementService.RELEASE_DATE) != null) { msg.getPropertiesEdit().removeProperty(AnnouncementService.RELEASE_DATE); } // since revised, set Date to current Date aka date modified, to maintain Date sort. header.setDate(TimeService.newTime()); } if (use_end_date && SPECIFY_DATES.equals(specify)) { int end_year = params.getInt("retract_year"); int end_month = params.getInt("retract_month"); int end_day = params.getInt("retract_day"); int end_hour = hourAmPmConvert(params, "retract_hour", "retract_ampm"); int end_min = params.getInt("retract_minute"); retractDate = TimeService.newTimeLocal(end_year, end_month, end_day, end_hour, end_min, 0, 0); msg.getPropertiesEdit().addProperty("retractDate", retractDate.toString()); } else if (tempRetractDate != null) { msg.getPropertiesEdit().addProperty(AnnouncementService.RETRACT_DATE, tempRetractDate.toString()); } else { // they are not using retract date so remove if (msg.getProperties().getProperty(AnnouncementService.RETRACT_DATE) != null) { msg.getPropertiesEdit().removeProperty(AnnouncementService.RETRACT_DATE); } } // release and retract date changed? availabilityChanged = stringChanged(availabilityChanged, oReleaseDate, msg.getPropertiesEdit().getProperty(AnnouncementService.RELEASE_DATE)); availabilityChanged = stringChanged(availabilityChanged, oRetractDate, msg.getPropertiesEdit().getProperty(AnnouncementService.RETRACT_DATE)); //modified date msg.getPropertiesEdit().addProperty(AnnouncementService.MOD_DATE, TimeService.newTime().toString()); //announceTo Placement placement = ToolManager.getCurrentPlacement(); // If the channel into which we are saving is public mark the item as public so it shows up in the // RSS feed. if (isChannelPublic(channelId)) { msg.getPropertiesEdit().addProperty(ResourceProperties.PROP_PUBVIEW, Boolean.TRUE.toString()); header.clearGroupAccess(); } // get the existing access and group settings String oPubView = msg.getPropertiesEdit().getProperty(ResourceProperties.PROP_PUBVIEW); String oAccess = header.getAccess().toString(); Collection<Group> oGroups = header.getGroupObjects(); try { Site site = SiteService.getSite(channel.getContext()); if (announceTo != null && announceTo.equals("pubview") || Boolean .valueOf((String) sstate.getAttribute(AnnouncementAction.SSTATE_PUBLICVIEW_VALUE)) .booleanValue()) // if from the post in preview, get the setting from sstate object { // any setting of this property indicates pubview msg.getPropertiesEdit().addProperty(ResourceProperties.PROP_PUBVIEW, Boolean.TRUE.toString()); header.clearGroupAccess(); } else { // remove the property to indicate no pubview msg.getPropertiesEdit().removeProperty(ResourceProperties.PROP_PUBVIEW); } // pubview changed? accessChanged = stringChanged(accessChanged, oPubView, msg.getPropertiesEdit().getProperty(ResourceProperties.PROP_PUBVIEW)); // announce to site? if (announceTo != null && announceTo.equals("site")) { header.clearGroupAccess(); } else if (announceTo != null && announceTo.equals("groups")) { // get the group ids selected Collection groupChoice = state.getTempAnnounceToGroups(); // make a collection of Group objects Collection groups = new Vector(); for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); groups.add(site.getGroup(groupId)); } // set access header.setGroupAccess(groups); } // site/grouop changed? accessChanged = stringChanged(accessChanged, oAccess, header.getAccess().toString()); if (!accessChanged) { Collection<Group> groups = header.getGroupObjects(); if (oGroups != null && groups != null && !(oGroups.containsAll(groups) && groups.containsAll(oGroups))) { // group changed accessChanged = true; } } } catch (PermissionException e) { addAlert(sstate, rb.getFormattedMessage("java.alert.youpermi.subject", subject)); state.setIsListVM(false); state.setStatus("stayAtRevise"); // disable auto-updates while in view mode disableObservers(sstate); return; } catch (Exception ignore) { // No site available. } // save notification level if this is a future notification message Time now = TimeService.newTime(); int notiLevel = noti; if (msg.getAnnouncementHeaderEdit().getDraft()) { notiLevel = 3; //Set notilevel as 3 if it a hidden announcement, as no notification is sent regardless of the notification option } if (releaseDate != null && now.before(releaseDate))// && noti != NotificationService.NOTI_NONE) { msg.getPropertiesEdit().addProperty("notificationLevel", notification); msg.getPropertiesEdit().addPropertyToList("noti_history", now.toStringLocalFull() + "_" + notiLevel + "_" + releaseDate.toStringLocalFull()); } else { msg.getPropertiesEdit().addPropertyToList("noti_history", now.toStringLocalFull() + "_" + notiLevel); } channel.commitMessage(msg, noti, "org.sakaiproject.announcement.impl.SiteEmailNotificationAnnc"); if (!state.getIsNewAnnouncement()) { state.setEdit(null); } // if-else // for event tracking if (titleChanged) { // title changed eventTrackingService.post(eventTrackingService .newEvent(AnnouncementService.EVENT_ANNC_UPDATE_TITLE, msg.getReference(), true)); } if (accessChanged) { // access changed eventTrackingService.post(eventTrackingService .newEvent(AnnouncementService.EVENT_ANNC_UPDATE_ACCESS, msg.getReference(), true)); } if (availabilityChanged) { // availablity changed eventTrackingService.post(eventTrackingService.newEvent( AnnouncementService.EVENT_ANNC_UPDATE_AVAILABILITY, msg.getReference(), true)); } } catch (IdUnusedException e) { if (M_log.isDebugEnabled()) M_log.debug(this + "doPost()", e); } catch (PermissionException e) { if (M_log.isDebugEnabled()) M_log.debug(this + "doPost()", e); addAlert(sstate, rb.getFormattedMessage("java.alert.youpermi.subject", subject)); } state.setIsListVM(true); state.setAttachments(null); state.setSelectedAttachments(null); state.setDeleteMessages(null); state.setStatus(POST_STATUS); state.setMessageReference(""); state.setTempAnnounceTo(null); state.setTempAnnounceToGroups(null); state.setCurrentSortedBy(getCurrentOrder()); //state.setCurrentSortAsc(Boolean.TRUE.booleanValue()); sstate.setAttribute(STATE_CURRENT_SORTED_BY, getCurrentOrder()); sstate.setAttribute(STATE_CURRENT_SORT_ASC, state.getCurrentSortAsc()); // make sure auto-updates are enabled enableObservers(sstate); } }
From source file:org.sakaiproject.content.impl.BaseContentService.java
protected void adjustGroups(ContentEntity member, Collection groups) { // check groups and then return Collection subgroups = member.getGroups(); if (groups.containsAll(subgroups)) { // this entity's groups are OK, so do nothing } else {//from w ww . j av a 2s . co m Collection newgroups = new ArrayList(); Iterator groupIt = subgroups.iterator(); while (groupIt.hasNext()) { String groupRef = (String) groupIt.next(); if (groups.contains(groupRef)) { newgroups.add(groupRef); } } if (member instanceof ContentResource) { ContentResourceEdit edit = m_storage.editResource(member.getId()); try { if (newgroups.isEmpty()) { edit.clearGroupAccess(); } else { edit.setGroupAccess(newgroups); } // addLiveUpdateResourceProperties(edit); m_storage.commitResource(edit); // close the edit object ((BaseResourceEdit) edit).closeEdit(); } catch (InconsistentException e) { // If change of groups is consistent in superfolder, this should not occur here m_storage.cancelResource(edit); M_log.error("verifyGroups(): ", e); } catch (PermissionException e) { // If user has permission to change groups in superfolder, this should not occur here m_storage.cancelResource(edit); M_log.error("verifyGroups(): ", e); } catch (ServerOverloadException e) { M_log.error("verifyGroups(): ", e); } } else { ContentCollectionEdit edit = m_storage.editCollection(member.getId()); try { if (newgroups.isEmpty()) { edit.clearGroupAccess(); } else { edit.setGroupAccess(newgroups); } // addLiveUpdateCollectionProperties(edit); m_storage.commitCollection(edit); } catch (InconsistentException e) { // If change of groups is consistent in superfolder, this should not occur here m_storage.cancelCollection(edit); M_log.error("verifyGroups(): ", e); } catch (PermissionException e) { // If user has permission to change groups in superfolder, this should not occur here m_storage.cancelCollection(edit); M_log.error("verifyGroups(): ", e); } } } }
From source file:edu.brown.hstore.BatchPlanner.java
/** * @param txn_id//from w w w. j av a 2 s.c om * @param client_handle * @param base_partition * @param predict_partitions * @param touched_partitions * @param batchArgs * @return */ public BatchPlan plan(Long txn_id, long client_handle, Integer base_partition, Collection<Integer> predict_partitions, boolean predict_singlepartitioned, Histogram<Integer> touched_partitions, ParameterSet[] batchArgs) { if (this.enable_profiling) time_plan.start(); if (d) LOG.debug(String.format("Constructing a new %s BatchPlan for %s txn #%d", this.catalog_proc.getName(), (predict_singlepartitioned ? "single-partition" : "distributed"), txn_id)); boolean cache_isSinglePartition[] = null; // OPTIMIZATION: Check whether we can use a cached single-partition BatchPlan if (this.force_singlePartition || this.enable_caching) { boolean is_allSinglePartition = true; cache_isSinglePartition = new boolean[this.batchSize]; // OPTIMIZATION: Skip all of this if we know that we're always // suppose to be single-partitioned if (this.force_singlePartition == false) { for (int stmt_index = 0; stmt_index < this.batchSize; stmt_index++) { if (cache_fastLookups[stmt_index] == null) { if (d) LOG.debug(String.format( "[#%d-%02d] No fast look-ups for %s. Cache is marked as not single-partitioned", txn_id, stmt_index, this.catalog_stmts[stmt_index].fullName())); cache_isSinglePartition[stmt_index] = false; } else { if (d) LOG.debug(String.format("[#%d-%02d] Using fast-lookup caching for %s: %s", txn_id, stmt_index, this.catalog_stmts[stmt_index].fullName(), Arrays.toString(cache_fastLookups[stmt_index]))); Object params[] = batchArgs[stmt_index].toArray(); cache_isSinglePartition[stmt_index] = true; for (int idx : cache_fastLookups[stmt_index]) { if (hasher.hash(params[idx]) != base_partition.intValue()) { cache_isSinglePartition[stmt_index] = false; break; } } // FOR } if (d) LOG.debug(String.format("[#%d-%02d] cache_isSinglePartition[%s] = %s", txn_id, stmt_index, this.catalog_stmts[stmt_index].fullName(), cache_isSinglePartition[stmt_index])); is_allSinglePartition = is_allSinglePartition && cache_isSinglePartition[stmt_index]; } // FOR (Statement) } if (t) LOG.trace(String.format("[#%d] is_allSinglePartition=%s", txn_id, is_allSinglePartition)); // If all of the Statements are single-partition, then we can use // the cached BatchPlan if we already have one. // This saves a lot of trouble if (is_allSinglePartition && cache_singlePartitionPlans[base_partition.intValue()] != null) { if (d) LOG.debug(String.format("[#%d] Using cached BatchPlan at partition #%02d: %s", txn_id, base_partition, Arrays.toString(this.catalog_stmts))); if (this.enable_profiling) time_plan.stop(); return (cache_singlePartitionPlans[base_partition.intValue()]); } } // Otherwise we have to construct a new BatchPlan plan.init(client_handle, base_partition); // ---------------------- // DEBUG DUMP // ---------------------- if (t) { Map<String, Object> m = new ListOrderedMap<String, Object>(); m.put("Batch Size", this.batchSize); for (int i = 0; i < this.batchSize; i++) { m.put(String.format("[%02d] %s", i, this.catalog_stmts[i].getName()), Arrays.toString(batchArgs[i].toArray())); } LOG.trace("\n" + StringUtil.formatMapsBoxed(m)); } // Only maintain the histogram of what partitions were touched if we // know that we're going to throw a MispredictionException Histogram<Integer> mispredict_h = null; boolean mispredict = false; for (int stmt_index = 0; stmt_index < this.batchSize; stmt_index++) { final Statement catalog_stmt = this.catalog_stmts[stmt_index]; assert (catalog_stmt != null) : "The Statement at index " + stmt_index + " is null for " + this.catalog_proc; final Object params[] = batchArgs[stmt_index].toArray(); if (t) LOG.trace(String.format("[#%d-%02d] Calculating touched partitions plans for %s", txn_id, stmt_index, catalog_stmt.fullName())); Map<PlanFragment, Set<Integer>> frag_partitions = plan.frag_partitions[stmt_index]; Set<Integer> stmt_all_partitions = plan.stmt_partitions[stmt_index]; boolean has_singlepartition_plan = catalog_stmt.getHas_singlesited(); boolean is_replicated_only = this.stmt_is_replicatedonly[stmt_index]; boolean is_read_only = this.stmt_is_readonly[stmt_index]; // boolean stmt_localFragsAreNonTransactional = // plan.localFragsAreNonTransactional; boolean is_singlepartition = has_singlepartition_plan; boolean is_local = true; CatalogMap<PlanFragment> fragments = null; // AbstractPlanNode node = // PlanNodeUtil.getRootPlanNodeForStatement(catalog_stmt, false); // LOG.info(PlanNodeUtil.debug(node)); // OPTIMIZATION: Fast partition look-up caching // OPTIMIZATION: Read-only queries on replicated tables always just // go to the local partition // OPTIMIZATION: If we're force to be single-partitioned, pretend // that the table is replicated if (cache_isSinglePartition[stmt_index] || (is_replicated_only && is_read_only) || this.force_singlePartition) { if (t) { if (cache_isSinglePartition[stmt_index]) { LOG.trace(String.format("[#%d-%02d] Using fast-lookup for %s. Skipping PartitionEstimator", txn_id, stmt_index, catalog_stmt.fullName())); } else { LOG.trace(String.format( "[#%d-%02d] %s is read-only and replicate-only. Skipping PartitionEstimator", txn_id, stmt_index, catalog_stmt.fullName())); } } assert (has_singlepartition_plan); if (this.cache_singlePartitionFragmentPartitions == null) { this.cache_singlePartitionFragmentPartitions = CACHED_FRAGMENT_PARTITION_MAPS[base_partition .intValue()]; } Map<PlanFragment, Set<Integer>> cached_frag_partitions = this.cache_singlePartitionFragmentPartitions .get(catalog_stmt); if (cached_frag_partitions == null) { cached_frag_partitions = new HashMap<PlanFragment, Set<Integer>>(); Set<Integer> p = CACHED_SINGLE_PARTITION_SETS[base_partition.intValue()]; for (PlanFragment catalog_frag : catalog_stmt.getFragments().values()) { cached_frag_partitions.put(catalog_frag, p); } // FOR this.cache_singlePartitionFragmentPartitions.put(catalog_stmt, cached_frag_partitions); } if (plan.stmt_partitions_swap[stmt_index] == null) { plan.stmt_partitions_swap[stmt_index] = plan.stmt_partitions[stmt_index]; plan.frag_partitions_swap[stmt_index] = plan.frag_partitions[stmt_index]; } stmt_all_partitions = plan.stmt_partitions[stmt_index] = CACHED_SINGLE_PARTITION_SETS[base_partition .intValue()]; frag_partitions = plan.frag_partitions[stmt_index] = cached_frag_partitions; } // Otherwise figure out whether the query can execute as // single-partitioned or not else { if (t) LOG.trace(String.format( "[#%d-%02d] Computing touched partitions %s in txn #%d with the PartitionEstimator", txn_id, stmt_index, catalog_stmt.fullName(), txn_id)); if (plan.stmt_partitions_swap[stmt_index] != null) { stmt_all_partitions = plan.stmt_partitions[stmt_index] = plan.stmt_partitions_swap[stmt_index]; plan.stmt_partitions_swap[stmt_index] = null; stmt_all_partitions.clear(); frag_partitions = plan.frag_partitions[stmt_index] = plan.frag_partitions_swap[stmt_index]; plan.frag_partitions_swap[stmt_index] = null; } try { // OPTIMIZATION: If we were told that the transaction is suppose to be // single-partitioned, then we will throw the single-partitioned PlanFragments // at the PartitionEstimator to get back what partitions each PlanFragment // will need to go to. If we get multiple partitions, then we know that we // mispredicted and we should throw a MispredictionException // If we originally didn't predict that it was single-partitioned, then we // actually still need to check whether the query should be single-partitioned or not. // This is because a query may actually just want to execute on just one // partition (note that it could be a local partition or the remote partition). // We'll assume that it's single-partition <<--- Can we cache that?? while (true) { if (is_singlepartition == false) stmt_all_partitions.clear(); fragments = (is_singlepartition ? catalog_stmt.getFragments() : catalog_stmt.getMs_fragments()); // PARTITION ESTIMATOR if (this.enable_profiling) ProfileMeasurement.swap(this.time_plan, this.time_partitionEstimator); this.p_estimator.getAllFragmentPartitions(frag_partitions, stmt_all_partitions, fragments.values(), params, base_partition); if (this.enable_profiling) ProfileMeasurement.swap(this.time_partitionEstimator, this.time_plan); int stmt_all_partitions_size = stmt_all_partitions.size(); if (is_singlepartition && stmt_all_partitions_size > 1) { // If this was suppose to be multi-partitioned, then // we want to stop right here!! if (predict_singlepartitioned) { if (t) LOG.trace(String.format("Mispredicted txn #%d - Multiple Partitions")); mispredict = true; break; } // Otherwise we can let it wrap back around and // construct the fragment mapping for the // multi-partition PlanFragments is_singlepartition = false; continue; } is_local = (stmt_all_partitions_size == 1 && stmt_all_partitions.contains(base_partition)); if (is_local == false && predict_singlepartitioned) { // Again, this is not what was suppose to happen! if (t) LOG.trace(String.format("Mispredicted txn #%d - Remote Partitions %s", txn_id, stmt_all_partitions)); mispredict = true; break; } else if (predict_partitions.containsAll(stmt_all_partitions) == false) { // Again, this is not what was suppose to happen! if (t) LOG.trace(String.format("Mispredicted txn #%d - Unallocated Partitions %s / %s", txn_id, stmt_all_partitions, predict_partitions)); mispredict = true; break; } // Score! We have a plan that works! break; } // WHILE // Bad Mojo! } catch (Exception ex) { String msg = ""; for (int i = 0; i < this.batchSize; i++) { msg += String.format("[#%d-%02d] %s %s\n%5s\n", txn_id, i, catalog_stmt.fullName(), catalog_stmt.getSqltext(), Arrays.toString(batchArgs[i].toArray())); } // FOR LOG.fatal("\n" + msg); throw new RuntimeException("Unexpected error when planning " + catalog_stmt.fullName(), ex); } } if (d) LOG.debug(String.format("[#%d-%02d] is_singlepartition=%s, partitions=%s", txn_id, stmt_index, is_singlepartition, stmt_all_partitions)); // Get a sorted list of the PlanFragments that we need to execute // for this query if (is_singlepartition) { if (this.sorted_singlep_fragments[stmt_index] == null) { this.sorted_singlep_fragments[stmt_index] = PlanNodeUtil.getSortedPlanFragments(catalog_stmt, true); } plan.frag_list[stmt_index] = this.sorted_singlep_fragments[stmt_index]; // Only mark that we touched these partitions if the Statement // is not on a replicated table if (is_replicated_only == false) { touched_partitions.putAll(stmt_all_partitions); } } else { if (this.sorted_multip_fragments[stmt_index] == null) { this.sorted_multip_fragments[stmt_index] = PlanNodeUtil.getSortedPlanFragments(catalog_stmt, false); } plan.frag_list[stmt_index] = this.sorted_multip_fragments[stmt_index]; // Always mark that we are touching these partitions touched_partitions.putAll(stmt_all_partitions); } plan.readonly = plan.readonly && catalog_stmt.getReadonly(); // plan.localFragsAreNonTransactional = // plan.localFragsAreNonTransactional || // stmt_localFragsAreNonTransactional; plan.all_singlepartitioned = plan.all_singlepartitioned && is_singlepartition; plan.all_local = plan.all_local && is_local; // Keep track of whether the current query in the batch was // single-partitioned or not plan.singlepartition_bitmap[stmt_index] = is_singlepartition; // Misprediction!! if (mispredict) { // If this is the first Statement in the batch that hits the mispredict, // then we need to create the histogram and populate it with the // partitions from the previous queries int start_idx = stmt_index; if (mispredict_h == null) { mispredict_h = new Histogram<Integer>(); start_idx = 0; } for (int i = start_idx; i <= stmt_index; i++) { if (d) LOG.debug(String.format( "Pending mispredict for txn #%d. Checking whether to add partitions for batch statement %02d", txn_id, i)); // Make sure that we don't count the local partition if it // was reading a replicated table. if (this.stmt_is_replicatedonly[i] == false || (this.stmt_is_replicatedonly[i] && this.stmt_is_readonly[i] == false)) { if (t) LOG.trace(String.format( "%s touches non-replicated table. Including %d partitions in mispredict histogram for txn #%d", this.catalog_stmts[i].fullName(), plan.stmt_partitions[i].size(), txn_id)); mispredict_h.putAll(plan.stmt_partitions[i]); } } // FOR continue; } // ---------------------- // DEBUG DUMP // ---------------------- if (d) { Map<?, ?> maps[] = new Map[fragments.size() + 1]; int ii = 0; for (PlanFragment catalog_frag : fragments) { Map<String, Object> m = new ListOrderedMap<String, Object>(); Set<Integer> p = plan.frag_partitions[stmt_index].get(catalog_frag); boolean frag_local = (p.size() == 1 && p.contains(base_partition)); m.put(String.format("[%02d] Fragment", ii), catalog_frag.fullName()); m.put(String.format(" Partitions"), p); m.put(String.format(" IsLocal"), frag_local); ii++; maps[ii] = m; } // FOR Map<String, Object> header = new ListOrderedMap<String, Object>(); header.put("Batch Statement#", String.format("%02d / %02d", stmt_index, this.batchSize)); header.put("Catalog Statement", catalog_stmt.fullName()); header.put("Statement SQL", catalog_stmt.getSqltext()); header.put("All Partitions", plan.stmt_partitions[stmt_index]); header.put("Local Partition", base_partition); header.put("IsSingledSited", is_singlepartition); header.put("IsStmtLocal", is_local); header.put("IsReplicatedOnly", is_replicated_only); header.put("IsBatchLocal", plan.all_local); header.put("Fragments", fragments.size()); maps[0] = header; LOG.debug("\n" + StringUtil.formatMapsBoxed(maps)); } } // FOR (Statement) // Check whether we have an existing graph exists for this batch // configuration // This is the only place where we need to synchronize int bitmap_hash = Arrays.hashCode(plan.singlepartition_bitmap); PlanGraph graph = this.plan_graphs.get(bitmap_hash); if (graph == null) { // assume fast case graph = this.buildPlanGraph(plan); this.plan_graphs.put(bitmap_hash, graph); } plan.graph = graph; plan.rounds_length = graph.num_rounds; if (this.enable_profiling) time_plan.stop(); // Create the MispredictException if any Statement in the loop above hit // it. We don't want to throw it because whoever called us may want to look // at the plan first if (mispredict_h != null) { plan.mispredict = new MispredictionException(txn_id, mispredict_h); } // If this a single-partition plan and we have caching enabled, we'll // add this to our cached listing. We'll mark it as cached so that it is never // returned back to the BatchPlan object pool else if (this.enable_caching && cache_singlePartitionPlans[base_partition.intValue()] == null && plan.isSingledPartitionedAndLocal()) { cache_singlePartitionPlans[base_partition.intValue()] = plan; plan.cached = true; plan = new BatchPlan(this.maxRoundSize); return cache_singlePartitionPlans[base_partition.intValue()]; } if (d) LOG.debug("Created BatchPlan:\n" + plan.toString()); return (plan); }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * post or save assignment/*www .j a va 2s . c o m*/ */ private void post_save_assignment(RunData data, String postOrSave) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); boolean post = (postOrSave != null) && "post".equals(postOrSave); // assignment old title String aOldTitle = null; // assignment old access setting String aOldAccessString = null; // assignment old group setting Collection aOldGroups = null; // assignment old open date setting Time oldOpenTime = null; // assignment old due date setting Time oldDueTime = null; // assignment old visible date setting Time oldVisibleTime = null; // assignment old close date setting Time oldCloseTime = null; // assignment old associated Gradebook entry if any String oAssociateGradebookAssignment = null; String mode = (String) state.getAttribute(STATE_MODE); if (!MODE_INSTRUCTOR_PREVIEW_ASSIGNMENT.equals(mode)) { // read input data if the mode is not preview mode setNewAssignmentParameters(data, true); } String assignmentId = params.getString("assignmentId"); String assignmentContentId = params.getString("assignmentContentId"); // whether this is an editing which changes non-point graded assignment to point graded assignment? boolean bool_change_from_non_point = false; // whether there is a change in the assignment resubmission choice boolean bool_change_resubmit_option = false; if (state.getAttribute(STATE_MESSAGE) == null) { // AssignmentContent object AssignmentContentEdit ac = editAssignmentContent(assignmentContentId, "post_save_assignment", state, true); bool_change_from_non_point = change_from_non_point(state, assignmentId, assignmentContentId, ac); // Assignment AssignmentEdit a = editAssignment(assignmentId, "post_save_assignment", state, true); bool_change_resubmit_option = change_resubmit_option(state, a); // put the names and values into vm file String title = (String) state.getAttribute(NEW_ASSIGNMENT_TITLE); String order = (String) state.getAttribute(NEW_ASSIGNMENT_ORDER); // open time Time openTime = getTimeFromState(state, NEW_ASSIGNMENT_OPENMONTH, NEW_ASSIGNMENT_OPENDAY, NEW_ASSIGNMENT_OPENYEAR, NEW_ASSIGNMENT_OPENHOUR, NEW_ASSIGNMENT_OPENMIN); // visible time Time visibleTime = null; if (Boolean.valueOf(ServerConfigurationService.getBoolean("assignment.visible.date.enabled", false))) { if (((Boolean) state.getAttribute(NEW_ASSIGNMENT_VISIBLETOGGLE))) visibleTime = getTimeFromState(state, NEW_ASSIGNMENT_VISIBLEMONTH, NEW_ASSIGNMENT_VISIBLEDAY, NEW_ASSIGNMENT_VISIBLEYEAR, NEW_ASSIGNMENT_VISIBLEHOUR, NEW_ASSIGNMENT_VISIBLEMIN); } // due time Time dueTime = getTimeFromState(state, NEW_ASSIGNMENT_DUEMONTH, NEW_ASSIGNMENT_DUEDAY, NEW_ASSIGNMENT_DUEYEAR, NEW_ASSIGNMENT_DUEHOUR, NEW_ASSIGNMENT_DUEMIN); // close time Time closeTime = dueTime; boolean enableCloseDate = ((Boolean) state.getAttribute(NEW_ASSIGNMENT_ENABLECLOSEDATE)).booleanValue(); if (enableCloseDate) { closeTime = getTimeFromState(state, NEW_ASSIGNMENT_CLOSEMONTH, NEW_ASSIGNMENT_CLOSEDAY, NEW_ASSIGNMENT_CLOSEYEAR, NEW_ASSIGNMENT_CLOSEHOUR, NEW_ASSIGNMENT_CLOSEMIN); } // sections String section = (String) state.getAttribute(NEW_ASSIGNMENT_SECTION); int submissionType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_SUBMISSION_TYPE)).intValue(); int gradeType = ((Integer) state.getAttribute(NEW_ASSIGNMENT_GRADE_TYPE)).intValue(); boolean isGroupSubmit = "1".equals((String) state.getAttribute(NEW_ASSIGNMENT_GROUP_SUBMIT)); String gradePoints = (String) state.getAttribute(NEW_ASSIGNMENT_GRADE_POINTS); String description = (String) state.getAttribute(NEW_ASSIGNMENT_DESCRIPTION); String checkAddDueTime = state .getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) != null ? (String) state.getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_ADD_DUE_DATE) : null; boolean hideDueDate = "true".equals((String) state.getAttribute(NEW_ASSIGNMENT_CHECK_HIDE_DUE_DATE)); String checkAutoAnnounce = (String) state .getAttribute(ResourceProperties.NEW_ASSIGNMENT_CHECK_AUTO_ANNOUNCE); String valueOpenDateNotification = (String) state .getAttribute(Assignment.ASSIGNMENT_OPENDATE_NOTIFICATION); String checkAddHonorPledge = (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ADD_HONOR_PLEDGE); String addtoGradebook = state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) != null ? (String) state.getAttribute(NEW_ASSIGNMENT_ADD_TO_GRADEBOOK) : ""; long category = state.getAttribute(NEW_ASSIGNMENT_CATEGORY) != null ? ((Long) state.getAttribute(NEW_ASSIGNMENT_CATEGORY)).longValue() : -1; String associateGradebookAssignment = (String) state .getAttribute(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); String allowResubmitNumber = state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null ? (String) state.getAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) : null; // SAK-17606 String checkAnonymousGrading = state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING) != null ? (String) state.getAttribute(NEW_ASSIGNMENT_CHECK_ANONYMOUS_GRADING) : ""; // SAK-26319 - we no longer clear the resubmit number for non electronic submissions; the instructor may switch to another submission type in the future //Peer Assessment boolean usePeerAssessment = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_PEER_ASSESSMENT)); Time peerPeriodTime = getTimeFromState(state, NEW_ASSIGNMENT_PEERPERIODMONTH, NEW_ASSIGNMENT_PEERPERIODDAY, NEW_ASSIGNMENT_PEERPERIODYEAR, NEW_ASSIGNMENT_PEERPERIODHOUR, NEW_ASSIGNMENT_PEERPERIODMIN); boolean peerAssessmentAnonEval = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_ANON_EVAL)); boolean peerAssessmentStudentViewReviews = "true".equalsIgnoreCase( (String) state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_STUDENT_VIEW_REVIEWS)); int peerAssessmentNumReviews = 0; if (state.getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS) != null) { peerAssessmentNumReviews = ((Integer) state .getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_NUM_REVIEWS)).intValue(); } String peerAssessmentInstructions = (String) state .getAttribute(NEW_ASSIGNMENT_PEER_ASSESSMENT_INSTRUCTIONS); //Review Service boolean useReviewService = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_USE_REVIEW_SERVICE)); boolean allowStudentViewReport = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_ALLOW_STUDENT_VIEW)); // If the assignment switched to non-electronic, we need to use some of the assignment's previous content-review settings. // This way, students will maintain access to their originality reports when appropriate. if (submissionType == Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) { useReviewService = ac.getAllowReviewService(); allowStudentViewReport = ac.getAllowStudentViewReport(); } String submitReviewRepo = (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_SUBMIT_RADIO); String generateOriginalityReport = (String) state .getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_REPORT_RADIO); boolean checkTurnitin = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_TURNITIN)); boolean checkInternet = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INTERNET)); boolean checkPublications = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_PUB)); boolean checkInstitution = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_CHECK_INSTITUTION)); //exclude bibliographic materials boolean excludeBibliographic = "true".equalsIgnoreCase( (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_BIBLIOGRAPHIC)); //exclude quoted materials boolean excludeQuoted = "true" .equalsIgnoreCase((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_QUOTED)); //exclude small matches boolean excludeSmallMatches = "true".equalsIgnoreCase( (String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_SMALL_MATCHES)); //exclude type 0=none, 1=words, 2=percentages int excludeType = 0; int excludeValue = 1; if (excludeSmallMatches) { try { excludeType = Integer .parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_TYPE)); if (excludeType != 0 && excludeType != 1 && excludeType != 2) { excludeType = 0; } } catch (Exception e) { //Numberformatexception } //exclude value try { excludeValue = Integer .parseInt((String) state.getAttribute(NEW_ASSIGNMENT_REVIEW_SERVICE_EXCLUDE_VALUE)); if (excludeValue < 0 || excludeValue > 100) { excludeValue = 1; } } catch (Exception e) { //Numberformatexception } } // the attachments List attachments = (List) state.getAttribute(NEW_ASSIGNMENT_ATTACHMENT); // set group property String range = (String) state.getAttribute(NEW_ASSIGNMENT_RANGE); Collection groups = new ArrayList(); try { Site site = SiteService.getSite(siteId); Collection groupChoice = (Collection) state.getAttribute(NEW_ASSIGNMENT_GROUPS); if (Assignment.AssignmentAccess.GROUPED.toString().equals(range) && (groupChoice == null || groupChoice.size() == 0)) { // show alert if no group is selected for the group access assignment addAlert(state, rb.getString("java.alert.youchoosegroup")); } else if (groupChoice != null) { for (Iterator iGroups = groupChoice.iterator(); iGroups.hasNext();) { String groupId = (String) iGroups.next(); Group _aGroup = site.getGroup(groupId); if (_aGroup != null) groups.add(_aGroup); } } } catch (Exception e) { M_log.warn(this + ":post_save_assignment " + e.getMessage()); } if ((state.getAttribute(STATE_MESSAGE) == null) && (ac != null) && (a != null)) { aOldTitle = a.getTitle(); aOldAccessString = a.getAccess().toString(); aOldGroups = a.getGroups(); // old open time oldOpenTime = a.getOpenTime(); // old due time oldDueTime = a.getDueTime(); // old visible time oldVisibleTime = a.getVisibleTime(); // old close time oldCloseTime = a.getCloseTime(); //assume creating the assignment with the content review service will be successful state.setAttribute("contentReviewSuccess", Boolean.TRUE); // commit the changes to AssignmentContent object commitAssignmentContentEdit(state, ac, a.getReference(), title, submissionType, useReviewService, allowStudentViewReport, gradeType, gradePoints, description, checkAddHonorPledge, attachments, submitReviewRepo, generateOriginalityReport, checkTurnitin, checkInternet, checkPublications, checkInstitution, excludeBibliographic, excludeQuoted, excludeType, excludeValue, openTime, dueTime, closeTime, hideDueDate); // set the Assignment Properties object ResourcePropertiesEdit aPropertiesEdit = a.getPropertiesEdit(); oAssociateGradebookAssignment = aPropertiesEdit .getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT); Time resubmitCloseTime = getTimeFromState(state, ALLOW_RESUBMIT_CLOSEMONTH, ALLOW_RESUBMIT_CLOSEDAY, ALLOW_RESUBMIT_CLOSEYEAR, ALLOW_RESUBMIT_CLOSEHOUR, ALLOW_RESUBMIT_CLOSEMIN); // SAK-17606 editAssignmentProperties(a, checkAddDueTime, checkAutoAnnounce, addtoGradebook, associateGradebookAssignment, allowResubmitNumber, aPropertiesEdit, post, resubmitCloseTime, checkAnonymousGrading); //TODO: ADD_DUE_DATE // the notification option if (state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE)); } // the release grade notification option if (state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE, (String) state.getAttribute(Assignment.ASSIGNMENT_RELEASEGRADE_NOTIFICATION_VALUE)); } if (state.getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE) != null) { aPropertiesEdit.addProperty(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE, (String) state .getAttribute(Assignment.ASSIGNMENT_RELEASERESUBMISSION_NOTIFICATION_VALUE)); } // comment the changes to Assignment object commitAssignmentEdit(state, post, ac, a, title, visibleTime, openTime, dueTime, closeTime, enableCloseDate, section, range, groups, isGroupSubmit, usePeerAssessment, peerPeriodTime, peerAssessmentAnonEval, peerAssessmentStudentViewReviews, peerAssessmentNumReviews, peerAssessmentInstructions); if (post) { // we need to update the submission if (bool_change_from_non_point || bool_change_resubmit_option) { List submissions = AssignmentService.getSubmissions(a); if (submissions != null && submissions.size() > 0) { // assignment already exist and with submissions for (Iterator iSubmissions = submissions.iterator(); iSubmissions.hasNext();) { AssignmentSubmission s = (AssignmentSubmission) iSubmissions.next(); AssignmentSubmissionEdit sEdit = editSubmission(s.getReference(), "post_save_assignment", state); if (sEdit != null) { ResourcePropertiesEdit sPropertiesEdit = sEdit.getPropertiesEdit(); if (bool_change_from_non_point) { // set the grade to be empty for now sEdit.setGrade(""); sEdit.setGraded(false); sEdit.setGradedBy(null); sEdit.setGradeReleased(false); sEdit.setReturned(false); } if (bool_change_resubmit_option) { String aAllowResubmitNumber = a.getProperties() .getProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (aAllowResubmitNumber == null || aAllowResubmitNumber.length() == 0 || "0".equals(aAllowResubmitNumber)) { sPropertiesEdit .removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); sPropertiesEdit .removeProperty(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); } else { sPropertiesEdit.addProperty(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER, a.getProperties().getProperty( AssignmentSubmission.ALLOW_RESUBMIT_NUMBER)); sPropertiesEdit.addProperty( AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME, a.getProperties().getProperty( AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME)); } } AssignmentService.commitEdit(sEdit); } } } } } //if // save supplement item information saveAssignmentSupplementItem(state, params, siteId, a); // set default sorting setDefaultSort(state); if (state.getAttribute(STATE_MESSAGE) == null) { // set the state navigation variables state.setAttribute(STATE_MODE, MODE_LIST_ASSIGNMENTS); state.setAttribute(ATTACHMENTS, EntityManager.newReferenceList()); resetAssignment(state); // integrate with other tools only if the assignment is posted if (post) { // add the due date to schedule if the schedule exists integrateWithCalendar(state, a, title, dueTime, checkAddDueTime, oldDueTime, aPropertiesEdit); // the open date been announced integrateWithAnnouncement(state, aOldTitle, a, title, openTime, checkAutoAnnounce, valueOpenDateNotification, oldOpenTime); // integrate with Gradebook try { initIntegrateWithGradebook(state, siteId, aOldTitle, oAssociateGradebookAssignment, a, title, dueTime, gradeType, gradePoints, addtoGradebook, associateGradebookAssignment, range, category); } catch (AssignmentHasIllegalPointsException e) { addAlert(state, rb.getString("addtogradebook.illegalPoints")); M_log.warn(this + ":post_save_assignment " + e.getMessage()); } // log event if there is a title update if (!aOldTitle.equals(title)) { // title changed m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_TITLE, assignmentId, true)); } if (!aOldAccessString.equals(a.getAccess().toString())) { // site-group access setting changed m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } else { Collection aGroups = a.getGroups(); if (!(aOldGroups == null && aGroups == null) && !(aOldGroups != null && aGroups != null && aGroups.containsAll(aOldGroups) && aOldGroups.containsAll(aGroups))) { //group changed m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_ACCESS, assignmentId, true)); } } if (oldOpenTime != null && !oldOpenTime.equals(a.getOpenTime())) { // open time change m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_OPENDATE, assignmentId, true)); } if (oldDueTime != null && !oldDueTime.equals(a.getDueTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_DUEDATE, assignmentId, true)); } if (oldCloseTime != null && !oldCloseTime.equals(a.getCloseTime())) { // due time change m_eventTrackingService.post(m_eventTrackingService.newEvent( AssignmentConstants.EVENT_UPDATE_ASSIGNMENT_CLOSEDATE, assignmentId, true)); } } } } // if } // if }