List of usage examples for java.util Collection remove
boolean remove(Object o);
From source file:processing.app.Base.java
protected void removeRecentSketchPath(String path) { Collection<String> sketches = new LinkedList<>(PreferencesData.getCollection("recent.sketches")); sketches.remove(path); PreferencesData.setCollection("recent.sketches", sketches); }
From source file:edu.jhuapl.openessence.controller.ReportController.java
private GraphObject createGraph(OeDataSource dataSource, final String userPrincipalName, final Collection<Record> records, final Dimension dimension, final Dimension filter, final Dimension accumulation, DefaultGraphData data, ChartModel chart, List<Filter> filters) { String filterId = (filter == null) ? dimension.getId() : filter.getId(); Map<String, String> possibleKeyValueMap = null; if (dimension.getPossibleValuesConfiguration() != null && dimension.getPossibleValuesConfiguration().getData() != null) { List<List<Object>> dataMap = dimension.getPossibleValuesConfiguration().getData(); possibleKeyValueMap = new HashMap<String, String>(); for (int i = 0; i < dataMap.size(); i++) { String dispVal = dataMap.get(i).size() == 2 ? dataMap.get(i).get(1).toString() : dataMap.get(i).get(0).toString(); possibleKeyValueMap.put(dataMap.get(i).get(0).toString(), dispVal); }//from w ww . ja v a2 s .c om } GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir); GraphObject graph = null; Color[] colorsFromHex = null; //only set an array if they provided one if (!ArrayUtils.isEmpty(chart.getGraphBaseColors())) { colorsFromHex = ControllerUtils.getColorsFromHex(Color.BLUE, chart.getGraphBaseColors()); //TODO when we limit the series these colors need augmented. Create a map of id = graphbasecolor[index] first, then use that map to create a //new graph base color array that combines the parameter list with the default list... data.setGraphBaseColors(colorsFromHex); } GraphController gc = getGraphController(null, hndl, userPrincipalName); List<Record> recs = new ArrayList<Record>(records); String otherLabel = messageSource.getDataSourceMessage("graph.category.other", dataSource); LinkedHashMap<String, ChartData> recordMap = getRecordMap(recs, accumulation.getId(), dimension.getId(), filterId); //perform series limit recordMap = ControllerUtils.getSortedAndLimitedChartDataMap(recordMap, chart.getCategoryLimit(), otherLabel); //if there is no data (all zeros for a pie chart) the chart will not display anything if (!ControllerUtils.isCollectionValued(getCountsForChart(recordMap)) && !chart.isShowNoDataGraph()) { //this will hide the title and message if there is no data data.setGraphTitle(""); data.setNoDataMessage(""); } // Create urls for each slice/bar DataSeriesSource dss = null; StringBuilder jsCall = new StringBuilder(); jsCall.append("javascript:OE.report.datasource.showDetails({"); if (dataSource instanceof DataSeriesSource) { dss = (DataSeriesSource) dataSource; Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions()); Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims); Collection<Dimension> accums = new ArrayList<Dimension>(dss.getAccumulations()); for (Dimension d : accums) { if (dimIds.contains(d.getId()) && d.getId().equals(accumulation.getId())) { } else { dimIds.remove(d.getId()); } } jsCall.append("dsId:'").append(dss.getClass().getName()).append("'"); //specify results jsCall.append(",results:[").append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")) .append(']'); //specify accumId jsCall.append(",accumId:'").append(accumulation.getId()).append("'"); addJavaScriptFilters(jsCall, filters, dimension.getId()); } int rSize = recordMap.size(); int aSize = 1; String[] lbl = new String[rSize]; String[][] txtb = new String[1][rSize]; double[][] bardat = new double[aSize][rSize]; String[][] txtp = new String[rSize][1]; double[][] piedat = new double[rSize][aSize]; String[][] urlsP = new String[rSize][1]; String[][] urlsB = new String[1][rSize]; int i = 0; double totalCount = 0; DecimalFormat df = new DecimalFormat("#.##"); for (String key : recordMap.keySet()) { if (recordMap.get(key) != null && recordMap.get(key).getCount() != null && !recordMap.get(key).getCount().isNaN()) { totalCount += recordMap.get(key).getCount(); } } for (String key : recordMap.keySet()) { Double dubVal = recordMap.get(key).getCount(); String strPercentVal = df.format(100 * dubVal / totalCount); lbl[i] = recordMap.get(key).getName(); //create bar data set bardat[0][i] = dubVal; txtb[0][i] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)"; if (lbl[i].length() > DEFAULT_LABEL_LENGTH) { lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "..."; } //create pie data set piedat[i][0] = dubVal; txtp[i][0] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)"; if (lbl[i].length() > DEFAULT_LABEL_LENGTH) { lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "..."; } //TODO all "Others" to return details of all results except for those in recordMap.keyset //We need a "Not" filter if (!otherLabel.equals(key)) { if (dataSource instanceof DataSeriesSource) { if (dimension.getId().equals(filterId) && possibleKeyValueMap != null) { if (possibleKeyValueMap.containsKey(key)) { urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});"; urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});"; } else { urlsP[i][0] = jsCall.toString() + "});"; urlsB[0][i] = jsCall.toString() + "});"; } } else { if (key == null || key.equals("") || key.equals(messageSource.getMessage("graph.dimension.null", "Empty Value"))) { // TODO: This is when we have an ID field also marked as isResult:true and the value is null // We can not provide url param filterId:null as field can be numeric and we get a java.lang.NumberFormatException... urlsP[i][0] = jsCall.toString() + "});"; urlsB[0][i] = jsCall.toString() + "});"; } else { urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});"; urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});"; } } } } i++; } if (BAR.equalsIgnoreCase(chart.getType())) { data.setCounts(bardat); data.setXLabels(lbl); data.setMaxLabeledCategoryTicks(rSize); data.setAltTexts(txtb); if (jsCall.length() > 0) { data.setLineSetURLs(urlsB); } //TODO add encoding? graph = gc.createBarGraph(data, false, true); } else if (PIE.equalsIgnoreCase(chart.getType())) { data.setCounts(piedat); data.setLineSetLabels(lbl); data.setAltTexts(txtp); if (jsCall.length() > 0) { data.setLineSetURLs(urlsP); } graph = gc.createPieGraph(data, Encoding.PNG_WITH_TRANSPARENCY); } return graph; }
From source file:org.hyperledger.fabric.sdkintegration.End2endMTIT.java
Channel constructChannel(String name, HFClient client, SampleOrg sampleOrg) throws Exception { //////////////////////////// //Construct the channel ///*w w w .ja v a 2 s .c o m*/ out("Constructing channel %s", name); //boolean doPeerEventing = false; boolean doPeerEventing = !testConfig.isRunningAgainstFabric10() && BAR_CHANNEL_NAME.equals(name); // boolean doPeerEventing = !testConfig.isRunningAgainstFabric10() && FOO_CHANNEL_NAME.equals(name); //Only peer Admin org client.setUserContext(sampleOrg.getPeerAdmin()); Collection<Orderer> orderers = new LinkedList<>(); for (String orderName : sampleOrg.getOrdererNames()) { Properties ordererProperties = testConfig.getOrdererProperties(orderName); //example of setting keepAlive to avoid timeouts on inactive http2 connections. // Under 5 minutes would require changes to server side to accept faster ping rates. ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] { 5L, TimeUnit.MINUTES }); ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] { 8L, TimeUnit.SECONDS }); ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveWithoutCalls", new Object[] { true }); orderers.add(client.newOrderer(orderName, sampleOrg.getOrdererLocation(orderName), ordererProperties)); } //Just pick the first orderer in the list to create the channel. Orderer anOrderer = orderers.iterator().next(); orderers.remove(anOrderer); ChannelConfiguration channelConfiguration = new ChannelConfiguration(new File(TEST_FIXTURES_PATH + "/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/" + name + ".tx")); //Create channel that has only one signer that is this orgs peer admin. If channel creation policy needed more signature they would need to be added too. Channel newChannel = client.newChannel(name, anOrderer, channelConfiguration, client.getChannelConfigurationSignature(channelConfiguration, sampleOrg.getPeerAdmin())); out("Created channel %s", name); boolean everyother = true; //test with both cases when doing peer eventing. for (String peerName : sampleOrg.getPeerNames()) { String peerLocation = sampleOrg.getPeerLocation(peerName); Properties peerProperties = testConfig.getPeerProperties(peerName); //test properties for peer.. if any. if (peerProperties == null) { peerProperties = new Properties(); } //Example of setting specific options on grpc's NettyChannelBuilder peerProperties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000); Peer peer = client.newPeer(peerName, peerLocation, peerProperties); if (doPeerEventing && everyother) { newChannel.joinPeer(peer, createPeerOptions()); //Default is all roles. } else { // Set peer to not be all roles but eventing. newChannel.joinPeer(peer, createPeerOptions().setPeerRoles(PeerRole.NO_EVENT_SOURCE)); } out("Peer %s joined channel %s", peerName, name); everyother = !everyother; } //just for testing ... if (doPeerEventing) { // Make sure there is one of each type peer at the very least. assertFalse(newChannel.getPeers(EnumSet.of(PeerRole.EVENT_SOURCE)).isEmpty()); assertFalse(newChannel.getPeers(PeerRole.NO_EVENT_SOURCE).isEmpty()); } for (Orderer orderer : orderers) { //add remaining orderers if any. newChannel.addOrderer(orderer); } for (String eventHubName : sampleOrg.getEventHubNames()) { final Properties eventHubProperties = testConfig.getEventHubProperties(eventHubName); eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] { 5L, TimeUnit.MINUTES }); eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] { 8L, TimeUnit.SECONDS }); EventHub eventHub = client.newEventHub(eventHubName, sampleOrg.getEventHubLocation(eventHubName), eventHubProperties); newChannel.addEventHub(eventHub); } newChannel.initialize(); out("Finished initialization channel %s", name); //Just checks if channel can be serialized and deserialized .. otherwise this is just a waste :) byte[] serializedChannelBytes = newChannel.serializeChannel(); newChannel.initialize(); return newChannel; }
From source file:org.opengroupware.logic.authz.OGoAuthzFetchContext.java
/** * This method fetches object_acl records for all global-ids which are passed * in as a parameter. Only records of the authz-ctx' authids are fetched and * then compressed into a single permission. * /*from www. j a va2 s. c om*/ * @param _gids - the GIDs we want to have the ACLs for * @return a Map containing the GIDs as keys and their permission as the value */ @SuppressWarnings("unchecked") public Exception fetchACLsForGlobalIDs(final Collection<EOKeyGlobalID> _gids) { if (_gids == null) return null; final int gidCount = _gids.size(); if (gidCount == 0) return null; /* everything ok */ /* Extract primary key values from global-ids. This works because pkeys * are unique across tables in OGo. * Also: we set the minimum access-level for each gid in the map, so that * we can be sure that entries w/o ACEs do get the no-access permission. */ final Map<Number, EOKeyGlobalID> pkeyToGlobalID = new HashMap<Number, EOKeyGlobalID>(gidCount + 1); final Collection<Number> pkeysToProcess = new HashSet<Number>(gidCount); for (final EOKeyGlobalID gid : _gids) { /* default access */ this.gidToACLPermission.put(gid, noPermission); this.gidHasACL.put(gid, Boolean.FALSE); /* extract key */ final Number oid = (Number) gid.toNumber(); pkeyToGlobalID.put(oid, gid); /* fetch this */ pkeysToProcess.add(oid); } /* setup fetch environment */ final EODatabase db = this.oCtx != null ? this.oCtx.database() : null; final EOEntity aclEntity = db.entityNamed("ACLEntries"); EOAccessDataSource ads = new EOAdaptorDataSource(db.adaptor(), aclEntity); List<Map<String, Object>> results = ads.fetchObjects("authzFetch", "authIds", this.authIds, "ids", pkeysToProcess); if (results == null) return ads.consumeLastException(); for (int i = results.size() - 1; i >= 0; i--) { final Map<String, Object> ace = results.get(i); final String perms = (String) ace.get("permissions"); final Number oid = (Number) ace.get("object_id"); // watch for Go changes if (perms == null || oid == null) { log.warn("found ACE w/o oid or permissions: " + ace); continue; } EOKeyGlobalID gid = pkeyToGlobalID.get(oid); /* there where results for the GID, remember this fact */ this.gidHasACL.put(gid, true); pkeysToProcess.remove(oid); /* process permissions */ final int permsLen = perms.length(); if (permsLen == 0) continue; /* perm empty, won't add anything */ final String currentPerms = this.gidToACLPermission.get(gid); this.gidToACLPermission.put(gid, UString.unionCharacterSets(perms, currentPerms)); } /* fetch counts */ if (pkeysToProcess.size() > 0) { // TBD: Could we do this in some kind of join with the fetch above? // Probably not, but maybe we could make a union. // We also have the option to do the GROUP BY in memory at the // expense of having to transfer all ACEs of an ACL. if (log.isDebugEnabled()) log.debug(" fetch-acl-count: #" + pkeysToProcess.size()); results = ads.fetchObjects("authzCountFetch", "ids", pkeysToProcess); if (results == null) return ads.consumeLastException(); for (int i = results.size() - 1; i >= 0; i--) { final Map<String, Object> objectAclCount = results.get(i); final Number oid = (Number) objectAclCount.get("object_id"); final EOKeyGlobalID gid = pkeyToGlobalID.get(oid); this.gidHasACL.put(gid, true); } } return null; /* everything OK */ }
From source file:org.openmrs.module.webservices.rest.web.v1_0.resource.openmrs1_8.ModuleActionResource1_8.java
/** * Overriding create directly, because ModuleFactory requires ServletContext to execute any * action/*w ww . j a va 2 s . c om*/ */ @Override public Object create(SimpleObject post, RequestContext context) throws ResponseException { moduleFactoryWrapper.checkPrivilege(); ModuleAction action = newDelegate(); setConvertedProperties(action, post, getCreatableProperties(), true); String installUri = action.getInstallUri(); Collection<Module> modules; if (action.isAllModules() != null && action.isAllModules()) { modules = moduleFactoryWrapper.getLoadedModules(); action.setModules(new ArrayList<Module>(modules)); } else { modules = action.getModules(); } ServletContext servletContext = getServletContext(context); if (modules == null || modules.isEmpty()) { throw new IllegalRequestException( "Cannot execute action " + action.getAction() + " on empty set of modules."); } else { if (action.getAction() == Action.INSTALL) { if (installUri == null || !ResourceUtils.isUrl(installUri)) { throw new IllegalRequestException( "The installUri needs to be a URL for this action to be performed"); } } else { if (action.isAllModules() == null || !action.isAllModules()) { // ensure all specified modules exist // ensure they're not trying to modify the REST module for (Module module : modules) { // if they specified a module that's not loaded, it will show up here as null if (module == null) { throw new IllegalRequestException( "One or more of the modules you specified are not loaded on this server"); } if (module.getModuleId().equals(RestConstants.MODULE_ID)) { throw new IllegalRequestException("You are not allowed to modify " + module.getModuleId() + " via this REST call"); } } } // even if they said allModule=true, don't touch the REST module Module restModule = moduleFactoryWrapper.getModuleById(RestConstants.MODULE_ID); modules.remove(restModule); } switch (action.getAction()) { case START: startModules(modules, servletContext); break; case STOP: stopModules(modules, servletContext, true); break; case RESTART: restartModules(modules, servletContext); break; case UNLOAD: unloadModules(modules, servletContext); break; case INSTALL: Module module = installModule(modules, installUri, servletContext); modules.clear(); modules.add(module); action.setModules(new ArrayList<Module>(modules)); break; } } return ConversionUtil.convertToRepresentation(action, Representation.DEFAULT); }
From source file:org.ms123.common.data.MultiOperations.java
public static void populate(SessionContext sessionContext, Map sourceMap, Object destinationObj, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from w w w . j a v a2 s. com boolean noUpdate = Utils.getBoolean(hintsMap, "noUpdate", false); BeanMap destinationMap = new BeanMap(destinationObj); String entityName = m_inflector.getEntityName(destinationObj.getClass().getSimpleName()); debug("populate.sourceMap:" + sourceMap + ",destinationObj:" + destinationObj + ",destinationMap:" + destinationMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (sourceMap == null) { return; } debug("populate(" + entityName + ") is a persistObject:" + javax.jdo.JDOHelper.isPersistent(destinationObj) + "/" + javax.jdo.JDOHelper.isNew(destinationObj)); if (sourceMap.get("id") != null) { debug("populate(" + entityName + ") has id:" + sourceMap.get("id")); return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = sourceMap.keySet().iterator(); while (it.hasNext()) { String propertyName = it.next(); boolean permitted = sessionContext.getPermissionService().hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(propertyName, entityName, "write"); if (!propertyName.startsWith("_") && !permitted) { debug("---->populate:field(" + propertyName + ") no write permission"); continue; } else { debug("++++>populate:field(" + propertyName + ") write permitted"); } String datatype = null; String edittype = null; if (!propertyName.startsWith("_")) { Map config = (Map) permittedFields.get(propertyName); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (propertyName.equals(STATE_FIELD) && !sessionContext.getPermissionService().hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(propertyName); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class propertyClass = destinationMap.getType(propertyName); debug("\ttype:" + propertyClass + "(" + propertyName + "=" + sourceMap.get(propertyName) + ")"); if ("_ignore_".equals(sourceMap.get(propertyName))) { continue; } if (propertyClass == null) { debug("\t--- Warning property not found:" + propertyName); } else if (propertyClass.equals(java.util.Date.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); debug("\tDate found:" + propertyName + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); destinationMap.put(propertyName, date); } else if (propertyClass.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (propertyClass.equals(java.util.List.class) || propertyClass.equals(java.util.Set.class)) { boolean isList = propertyClass.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + " fill with: " + sourceMap.get(propertyName) + ",list:" + destinationMap.get(propertyName) + "/mode:" + mode); Collection sourceList = isList ? new ArrayList() : new HashSet(); Object fromVal = sourceMap.get(propertyName); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (sourceMap.get(propertyName) instanceof Collection) { sourceList = (Collection) sourceMap.get(propertyName); } if (sourceList == null) { sourceList = isList ? new ArrayList() : new HashSet(); } Collection destinationList = (Collection) PropertyUtils.getProperty(destinationObj, propertyName); debug("destinationList:" + destinationList); debug("sourceList:" + sourceList); if (destinationList == null) { destinationList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(destinationObj, propertyName, destinationList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(destinationList, sourceList); if (!isEqual) { destinationList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : destinationList) { if (propertyType.getName().endsWith(".Team")) { int status = sessionContext.getTeamService().getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { destinationList.remove(o); } } debug("populate.replace.destinationList:" + destinationList + "/" + propertyType.getName()); if (isSimple) { if (!isEqual) { for (Object o : sourceList) { destinationList.add(o); } } } else { for (Object o : sourceList) { Map childSourceMap = (Map) o; Object childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { childSourceMap.remove("id"); Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } debug("populated.add:" + new HashMap(new BeanMap(childDestinationObj))); destinationList.add(childDestinationObj); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : sourceList) { if (destinationList.contains(o)) { destinationList.remove(o); } } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object o = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (o != null) { destinationList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : sourceList) { destinationList.add(o); } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (childDestinationObj != null) { populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } destinationList.add(childDestinationObj); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap); if (childDestinationObj != null) { debug("id:" + childSourceMap + " already assigned"); } else { Object id = childSourceMap.get("id"); Boolean assign = Utils.getBoolean(childSourceMap.get("assign")); Object obj = pm.getObjectById(propertyType, id); if (assign) { destinationList.add(obj); } else { destinationList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Boolean.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Double.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { destinationMap.put(propertyName, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + propertyName + "=>" + value + ";" + e); } } else if (propertyClass.equals(java.lang.Long.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if ("binary".equals(datatype) || propertyClass.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (sourceMap.get(propertyName) instanceof FileItem) { FileItem fi = (FileItem) sourceMap.get(propertyName); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } destinationMap.put(propertyName, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (sourceMap.get(propertyName) instanceof Map) { Map map = (Map) sourceMap.get(propertyName); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); destinationMap.put(propertyName, bytes); is = new FileInputStream(new File(storeLocation)); } else if (sourceMap.get(propertyName) instanceof String) { String value = (String) sourceMap.get(propertyName); if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); destinationMap.put(propertyName, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { } } else { debug("populate.byte[].no a FileItem:" + propertyName + "=>" + sourceMap.get(propertyName)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { destinationMap.put("text", text); } catch (Exception e) { destinationMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); destinationMap.put("type", mime.toString()); sourceMap.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + "/" + propertyName); if (propertyType != null) { boolean hasAnn = propertyType.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (propertyType.newInstance() instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { handleRelatedTo(sessionContext, sourceMap, propertyName, destinationMap, destinationObj, propertyType); Object obj = sourceMap.get(propertyName); if (obj != null && obj instanceof Map) { Map childSourceMap = (Map) obj; Object childDestinationObj = destinationMap.get(propertyName); if (childDestinationObj == null) { childDestinationObj = propertyType.newInstance(); destinationMap.put(propertyName, childDestinationObj); } populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { if (obj == null) { destinationMap.put(propertyName, null); } } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { if (noUpdate) { if (Utils.isEmptyObj(destinationMap.get(propertyName))) { destinationMap.put(propertyName, value); } } else { destinationMap.put(propertyName, value); } } catch (Exception e) { debug("populate.failed:" + propertyName + "=>" + value + ";" + e); } } } } }
From source file:org.hyperic.hq.autoinventory.server.session.AutoinventoryManagerImpl.java
private void addAIServersToAIPlatform(ScanStateCore stateCore, ScanState state, AIPlatformValue aiPlatform) throws AutoinventoryException { if (stateCore.getAreServersIncluded()) { // TODO: G Set<AIServerValue> serverSet = state.getAllServers(); Collection<Server> removableServers = null; AuthzSubject subject = getHQAdmin(); Platform p = null;/*from ww w . j av a2s . co m*/ try { p = platformManager.getPlatformByAIPlatform(subject, aiPlatform); } catch (Exception e) { log.error("failed finding a platform for AI platform " + aiPlatform.getName() + " with the following exception: " + e.getMessage(), e); } try { if (p != null) { boolean allowRemoveServers = allowToRemoveServers(aiPlatform); log.debug("allow remove children=" + allowRemoveServers); if (allowRemoveServers) { removableServers = serverManager.getRemovableChildren(subject, p.getResource()); } } } catch (Exception e) { log.error("failed getting removable servers with the following exception: " + e.getMessage(), e); } for (AIServerValue aiServer : serverSet) { // Ensure the server reported has a valid appdef type try { serverManager.findServerTypeByName(aiServer.getServerTypeName()); // don't delete servers which are removable but still discoverable by the agent if (p != null && removableServers != null && !removableServers.isEmpty()) { Server s = serverManager.getServerByName(p, aiServer.getName()); removableServers.remove(s); } } catch (NotFoundException e) { log.error("Ignoring non-existent server type: " + aiServer.getServerTypeName(), e); continue; } aiPlatform.addAIServerValue(aiServer); } if (removableServers != null && !removableServers.isEmpty()) { for (Server s : removableServers) { try { appdefManager.removeAppdefEntity(s.getResource(), s.getId(), AppdefEntityConstants.APPDEF_TYPE_SERVER, subject, true); } catch (VetoException e) { log.error("failed removing resource " + s.getName() + " with the following exception: " + e.getMessage(), e); } catch (PermissionException e) { log.error("failed removing resource " + s.getName() + " with the following exception: " + e.getMessage(), e); } catch (ApplicationException e) { log.error("failed removing resource " + s.getName() + " with the following exception: " + e.getMessage(), e); } } } } }
From source file:ubic.gemma.core.loader.expression.arrayDesign.ArrayDesignSequenceProcessingServiceImpl.java
@Override public Collection<BioSequence> processArrayDesign(ArrayDesign arrayDesign, InputStream sequenceIdentifierFile, String[] databaseNames, String blastDbHome, Taxon taxon, boolean force, FastaCmd fc) throws IOException { this.checkForCompositeSequences(arrayDesign); Map<String, String> probe2acc = this.parseAccessionFile(sequenceIdentifierFile); // values that were not found Collection<String> notFound = new HashSet<>(probe2acc.values()); // the actual thing values to search for (with version numbers) Collection<String> accessionsToFetch = new HashSet<>(probe2acc.values()); // only 1 taxon should be on array design if taxon not supplied on command line taxon = this.validateTaxon(taxon, arrayDesign); /*//from ww w . ja v a2s . c om * Fill in sequences from BLAST databases. */ int numSwitched = 0; if (fc == null) fc = new SimpleFastaCmd(); Collection<BioSequence> retrievedSequences = this.searchBlastDbs(databaseNames, blastDbHome, notFound, fc); // map of accessions to sequence. Map<String, BioSequence> found = this.findOrUpdateSequences(accessionsToFetch, retrievedSequences, taxon, force); Collection<BioSequence> finalResult = new HashSet<>(retrievedSequences); // replace the sequences. numSwitched = this.replaceSequences(arrayDesign, probe2acc, numSwitched, found); notFound = this.getUnFound(notFound, found); if (!notFound.isEmpty() && taxon != null) { Collection<String> stillLooking = new HashSet<>(notFound); notFound.clear(); /* * clear the version number. */ for (String accession : stillLooking) { notFound.remove(accession); accession = accession.replaceFirst("\\.\\d+$", ""); notFound.add(accession); } assert notFound.size() > 0; /* * See if they're already in Gemma. This is good for sequences that are not in genbank but have been loaded * previously. */ found = this.findLocalSequences(notFound, taxon); finalResult.addAll(found.values()); numSwitched = this.replaceSequences(arrayDesign, probe2acc, numSwitched, found); notFound = this.getUnFound(notFound, found); } if (!notFound.isEmpty()) { this.logMissingSequences(arrayDesign, notFound); } ArrayDesignSequenceProcessingServiceImpl.log .info(numSwitched + " composite sequences had their biologicalCharacteristics changed"); arrayDesignService.update(arrayDesign); arrayDesignReportService.generateArrayDesignReport(arrayDesign.getId()); return finalResult; }
From source file:com.surevine.alfresco.repo.action.EnhancedSecurityModelGroupRemovalBehaviour.java
/** * Only allow the update if no previous groups, except those listed in the authorisedDeletion property, have been removed. We only care about removal * from the model - it's OK to change the type of a group. * /* ww w . j a v a 2s .c o m*/ * Additionally, please note that groups that are commented out are _NOT_ counted as having been removed. This shouldn't be a problem ibn production, * but could cause confusion during test */ @SuppressWarnings("unchecked") @Override public void onContentUpdate(NodeRef nodeRef, boolean newContent) { if (_nodeService.exists(nodeRef)) { // Q.Only interested in? workspace://SpacesStore/enhanced_security_custom_model // A. Sorta. We're interested in anything with the psg:groups aspect applied, which will (at time of writing) only be one file. // This is taken care of us by the call to policyComponent in the init() method so we don't have to worry about it here, if we bind on init. // If we don't bind on init, then it's up to the caller to call us at the right time! //Get the new content and load it into a string ContentReader reader = _contentService.getReader(nodeRef, ContentModel.PROP_CONTENT); String newContentString = reader.getContentString(); LOGGER.trace("New Model: " + newContentString); Collection<String> valuesAfterUpdate = getGroupNamesFromModelContent(newContentString); //Get (and log) the list of groups it's OK to remove @SuppressWarnings("rawtypes") Collection<String> authorisedGroupsToRemove = (Collection) (_nodeService.getProperty(nodeRef, _authorisedGroupsToRemoveQName)); if (LOGGER.isDebugEnabled()) { String s = "undefined"; if (authorisedGroupsToRemove != null) { s = StringUtils.join(authorisedGroupsToRemove.toArray(), ","); LOGGER.debug(authorisedGroupsToRemove.size() + " authorised groups to remove: " + s); } else { LOGGER.debug("No groups are authorised for removal"); } } // This is the set of values allowed after the update. Usually retrieved from LDAP. final String allowedValues = StringUtils.join(valuesAfterUpdate.toArray(), ','); LOGGER.debug("The Model is now allowed the values: " + allowedValues); //Get the previous values. if it's not present, just allow the update Object previousValuesPropVal = _nodeService.getProperty(nodeRef, _previousValuesPropertyName); if (previousValuesPropVal == null) { LOGGER.debug("Existing property: " + _previousValuesPropertyName + " could not be found"); } else { Collection<String> valuesBeforeUpdate = Arrays.asList(previousValuesPropVal.toString().split(",")); // This is the set of values previously allowed. Retrieved from Alfresco. LOGGER.debug("The model was allowed the values: " + previousValuesPropVal.toString()); //For each group before the update, if it's not in the file after the update, then see if it's in the list of groups to delete. If it isn't, abort Iterator<String> groupNamesBeforeUpdate = valuesBeforeUpdate.iterator(); while (groupNamesBeforeUpdate.hasNext()) { String groupName = groupNamesBeforeUpdate.next(); LOGGER.debug("Checking for the presence of: " + groupName); if (!safeContains(groupName, valuesAfterUpdate)) { if (authorisedGroupsToRemove != null && safeContains(groupName, authorisedGroupsToRemove)) { authorisedGroupsToRemove.remove(groupName); _nodeService.setProperty(nodeRef, _authorisedGroupsToRemoveQName, new ArrayList<String>(authorisedGroupsToRemove)); } else { throw new EnhancedSecurityException("The group: " + groupName + " was removed and was not in the authorised removal list"); } } } } _nodeService.setProperty(nodeRef, _previousValuesPropertyName, allowedValues.toString()); } else { LOGGER.debug("The node does not exist: " + nodeRef); } }
From source file:org.andromda.cartridges.gui.metafacades.GuiUseCaseLogicImpl.java
private void collectTypeMessages(final Map<String, String> messages, ClassifierFacade type, final Collection<ClassifierFacade> resolvingTypes) { if (type != null) { if (!resolvingTypes.contains(type)) { resolvingTypes.add(type);//from w w w . ja v a 2 s .co m if (type.isArrayType()) { type = type.getNonArray(); } // check again, since the type can be changed if (!resolvingTypes.contains(type)) { this.collectAttributeMessages(messages, type.getAttributes(), resolvingTypes); this.collectAssociationEndMessages(messages, type.getNavigableConnectingEnds(), resolvingTypes); } } resolvingTypes.remove(type); } }