List of usage examples for java.util Set clear
void clear();
From source file:org.apache.sling.scripting.sightly.impl.engine.extension.ResourceRuntimeExtension.java
private Map<String, String> handleSelectors(Bindings bindings, Set<String> selectors, Map<String, Object> options) { if (selectors.isEmpty()) { SlingHttpServletRequest request = BindingsUtils.getRequest(bindings); selectors.addAll(Arrays.asList(request.getRequestPathInfo().getSelectors())); }//from w ww . j av a 2 s.c om Map<String, String> dispatcherOptionsMap = new HashMap<>(); dispatcherOptionsMap.put(OPTION_ADD_SELECTORS, getSelectorString(selectors)); dispatcherOptionsMap.put(OPTION_REPLACE_SELECTORS, " "); if (options.containsKey(OPTION_SELECTORS)) { Object selectorsObject = getAndRemoveOption(options, OPTION_SELECTORS); selectors.clear(); addSelectors(selectors, selectorsObject); dispatcherOptionsMap.put(OPTION_ADD_SELECTORS, getSelectorString(selectors)); dispatcherOptionsMap.put(OPTION_REPLACE_SELECTORS, " "); } if (options.containsKey(OPTION_ADD_SELECTORS)) { Object selectorsObject = getAndRemoveOption(options, OPTION_ADD_SELECTORS); addSelectors(selectors, selectorsObject); dispatcherOptionsMap.put(OPTION_ADD_SELECTORS, getSelectorString(selectors)); dispatcherOptionsMap.put(OPTION_REPLACE_SELECTORS, " "); } if (options.containsKey(OPTION_REMOVE_SELECTORS)) { Object selectorsObject = getAndRemoveOption(options, OPTION_REMOVE_SELECTORS); if (selectorsObject instanceof String) { String selectorString = (String) selectorsObject; String[] parts = selectorString.split("\\."); for (String s : parts) { selectors.remove(s); } } else if (selectorsObject instanceof Object[]) { for (Object s : (Object[]) selectorsObject) { String selector = coerceString(s); if (StringUtils.isNotEmpty(selector)) { selectors.remove(selector); } } } else if (selectorsObject == null) { selectors.clear(); } String selectorString = getSelectorString(selectors); if (StringUtils.isEmpty(selectorString)) { dispatcherOptionsMap.put(OPTION_REPLACE_SELECTORS, " "); } else { dispatcherOptionsMap.put(OPTION_ADD_SELECTORS, getSelectorString(selectors)); dispatcherOptionsMap.put(OPTION_REPLACE_SELECTORS, " "); } } return dispatcherOptionsMap; }
From source file:org.apache.jackrabbit.core.security.authentication.AbstractLoginModule.java
/** * Method which logs out a <code>Subject</code>. * <p/>/*from w ww . ja v a 2s . c om*/ * <p>An implementation of this method might remove/destroy a Subject's * Principals and Credentials. * <p/> * <p/> * * @return true if this method succeeded, or false if this * <code>LoginModule</code> should be ignored. * @throws LoginException if the logout fails */ public boolean logout() throws LoginException { Set thisPrincipals = subject.getPrincipals(); Set thisCredentials = subject.getPublicCredentials(SimpleCredentials.class); if (thisPrincipals == null || thisCredentials == null || thisPrincipals.isEmpty() || thisCredentials.isEmpty()) { return false; } else { thisPrincipals.clear(); thisCredentials.clear(); return true; } }
From source file:edu.brown.benchmark.seats.SEATSClient.java
protected final void clearCache() { for (BitSet seats : CACHE_BOOKED_SEATS.values()) { seats.clear();/*from ww w . j a v a 2 s .com*/ } // FOR for (Buffer<Reservation> queue : CACHE_RESERVATIONS.values()) { queue.clear(); } // FOR for (Set<Long> f_ids : CACHE_CUSTOMER_BOOKED_FLIGHTS.values()) { synchronized (f_ids) { f_ids.clear(); } // SYNCH } // FOR }
From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java
/** * Populates an array of photo IDs that need to be loaded. *///from ww w .ja v a 2s . c o m private void obtainPhotoIdsAndUrisToLoad(Set<Long> photoIds, Set<String> photoIdsAsStrings, Set<Uri> uris) { photoIds.clear(); photoIdsAsStrings.clear(); uris.clear(); /* * Since the call is made from the loader thread, the map could be * changing during the iteration. That's not really a problem: * ConcurrentHashMap will allow those changes to happen without throwing * exceptions. Since we may miss some requests in the situation of * concurrent change, we will need to check the map again once loading * is complete. */ Iterator<Request> iterator = mPendingRequests.values().iterator(); while (iterator.hasNext()) { Request request = iterator.next(); BitmapHolder holder = mBitmapHolderCache.get(request); if (holder == null || !holder.fresh) { if (request.isUriRequest()) { uris.add(request.mUri); } else { photoIds.add(request.mId); photoIdsAsStrings.add(String.valueOf(request.mId)); } } } }
From source file:org.apache.syncope.core.rest.data.UserDataBinder.java
/** * Update user, given UserMod./*from w ww . j ava 2 s . c om*/ * * @param toBeUpdated user to be updated * @param userMod bean containing update request * @return updated user + propagation by resource * @see PropagationByResource */ public PropagationByResource update(final SyncopeUser toBeUpdated, final UserMod userMod) { // Re-merge any pending change from workflow tasks SyncopeUser user = userDAO.save(toBeUpdated); PropagationByResource propByRes = new PropagationByResource(); SyncopeClientCompositeException scce = SyncopeClientException.buildComposite(); Set<String> currentResources = user.getResourceNames(); // password if (StringUtils.isNotBlank(userMod.getPassword())) { setPassword(user, userMod.getPassword(), scce); user.setChangePwdDate(new Date()); propByRes.addAll(ResourceOperation.UPDATE, currentResources); } // username if (userMod.getUsername() != null && !userMod.getUsername().equals(user.getUsername())) { String oldUsername = user.getUsername(); user.setUsername(userMod.getUsername()); propByRes.addAll(ResourceOperation.UPDATE, currentResources); for (ExternalResource resource : user.getResources()) { for (AbstractMappingItem mapItem : resource.getUmapping().getItems()) { if (mapItem.isAccountid() && mapItem.getIntMappingType() == IntMappingType.Username) { propByRes.addOldAccountId(resource.getName(), oldUsername); } } } } // attributes, derived attributes, virtual attributes and resources propByRes.merge(fill(user, userMod, AttributableUtil.getInstance(AttributableType.USER), scce)); // store the role ids of membership required to be added Set<Long> membershipToBeAddedRoleIds = new HashSet<Long>(); for (MembershipMod membToBeAdded : userMod.getMembershipsToAdd()) { membershipToBeAddedRoleIds.add(membToBeAdded.getRole()); } final Set<String> toBeDeprovisioned = new HashSet<String>(); final Set<String> toBeProvisioned = new HashSet<String>(); // memberships to be removed for (Long membershipId : userMod.getMembershipsToRemove()) { LOG.debug("Membership to be removed: {}", membershipId); Membership membership = membershipDAO.find(membershipId); if (membership == null) { LOG.debug("Invalid membership id specified to be removed: {}", membershipId); } else { if (!membershipToBeAddedRoleIds.contains(membership.getSyncopeRole().getId())) { toBeDeprovisioned.addAll(membership.getSyncopeRole().getResourceNames()); } // In order to make the removeMembership() below to work, // we need to be sure to take exactly the same membership // of the user object currently in memory (which has potentially // some modifications compared to the one stored in the DB membership = user.getMembership(membership.getSyncopeRole().getId()); if (membershipToBeAddedRoleIds.contains(membership.getSyncopeRole().getId())) { Set<Long> attributeIds = new HashSet<Long>(membership.getAttrs().size()); for (AbstractAttr attribute : membership.getAttrs()) { attributeIds.add(attribute.getId()); } for (Long attributeId : attributeIds) { attrDAO.delete(attributeId, MAttr.class); } attributeIds.clear(); // remove derived attributes for (AbstractDerAttr derAttr : membership.getDerAttrs()) { attributeIds.add(derAttr.getId()); } for (Long derAttrId : attributeIds) { derAttrDAO.delete(derAttrId, MDerAttr.class); } attributeIds.clear(); // remove virtual attributes for (AbstractVirAttr virAttr : membership.getVirAttrs()) { attributeIds.add(virAttr.getId()); } for (Long virAttrId : attributeIds) { virAttrDAO.delete(virAttrId, MVirAttr.class); } attributeIds.clear(); } else { user.removeMembership(membership); membershipDAO.delete(membershipId); } } } // memberships to be added for (MembershipMod membershipMod : userMod.getMembershipsToAdd()) { LOG.debug("Membership to be added: role({})", membershipMod.getRole()); SyncopeRole role = roleDAO.find(membershipMod.getRole()); if (role == null) { LOG.debug("Ignoring invalid role {}", membershipMod.getRole()); } else { Membership membership = user.getMembership(role.getId()); if (membership == null) { membership = new Membership(); membership.setSyncopeRole(role); membership.setSyncopeUser(user); user.addMembership(membership); toBeProvisioned.addAll(role.getResourceNames()); } propByRes.merge(fill(membership, membershipMod, AttributableUtil.getInstance(AttributableType.MEMBERSHIP), scce)); } } propByRes.addAll(ResourceOperation.DELETE, toBeDeprovisioned); propByRes.addAll(ResourceOperation.UPDATE, toBeProvisioned); /** * In case of new memberships all the current resources have to be updated in order to propagate new role and * membership attribute values. */ if (!toBeDeprovisioned.isEmpty() || !toBeProvisioned.isEmpty()) { currentResources.removeAll(toBeDeprovisioned); propByRes.addAll(ResourceOperation.UPDATE, currentResources); } return propByRes; }
From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByConsumerByServiceByMethod.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {/* w w w . jav a 2 s. co m*/ PreparedStatement cmd = null; ResultSet rs = null; DefaultCategoryDataset set = new DefaultCategoryDataset(); JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append( "<table class=\"table table-hover\"><tr><th>URL</th><th>Consumer</th><th>Method</th><th>Invocations</th></tr>"); Set<String> consumers2 = new HashSet<String>(); List<String> actions = new ArrayList<String>(); for (int k = 0; k < urls.size(); k++) { if (!isPolicyTypeOf(urls.get(k), PolicyType.TRANSACTIONAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(k), classification, ctx)) { continue; } String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(k))); consumers2.clear(); actions.clear(); try { actions = getSoapActions(urls.get(k), con); rs = null; for (int k2 = 0; k2 < actions.size(); k2++) { try { consumers2.clear(); cmd = con.prepareStatement( "select consumeridentity from rawdata where uri=? and (UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=? group by consumeridentity;"); cmd.setString(1, urls.get(k)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); cmd.setString(4, actions.get(k2)); rs = cmd.executeQuery(); while (rs.next()) { String s = rs.getString(1); // log.log(Level.WARN, " debug INVOCATIONS_BY_CONSUMER_BY_SERVICE url:" + urls.get(k) + " user: " + s); if (!Utility.stringIsNullOrEmpty(s)) { String ids[] = s.split(";"); for (int i = 0; i < ids.length; i++) { if (!Utility.stringIsNullOrEmpty(ids[i])) { // log.log(Level.WARN, " debug2 INVOCATIONS_BY_CONSUMER_BY_SERVICE url:" + urls.get(k) + " user: " + ids[i]); if (!consumers2.contains(ids[i])) { consumers2.add(ids[i]); } } } } } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } consumers2.add("unspecified"); //ok for this service, count the times each consumer as hit it Iterator<String> iterator = consumers2.iterator(); while (iterator.hasNext()) { String u = iterator.next(); long count = 0; try { cmd = con.prepareStatement( "select count(*) from RawData where URI=? and soapaction=? and " + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity ~* ?;"); cmd.setString(1, urls.get(k)); cmd.setString(2, actions.get(k2)); cmd.setLong(3, range.getStart().getTimeInMillis()); cmd.setLong(4, range.getEnd().getTimeInMillis()); cmd.setString(5, u); rs = cmd.executeQuery(); try { if (rs.next()) { count = rs.getLong(1); } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } if (count > 0) { //cut down on the noise data.append("<tr><td>").append(url).append("</td><td>") .append(Utility.encodeHTML(u)).append("</td><td>") .append(Utility.encodeHTML(actions.get(k2))).append("</td><td>"); data.append(count + ""); data.append("</td></tr>"); set.addValue(count, u, urls.get(k) + " " + actions.get(k2)); } } long count = 0; try { cmd = con.prepareStatement( "select count(*) from RawData where URI=? and soapaction=? and " + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity is null;"); cmd.setString(1, urls.get(k)); cmd.setString(2, actions.get(k2)); cmd.setLong(3, range.getStart().getTimeInMillis()); cmd.setLong(4, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); try { if (rs.next()) { count = rs.getLong(1); } } catch (Exception ex) { log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } if (count > 0) { //cut down on the noise data.append("<tr><td>").append(url).append("</td><td>unspecified</td><td>") .append(Utility.encodeHTML(actions.get(k2))).append("</td><td>"); data.append(count + ""); data.append("</td></tr>"); set.addValue(count, "unspecified", url + " " + actions.get(k2)); } } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } // insert query for unspecified chart = org.jfree.chart.ChartFactory.createBarChart(toFriendlyName(get.getType()), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false); data.append("</table>"); chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false); try { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, pixelHeightCalc(set.getColumnCount())); } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:com.glaf.core.db.TransformTable.java
protected void transform(QueryDefinition queryDefinition, Map<String, ColumnDefinition> columnMap, List<String> aggregationKeys, Map<String, TableModel> resultMap) { Map<String, Object> params = SystemConfig.getContextMap(); StringBuffer sb = new StringBuffer(1000); String sql = queryDefinition.getSql(); sql = QueryUtils.replaceSQLVars(sql); sql = QueryUtils.replaceSQLParas(sql, params); logger.debug("sql=" + sql); logger.debug("columnMap=" + columnMap.keySet()); Long databaseId = queryDefinition.getDatabaseId(); String systemName = Environment.getCurrentSystemName(); List<ColumnModel> cellModelList = new java.util.ArrayList<ColumnModel>(); try {/*w w w . j ava2s . c om*/ Database database = getDatabaseService().getDatabaseById(databaseId); if (database != null) { Environment.setCurrentSystemName(database.getName()); } List<Map<String, Object>> rows = getTablePageService().getListData(sql, params); if (rows != null && !rows.isEmpty()) { logger.debug(queryDefinition.getTitle() + " " + rows.size()); logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag()); logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn()); /** * ???? */ if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C") && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && rows.size() == 1) { Map<String, Object> dataMap = rows.get(0); logger.debug("?dataMap?:" + dataMap); ColumnDefinition idField = columnMap.get(aggregationKeys.get(0).toLowerCase()); ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase()); if (idField != null && field != null) { String javaType = field.getJavaType(); List<TableModel> list = new ArrayList<TableModel>(); Set<Entry<String, Object>> entrySet = dataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } TableModel tableModel = new TableModel(); tableModel.setTableName(queryDefinition.getTargetTableName()); ColumnModel cell = new ColumnModel(); cell.setColumnName(queryDefinition.getRotatingColumn()); cell.setType(javaType); // logger.debug(cell.getColumnName()+"->"+javaType); if ("String".equals(javaType)) { cell.setStringValue(ParamUtils.getString(dataMap, key)); cell.setValue(cell.getStringValue()); } else if ("Integer".equals(javaType)) { cell.setIntValue(ParamUtils.getInt(dataMap, key)); cell.setValue(cell.getIntValue()); } else if ("Long".equals(javaType)) { cell.setLongValue(ParamUtils.getLong(dataMap, key)); cell.setValue(cell.getLongValue()); } else if ("Double".equals(javaType)) { cell.setDoubleValue(ParamUtils.getDouble(dataMap, key)); cell.setValue(cell.getDoubleValue()); } else if ("Date".equals(javaType)) { cell.setDateValue(ParamUtils.getDate(dataMap, key)); cell.setValue(cell.getDateValue()); } else { cell.setValue(value); } tableModel.addColumn(cell); ColumnModel idColumn = new ColumnModel(); idColumn.setColumnName(aggregationKeys.get(0)); idColumn.setJavaType(idField.getJavaType()); idColumn.setValue(key); tableModel.setIdColumn(idColumn); list.add(tableModel); } logger.debug("update datalist:" + list); Environment.setCurrentSystemName(systemName); getTableDataService().updateTableData(list); } } else { Set<String> cols = new HashSet<String>(); for (Map<String, Object> dataMap : rows) { sb.delete(0, sb.length()); cols.clear(); cellModelList.clear(); logger.debug("dataMap:" + dataMap); Set<Entry<String, Object>> entrySet = dataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } /** * ???? */ if (cols.contains(key.toLowerCase())) { continue; } if (columnMap.get(key.toLowerCase()) == null) { logger.debug(key + " definition is null"); continue; } if (aggregationKeys.contains(key.toLowerCase())) { sb.append(value).append("_"); } ColumnDefinition column = columnMap.get(key.toLowerCase()); String javaType = column.getJavaType(); ColumnModel cell = new ColumnModel(); cell.setColumnName(column.getColumnName()); cell.setType(javaType); // logger.debug(cell.getColumnName()+"->"+javaType); if ("String".equals(javaType)) { cell.setStringValue(ParamUtils.getString(dataMap, key)); cell.setValue(cell.getStringValue()); } else if ("Integer".equals(javaType)) { cell.setIntValue(ParamUtils.getInt(dataMap, key)); cell.setValue(cell.getIntValue()); } else if ("Long".equals(javaType)) { cell.setLongValue(ParamUtils.getLong(dataMap, key)); cell.setValue(cell.getLongValue()); } else if ("Double".equals(javaType)) { cell.setDoubleValue(ParamUtils.getDouble(dataMap, key)); cell.setValue(cell.getDoubleValue()); } else if ("Date".equals(javaType)) { cell.setDateValue(ParamUtils.getDate(dataMap, key)); cell.setValue(cell.getDateValue()); } else { cell.setValue(value); } cellModelList.add(cell); cols.add(cell.getColumnName()); // logger.debug(cell.getColumnName()+"->"+javaType+":"+cell.getValue()); } // logger.debug(sb.toString()); /** * ?? */ if (sb.toString().endsWith("_")) { sb.delete(sb.length() - 1, sb.length()); String rowKey = sb.toString(); logger.debug("rowKey=" + rowKey); TableModel rowModel = resultMap.get(rowKey); if (rowModel == null) { rowModel = new TableModel(); ColumnModel cell01 = new ColumnModel(); cell01.setColumnName("ID"); cell01.setType("String"); cell01.setValueExpression(ExpressionConstants.ID_EXPRESSION); cols.add("ID"); rowModel.addColumn(cell01); rowModel.setIdColumn(cell01); ColumnModel cell04 = new ColumnModel(); cell04.setColumnName("AGGREGATIONKEY"); cell04.setType("String"); cols.add("AGGREGATIONKEY"); rowModel.addColumn(cell04); resultMap.put(rowKey, rowModel); } for (ColumnModel cell : cellModelList) { /** * ?? */ if (columnMap.get(cell.getColumnName().toLowerCase()) != null) { rowModel.addColumn(cell); } } } } } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } finally { Environment.setCurrentSystemName(systemName); } }
From source file:org.andstatus.app.msg.TimelineData.java
private void innerCollapseDuplicates(long itemId, Collection<Pair<TimelinePage, TimelineViewItem>> toCollapse) { Pair<TimelinePage, TimelineViewItem> parent = new Pair<>(null, null); Set<Pair<TimelinePage, TimelineViewItem>> group = new HashSet<>(); for (TimelinePage page : pages) { for (TimelineViewItem item : page.items) { Pair<TimelinePage, TimelineViewItem> itemPair = new Pair<>(page, item); switch (item.duplicates(parent.second)) { case DUPLICATES: break; case IS_DUPLICATED: parent = itemPair;//from w w w. j a va 2 s .c om break; default: if (collapseThisGroup(itemId, parent, group, toCollapse)) { return; } group.clear(); parent = itemPair; break; } group.add(itemPair); } } collapseThisGroup(itemId, parent, group, toCollapse); }
From source file:org.tsm.concharto.lab.PopulateDummyData.java
@Test public void makeData() throws ParseException, IOException { Set<Event> events = new HashSet<Event>(); LapTimer timer = new LapTimer(this); for (int i = 0; i < NUM_EVENTS; i++) { Event event = eventUtil.createEvent(null, getNextPoint(), getNextTimeRange(), null, getNextText(SZ_SUMMARY), getNextText(SZ_DESCRIPTION)); event.setSnippet(null);//from w w w.ja v a 2s .c o m event.setSource(getNextText(SZ_SOURCE)); event.setWhere(getNextText(SZ_WHERE)); event.setUserTagsAsString(getNextText(SZ_TAGS)); events.add(event); if (i % COLLECTION_SIZE == 0) { timer.timeIt("create " + i); eventTesterDao.save(events); timer.timeIt("save").logDebugTime(); events.clear(); timer.init(); } } timer.timeIt("create"); eventTesterDao.save(events); timer.timeIt("save").logDebugTime(); //System.out.println(minLng +", " + minLat + ", " + maxLng + ", " + maxLat ); }
From source file:com.npower.dm.hibernate.management.ProfileAssignmentManagementBeanImpl.java
/** * Add or update the AttributeValue specified by the name. This is modifier of * AttributeValue in multiple-value mode. * // w w w . j a v a 2s . c o m * Caution: Assign null to value is permitted. this will set the value to * null, AttributeValue will not be deleted! * * Caution: Order of AttributeValue will automaticlly increased! The * AttributeValue added lastestly will be bottom. * * @param name * Attribute's name * @param value * String[] array of multi-value * @throws DMException */ public void setAttributeValue(ProfileAssignment assignment, String name, String value[]) throws DMException { // update this profile config, first. make sure the profileID will generated // by hibernate. Session hsession = this.getHibernateSession(); hsession.saveOrUpdate(assignment); Clob[] clobValues = null; if (value != null) { clobValues = new Clob[value.length]; for (int i = 0; value != null && i < value.length; i++) { clobValues[i] = (value[i] == null) ? null : Hibernate.createClob(value[i]); } } // Check exists? Set<ProfileAssignmentValue> vMaps = ((ProfileAssignmentEntity) assignment).getProfileAssignValues(); for (Iterator<ProfileAssignmentValue> i = vMaps.iterator(); i.hasNext();) { ProfileAssignmentValue vMap = (ProfileAssignmentValue) i.next(); ProfileAttributeValueEntity v = (ProfileAttributeValueEntity) vMap.getProfileAttribValue(); if (name.equals(v.getProfileAttribute().getName())) { // In multi-value mode, clear single value; v.setRawData(null); // Set to multi-value mode v.setIsMultiValued(true); v.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_TEXT); v.setMFormat(DDFNode.DDF_FORMAT_CHR); // Clear all of old values. Set<ProfileValueItem> items = v.getProfileValueItems(); for (Iterator<ProfileValueItem> item = items.iterator(); item.hasNext();) { hsession.delete(item.next()); } // clear up the set of items. items.clear(); for (int j = 0; clobValues != null && j < clobValues.length; j++) { // Create a ProfileValueItem ProfileValueItem item = new ProfileValueItem(v); // Inherit property from AttributeValues item.setItemDataKind(v.getItemDataKind()); item.setMFormat(v.getMFormat()); item.setMType(v.getMType()); item.setUpdateId(v.getUpdateId()); // Assign the value item.setRawData(clobValues[j]); hsession.saveOrUpdate(item); // Save into DM inventory items.add(item); } return; } } // Create a new AttributeValue ProfileTemplate template = assignment.getProfileConfig().getProfileTemplate(); ManagementBeanFactory factory = this.getManagementBeanFactory(); ProfileAttribute attr = factory.createProfileTemplateBean().getProfileAttributeByName(template.getName(), name); if (attr == null) { throw new DMException( "Could not find attribute by name: " + name + " from the template: " + template.getName()); } // Create a ProfileAttributeValueEntity ProfileAttributeValueEntity av = new ProfileAttributeValueEntity(); av.setProfileAttribute(attr); // In Multi-value mode, clear the value of single-value mode. av.setRawData(null); // Set to multi-value mode av.setIsMultiValued(true); av.setItemDataKind(ProfileAttributeValue.ITEM_DATA_KIND_TEXT); av.setMFormat(DDFNode.DDF_FORMAT_CHR); hsession.saveOrUpdate(av); // Create all of items from clobValues for (int j = 0; clobValues != null && j < clobValues.length; j++) { // Create a ProfileValueItem ProfileValueItem item = new ProfileValueItem(av); // Inherit the value of properties from ProfileAttributeValueEntity. item.setItemDataKind(av.getItemDataKind()); item.setMFormat(av.getMFormat()); item.setMType(av.getMType()); item.setUpdateId(av.getUpdateId()); // set the value of Clob item.setRawData(clobValues[j]); // Add into DMInventory. hsession.saveOrUpdate(item); // Link the Item to ProfileAttributeValueEntity av.getProfileValueItems().add(item); } // New a ProfileAssignmentValue ProfileAssignmentValueID mapID = new ProfileAssignmentValueID(); mapID.setAttributeValueId(av.getID()); mapID.setProfileAssignmentId(assignment.getID()); // New a ProfileAssignmentValue // long index = this.getProfileValueMaps().size() + 1; ProfileAssignmentValue map = new ProfileAssignmentValue(mapID, av, assignment); // Link to ProfileAssignmentEntity Set<ProfileAssignmentValue> maps = ((ProfileAssignmentEntity) assignment).getProfileAssignValues(); maps.add(map); // Add the ProfileAssignmentEntity into DM inventory. hsession.saveOrUpdate(map); }