List of usage examples for java.util List containsAll
boolean containsAll(Collection<?> c);
From source file:com.linkedin.pinot.controller.helix.core.rebalance.ReplicaGroupRebalanceSegmentStrategy.java
/** * Compute the new replica group mapping based on the new configurations * @param tableConfig a talbe config/*from w w w . jav a 2 s . c om*/ * @param partitionAssignmentGenerator partition assignment generator * @return new replica group partition assignment */ private ReplicaGroupPartitionAssignment computeNewReplicaGroupMapping(TableConfig tableConfig, ReplicaGroupPartitionAssignmentGenerator partitionAssignmentGenerator) throws InvalidConfigException { ReplicaGroupStrategyConfig replicaGroupConfig = tableConfig.getValidationConfig() .getReplicaGroupStrategyConfig(); // If no replica group config is available in table config, we cannot perform the rebalance algorithm if (replicaGroupConfig == null) { throw new InvalidConfigException("This table is not using replica group segment assignment"); } // Currently, only table level replica group rebalance is supported if (replicaGroupConfig.getPartitionColumn() != null) { throw new InvalidConfigException("Partition level replica group rebalance is not supported"); } // Fetch the information required for computing new replica group partition assignment int targetNumInstancesPerPartition = replicaGroupConfig.getNumInstancesPerPartition(); int targetNumReplicaGroup = tableConfig.getValidationConfig().getReplicationNumber(); OfflineTagConfig offlineTagConfig = new OfflineTagConfig(tableConfig); List<String> serverInstances = _helixAdmin.getInstancesInClusterWithTag(_helixClusterName, offlineTagConfig.getOfflineServerTag()); // Perform the basic validation if (targetNumReplicaGroup <= 0 || targetNumInstancesPerPartition <= 0 || targetNumReplicaGroup * targetNumInstancesPerPartition > serverInstances.size()) { throw new InvalidConfigException("Invalid input config (numReplicaGroup: " + targetNumReplicaGroup + ", " + "numInstancesPerPartition: " + targetNumInstancesPerPartition + ", numServers: " + serverInstances.size() + ")"); } // Check that the partition assignment exists String tableNameWithType = tableConfig.getTableName(); ReplicaGroupPartitionAssignment oldReplicaGroupPartitionAssignment = partitionAssignmentGenerator .getReplicaGroupPartitionAssignment(tableNameWithType); if (oldReplicaGroupPartitionAssignment == null) { throw new InvalidConfigException( "Replica group partition assignment does not exist for " + tableNameWithType); } // Fetch the previous replica group configurations List<String> oldServerInstances = oldReplicaGroupPartitionAssignment.getAllInstances(); int oldNumReplicaGroup = oldReplicaGroupPartitionAssignment.getNumReplicaGroups(); int oldNumInstancesPerPartition = oldServerInstances.size() / oldNumReplicaGroup; // Compute added and removed servers List<String> addedServers = new ArrayList<>(serverInstances); addedServers.removeAll(oldServerInstances); List<String> removedServers = new ArrayList<>(oldServerInstances); removedServers.removeAll(serverInstances); // Create the new replica group partition assignment ReplicaGroupPartitionAssignment newReplicaGroupPartitionAssignment = new ReplicaGroupPartitionAssignment( oldReplicaGroupPartitionAssignment.getTableName()); // In case of replacement, create the removed to added server mapping Map<String, String> oldToNewServerMapping = new HashMap<>(); if (addedServers.size() == removedServers.size()) { for (int i = 0; i < addedServers.size(); i++) { oldToNewServerMapping.put(removedServers.get(i), addedServers.get(i)); } } // Compute rebalance type ReplicaGroupRebalanceType rebalanceType = computeRebalanceType(oldNumInstancesPerPartition, oldNumReplicaGroup, targetNumReplicaGroup, targetNumInstancesPerPartition, addedServers, removedServers); LOGGER.info("Replica group rebalance type: " + rebalanceType); // For now, we don't support the rebalance for partition level replica group so "numPartitions" will always be 1. for (int partitionId = 0; partitionId < oldReplicaGroupPartitionAssignment .getNumPartitions(); partitionId++) { int currentNewReplicaGroupId = 0; for (int groupId = 0; groupId < oldNumReplicaGroup; groupId++) { List<String> oldReplicaGroup = oldReplicaGroupPartitionAssignment .getInstancesfromReplicaGroup(partitionId, groupId); List<String> newReplicaGroup = new ArrayList<>(); boolean removeGroup = false; // Based on the rebalance type, compute the new replica group partition assignment accordingly switch (rebalanceType) { case REPLACE: // Swap the removed server with the added one. for (String oldServer : oldReplicaGroup) { if (!oldToNewServerMapping.containsKey(oldServer)) { newReplicaGroup.add(oldServer); } else { newReplicaGroup.add(oldToNewServerMapping.get(oldServer)); } } break; case ADD_SERVER: newReplicaGroup.addAll(oldReplicaGroup); // Assign new servers to the replica group for (int serverIndex = 0; serverIndex < addedServers.size(); serverIndex++) { if (serverIndex % targetNumReplicaGroup == groupId) { newReplicaGroup.add(addedServers.get(serverIndex)); } } break; case REMOVE_SERVER: // Only add the servers that are not in the removed list newReplicaGroup.addAll(oldReplicaGroup); newReplicaGroup.removeAll(removedServers); break; case ADD_REPLICA_GROUP: // Add all servers for original replica groups and add new replica groups later newReplicaGroup.addAll(oldReplicaGroup); break; case REMOVE_REPLICA_GROUP: newReplicaGroup.addAll(oldReplicaGroup); // mark the group if this is the replica group that needs to be removed if (removedServers.containsAll(oldReplicaGroup)) { removeGroup = true; } break; default: String errorMessage = "Not supported replica group rebalance operation. Need to check server tags and replica group config to" + " make sure only one maintenance step is asked. ( oldNumInstancesPerPatition: " + oldNumInstancesPerPartition + ", targetNumInstancesPerPartition: " + targetNumInstancesPerPartition + ", oldNumReplicaGroup: " + oldNumReplicaGroup + ", targetNumReplicaGroup: " + targetNumReplicaGroup + ", numAddedServers: " + addedServers.size() + ", numRemovedServers: " + removedServers.size() + " )"; LOGGER.info(errorMessage); throw new InvalidConfigException(errorMessage); } if (!removeGroup) { LOGGER.info("Setting new replica group ( partitionId: " + partitionId + ", replicaGroupId: " + groupId + ", server list: " + StringUtils.join(",", newReplicaGroup)); newReplicaGroupPartitionAssignment.setInstancesToReplicaGroup(partitionId, currentNewReplicaGroupId++, newReplicaGroup); } } // Adding new replica groups if needed int index = 0; for (int newGroupId = currentNewReplicaGroupId; newGroupId < targetNumReplicaGroup; newGroupId++) { List<String> newReplicaGroup = new ArrayList<>(); while (newReplicaGroup.size() < targetNumInstancesPerPartition) { newReplicaGroup.add(addedServers.get(index)); index++; } newReplicaGroupPartitionAssignment.setInstancesToReplicaGroup(partitionId, newGroupId, newReplicaGroup); } } return newReplicaGroupPartitionAssignment; }
From source file:uk.ac.ebi.intact.util.protein.ProteinServiceImpl.java
/** * Update an existing intact protein's annotations. * <p/>//from w w w.j av a 2 s . c o m * That includes, all Xrefs, Aliases, splice variants. * * @param protein the intact protein to update. * @param uniprotProtein the uniprot protein used for data input. */ private void updateProtein(Protein protein, UniprotProtein uniprotProtein) throws ProteinServiceException { List<Protein> proteins = new ArrayList<Protein>(); // check that both protein carry the same organism information if (!UpdateBioSource(protein, uniprotProtein.getOrganism())) { return; } // Fullname String fullname = uniprotProtein.getDescription(); if (fullname != null && fullname.length() > 250) { if (log.isDebugEnabled()) { log.debug("Truncating fullname to the first 250 first chars."); } fullname = fullname.substring(0, 250); } protein.setFullName(fullname); // Shortlabel protein.setShortLabel(generateProteinShortlabel(uniprotProtein)); // Xrefs -- but UniProt's as they are supposed to be up-to-date at this stage. XrefUpdaterReport reports = XrefUpdaterUtils.updateAllXrefs(protein, uniprotProtein, databaseName2mi, IntactContext.getCurrentInstance().getDataContext(), processor, new TreeSet<InteractorXref>(new InteractorXrefComparator()), new TreeSet<UniprotXref>(new UniprotXrefComparator(databaseName2mi))); uniprotServiceResult.addXrefUpdaterReport(reports); // Aliases AliasUpdaterUtils.updateAllAliases(protein, uniprotProtein, IntactContext.getCurrentInstance().getDataContext(), processor); // Sequence updateProteinSequence(protein, uniprotProtein.getSequence(), uniprotProtein.getCrc64()); // Persist changes DaoFactory daoFactory = IntactContext.getCurrentInstance().getDataContext().getDaoFactory(); ProteinDao pdao = daoFactory.getProteinDao(); pdao.update((ProteinImpl) protein); /////////////////////////////// // Update Splice Variants and feature chains // search intact // splice variants with no 'no-uniprot-update' Collection<ProteinImpl> spliceVariantsAndChains = pdao.getSpliceVariants(protein); // feature chains spliceVariantsAndChains.addAll(pdao.getProteinChains(protein)); // We create a copy of the collection that hold the protein transcripts as the findMatches remove the protein transcripts // from the collection when a match is found. Therefore the first time it runs, it finds the match, protein transcripts // are correctly created, the protein transcripts are deleted from the collection so that the second // you run it, the splice variant are not linked anymore to the uniprotProtein and therefore they are not correctly // updated. Collection<UniprotProteinTranscript> variantsClone = new ArrayList<UniprotProteinTranscript>(); variantsClone.addAll(uniprotProtein.getSpliceVariants()); variantsClone.addAll(uniprotProtein.getFeatureChains()); for (UniprotProteinTranscript transcript : variantsClone) { proteins.addAll(createOrUpdateProteinTranscript(transcript, uniprotProtein, protein)); } if (!proteins.containsAll(spliceVariantsAndChains)) { if (proteins.size() < spliceVariantsAndChains.size()) { for (Object protNotUpdated : CollectionUtils.subtract(spliceVariantsAndChains, proteins)) { Protein prot = (Protein) protNotUpdated; if (prot.getActiveInstances().size() == 0) { deleteProtein(prot); uniprotServiceResult.addMessage( "The protein " + getProteinDescription(prot) + " is a protein transcript of " + getProteinDescription(protein) + " in IntAct but not in Uniprot." + " As it is not part of any interactions in IntAct we have deleted it."); } else if (ProteinUtils.isFromUniprot(prot)) { uniprotServiceResult.addError( UniprotServiceResult.SPLICE_VARIANT_IN_INTACT_BUT_NOT_IN_UNIPROT, "In Intact the protein " + getProteinDescription(prot) + " is a protein transcript of protein " + getProteinDescription(protein) + " but in Uniprot it is not the case. As it is part of interactions in IntAct we couldn't " + "delete it."); } } } else { Collection<Protein> spliceVariantsNotUpdated = new ArrayList<Protein>(spliceVariantsAndChains); spliceVariantsNotUpdated.removeAll(CollectionUtils.intersection(spliceVariantsAndChains, proteins)); for (Protein protNotUpdated : spliceVariantsNotUpdated) { if (protNotUpdated.getActiveInstances().size() == 0) { deleteProtein(protNotUpdated); uniprotServiceResult.addMessage("The protein " + getProteinDescription(protNotUpdated) + " is a protein transcript of " + getProteinDescription(protein) + " in IntAct but not in Uniprot." + " As it is not part of any interactions in IntAct we have deleted it."); } else if (ProteinUtils.isFromUniprot(protNotUpdated)) { uniprotServiceResult.addError( UniprotServiceResult.SPLICE_VARIANT_IN_INTACT_BUT_NOT_IN_UNIPROT, "In Intact the protein " + getProteinDescription(protNotUpdated) + " is a protein transcript of protein " + getProteinDescription(protein) + " but in Uniprot it is not the case. As it is part of interactions in IntAct we couldn't " + "delete it."); } } } } // Collection<ProteinTranscriptMatch> matches = findMatches( variants, variantsClone) ); /*Collection<ProteinTranscriptMatch> matches = findMatches( spliceVariantsAndChains, variantsClone ); for ( ProteinTranscriptMatch match : matches ) { if ( match.isSuccessful() ) { // update final UniprotProteinTranscript variant = match.getUniprotTranscript(); final Protein intactProtein = match.getIntactProtein(); if (ProteinUtils.isFromUniprot(intactProtein)){ updateProteinTranscript(intactProtein, protein, variant, uniprotProtein ); } if (variant.getSequence() != null || (variant.getSequence() == null && variant.isNullSequenceAllowed())) { proteins.add(intactProtein); } } else if ( match.hasNoIntact() ) { // TODO in the case of a global update, and the user requested splice variants without interactions to be deleted, // TODO we don't create splice variants when they are missing as they wouldn't have interactions anyways. // NOTE: this does not apply say in our curation environment as the users want to see imported SV so they can choose them // TODO test this final ProteinUpdateProcessorConfig config = ProteinUpdateContext.getInstance().getConfig(); final boolean globalProteinUpdate = config.isGlobalProteinUpdate(); final boolean deleteProteinTranscript = config.isDeleteProteinTranscriptWithoutInteractions(); if( ! globalProteinUpdate && !deleteProteinTranscript) { // create shallow Protein intactTranscript = createMinimalisticProteinTranscript( match.getUniprotTranscript(), protein.getAc(), protein.getBioSource(), uniprotProtein ); // update final UniprotProteinTranscript uniprotTranscript = match.getUniprotTranscript(); updateProteinTranscript( intactTranscript, protein, uniprotTranscript, uniprotProtein); proteinCreated(intactTranscript); if (uniprotTranscript.getSequence() != null || (uniprotTranscript.getSequence() == null && uniprotTranscript.isNullSequenceAllowed())) { proteins.add(intactTranscript); } } } else { Protein intactProteinTranscript = match.getIntactProtein(); if(intactProteinTranscript.getActiveInstances().size() == 0){ deleteProtein(intactProteinTranscript); uniprotServiceResult.addMessage("The protein " + getProteinDescription(intactProteinTranscript) + " is a protein transcript of " + getProteinDescription(protein) + " in IntAct but not in Uniprot." + " As it is not part of any interactions in IntAct we have deleted it." ); }else if (ProteinUtils.isFromUniprot(intactProteinTranscript)){ uniprotServiceResult.addError(UniprotServiceResult.SPLICE_VARIANT_IN_INTACT_BUT_NOT_IN_UNIPROT, "In Intact the protein "+ getProteinDescription(intactProteinTranscript) + " is a protein transcript of protein "+ getProteinDescription(protein)+ " but in Uniprot it is not the case. As it is part of interactions in IntAct we couldn't " + "delete it."); } } }*/ }
From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java
/** * This method is responsible for determining if a node already exists in * the database for the current interface. If the IfCollector object * contains a valid SNMP collection, an attempt will be made to look up in * the database each interface contained in the SNMP collection's ifTable. * If an interface is found to already exist in the database a DbNodeEntry * object will be created from it and returned. If the IfCollector object * does not contain a valid SNMP collection or if none of the interfaces * exist in the database null is returned. * * @param dbc Connection to the database. * @param collector Interface collector object * @return dbNodeEntry Returns null if a node does not already exist in * the database, otherwise returns the DbNodeEntry object for the * node under which the current interface/IP address should be * added./*from w w w. jav a 2 s. c om*/ * @throws java.sql.SQLException Thrown if an error occurs retrieving the parent nodeid from * the database. */ private DbNodeEntry getExistingNodeEntry(Connection dbc, IfCollector collector) throws SQLException { LOG.debug("getExistingNodeEntry: checking for current target: {}", collector.getTarget()); // Do we have any additional interface information collected via SNMP? // If not simply return, there is nothing to check if (!collector.hasSnmpCollection() || collector.getSnmpCollector().failed()) { return null; } // Next verify that ifTable and ipAddrTable entries were collected IfSnmpCollector snmpc = collector.getSnmpCollector(); IfTable ifTable = null; IpAddrTable ipAddrTable = null; if (snmpc.hasIfTable()) { ifTable = snmpc.getIfTable(); } if (snmpc.hasIpAddrTable()) { ipAddrTable = snmpc.getIpAddrTable(); } if (ifTable == null || ipAddrTable == null) { return null; } // SQL statement prefix StringBuffer sqlBuffer = new StringBuffer(SQL_RETRIEVE_INTERFACE_NODEID_PREFIX); boolean firstAddress = true; // Loop through the interface table entries and see if any already // exist in the database. List<String> ipaddrsOfNewNode = new ArrayList<String>(); List<String> ipaddrsOfOldNode = new ArrayList<String>(); for (IfTableEntry ifEntry : ifTable) { if (ifEntry.getIfIndex() == null) { LOG.debug("getExistingNodeEntry: Breaking from loop"); break; } // // Get ifIndex // int ifIndex = ifEntry.getIfIndex().intValue(); // // Get ALL IP Addresses for this ifIndex // List<InetAddress> ipAddrs = ipAddrTable.getIpAddresses(ifIndex); LOG.debug("getExistingNodeEntry: number of interfaces retrieved for ifIndex {} is: {}", ifIndex, ipAddrs.size()); // Iterate over IP address list and add each to the sql buffer // for (InetAddress ipAddress : ipAddrs) { // // Skip interface if no IP address or if IP address is // "0.0.0.0" // or if this interface is of type loopback if (ipAddress == null || str(ipAddress).equals("0.0.0.0") || ipAddress.isLoopbackAddress()) { continue; } if (firstAddress) { sqlBuffer.append("ipaddr='").append(str(ipAddress)).append("'"); firstAddress = false; } else { sqlBuffer.append(" OR ipaddr='").append(str(ipAddress)).append("'"); } ipaddrsOfNewNode.add(str(ipAddress)); } } // end while // Make sure we added at least one address to the SQL query // if (firstAddress) { return null; } // Prepare the db statement in advance // LOG.debug("getExistingNodeEntry: issuing SQL command: {}", sqlBuffer.toString()); int nodeID = -1; PreparedStatement stmt; final DBUtils d = new DBUtils(getClass()); try { stmt = dbc.prepareStatement(sqlBuffer.toString()); d.watch(stmt); // Do any of the IP addrs already exist in the database under another node? ResultSet rs = stmt.executeQuery(); d.watch(rs); if (rs.next()) { nodeID = rs.getInt(1); LOG.debug("getExistingNodeEntry: target {}/{}", str(collector.getTarget()), nodeID); rs = null; } } finally { d.cleanUp(); } if (nodeID == -1) { return null; } try { stmt = dbc.prepareStatement(SQL_RETRIEVE_IPINTERFACES_ON_NODEID); d.watch(stmt); stmt.setInt(1, nodeID); ResultSet rs = stmt.executeQuery(); d.watch(rs); while (rs.next()) { String ipaddr = rs.getString(1); if (!ipaddr.equals("0.0.0.0")) { ipaddrsOfOldNode.add(ipaddr); } } } finally { d.cleanUp(); } if (ipaddrsOfNewNode.containsAll(ipaddrsOfOldNode)) { LOG.debug("getExistingNodeEntry: found one of the addrs under existing node: {}", nodeID); return DbNodeEntry.get(nodeID); } else { String dupIpaddr = getDuplicateIpaddress(ipaddrsOfOldNode, ipaddrsOfNewNode); createAndSendDuplicateIpaddressEvent(nodeID, dupIpaddr); return null; } }
From source file:com.cloud.vm.VirtualMachineManagerImpl.java
@Override public void checkIfCanUpgrade(final VirtualMachine vmInstance, final ServiceOffering newServiceOffering) { if (newServiceOffering == null) { throw new InvalidParameterValueException("Invalid parameter, newServiceOffering can't be null"); }//from w w w . j a v a 2 s .c o m // Check that the VM is stopped / running if (!(vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Running))) { s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState()); throw new InvalidParameterValueException( "Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() + "; make sure the virtual machine is stopped/running"); } // Check if the service offering being upgraded to is what the VM is already running with if (!newServiceOffering.isDynamic() && vmInstance.getServiceOfferingId() == newServiceOffering.getId()) { if (s_logger.isInfoEnabled()) { s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " + "service offering (" + newServiceOffering.getName() + ")"); } throw new InvalidParameterValueException( "Not upgrading vm " + vmInstance.toString() + " since it already " + "has the requested service offering (" + newServiceOffering.getName() + ")"); } final ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId()); // Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering // NOTE: With the new network refactoring in 2.2, we shouldn't need the check for same guest IP type anymore. /* * if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) { String errorMsg = * "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType(); errorMsg += * ". Please select a service offering with the same guest IP type as the VM's current service offering (" + * currentServiceOffering.getGuestIpType() + ")."; throw new InvalidParameterValueException(errorMsg); } */ // Check that the service offering being upgraded to has the same storage pool preference as the VM's current service // offering if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) { throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + ", cannot switch between local storage and shared storage service offerings. Current offering " + "useLocalStorage=" + currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage()); } // if vm is a system vm, check if it is a system service offering, if yes return with error as it cannot be used for user vms if (currentServiceOffering.getSystemUse() != newServiceOffering.getSystemUse()) { throw new InvalidParameterValueException( "isSystem property is different for current service offering and new service offering"); } // Check that there are enough resources to upgrade the service offering if (!isVirtualMachineUpgradable(vmInstance, newServiceOffering)) { throw new InvalidParameterValueException( "Unable to upgrade virtual machine, not enough resources available " + "for an offering of " + newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory"); } // Check that the service offering being upgraded to has all the tags of the current service offering. final List<String> currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags()); final List<String> newTags = StringUtils.csvTagsToList(newServiceOffering.getTags()); if (!newTags.containsAll(currentTags)) { throw new InvalidParameterValueException( "Unable to upgrade virtual machine; the current service offering " + " should have tags as subset of " + "the new service offering tags. Current service offering tags: " + currentTags + "; " + "new service " + "offering tags: " + newTags); } }
From source file:org.talend.core.repository.ui.actions.DeleteAction.java
@Override protected void doRun() { final ISelection selection = getSelection(); final IProxyRepositoryFactory factory = ProxyRepositoryFactory.getInstance(); final DeleteActionCache deleteActionCache = DeleteActionCache.getInstance(); deleteActionCache.setGetAlways(false); deleteActionCache.setDocRefresh(false); deleteActionCache.createRecords();/* w w w . j av a 2 s . c o m*/ final Set<ERepositoryObjectType> types = new HashSet<ERepositoryObjectType>(); final List<RepositoryNode> deletedFolder = new ArrayList<RepositoryNode>(); final IWorkspaceRunnable op = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) { monitor.beginTask("Delete Running", IProgressMonitor.UNKNOWN); //$NON-NLS-1$ Object[] selections = ((IStructuredSelection) selection).toArray(); List<RepositoryNode> selectNodes = new ArrayList<RepositoryNode>(); for (Object obj : selections) { if (obj instanceof RepositoryNode) { // TDI-28549:if selectNodes contains the obj's parent,no need to add obj again if (!isContainParentNode(selectNodes, (RepositoryNode) obj)) { selectNodes.add((RepositoryNode) obj); } } } final List<ItemReferenceBean> unDeleteItems = RepositoryNodeDeleteManager.getInstance() .getUnDeleteItems(selectNodes, deleteActionCache); List<RepositoryNode> accessNodes = new ArrayList<RepositoryNode>(); for (RepositoryNode node : selectNodes) { try { accessNodes.add(node); // ADD xqliu 2012-05-24 TDQ-4831 if (sourceFileOpening(node)) { continue; } // ~ TDQ-4831 if (containParent(node, (IStructuredSelection) selection)) { continue; } if (isForbidNode(node)) { continue; } if (node.getType() == ENodeType.REPOSITORY_ELEMENT) { if (GlobalServiceRegister.getDefault().isServiceRegistered(IESBService.class)) { IESBService service = (IESBService) GlobalServiceRegister.getDefault() .getService(IESBService.class); Item repoItem = node.getObject().getProperty().getItem(); if (service != null && !repoItem.getState().isDeleted()) { final StringBuffer jobNames = service.getAllTheJObNames(node); if (jobNames != null) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { String message = jobNames.toString() + Messages .getString("DeleteAction.deleteJobAssignedToOneService"); //$NON-NLS-1$ final Shell shell = getShell(); confirmAssignDialog = MessageDialog.openQuestion(shell, "", //$NON-NLS-1$ message); } }); if (!confirmAssignDialog) { continue; } } } } if (isInDeletedFolder(deletedFolder, node.getParent())) { continue; } // TDI-22550 if (GlobalServiceRegister.getDefault() .isServiceRegistered(IDesignerCoreService.class)) { IDesignerCoreService coreService = (IDesignerCoreService) GlobalServiceRegister .getDefault().getService(IDesignerCoreService.class); IRepositoryViewObject object = node.getObject(); if (coreService != null && object != null && object.getProperty() != null) { Item item = object.getProperty().getItem(); IProcess iProcess = coreService.getProcessFromItem(item); if (iProcess != null && iProcess instanceof IProcess2) { IProcess2 process = (IProcess2) iProcess; process.removeProblems4ProcessDeleted(); } } } boolean needReturn = deleteElements(factory, deleteActionCache, node); if (node.getProperties(EProperties.CONTENT_TYPE) == ERepositoryObjectType.JOBLET) { needToUpdataPalette = true; } if (needReturn) { // TDI-31623: Access the rest nodes in select nodes if current node's delete has pb if (accessNodes.containsAll(selectNodes)) { return; } else { continue; } } types.add(node.getObjectType()); } else if (node.getType() == ENodeType.SIMPLE_FOLDER) { if (node.getChildren().size() > 0 && !node.getObject().isDeleted()) { if (GlobalServiceRegister.getDefault().isServiceRegistered(IESBService.class)) { IESBService service = (IESBService) GlobalServiceRegister.getDefault() .getService(IESBService.class); if (service != null) { final StringBuffer jobNames = service.getAllTheJObNames(node); if (jobNames != null) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { String message = null; if (jobNames.toString().contains(",")) { //$NON-NLS-1$ message = jobNames.toString() + Messages.getString( "DeleteAction.deleteSomeJobsAssignedToServices"); //$NON-NLS-1$ } else { message = jobNames.toString() + Messages.getString( "DeleteAction.deleteJobAssignedToOneService"); //$NON-NLS-1$ } final Shell shell = getShell(); confirmAssignDialog = MessageDialog.openQuestion(shell, "", //$NON-NLS-1$ message); } }); if (!confirmAssignDialog) { continue; } } } } } types.add(node.getContentType()); // fixed for the documentation deleted if (node.getContentType() == ERepositoryObjectType.PROCESS || node.getContentType() == ERepositoryObjectType.JOBLET) { types.add(ERepositoryObjectType.DOCUMENTATION); } deletedFolder.add(node); deleteFolder(node, factory, deleteActionCache); } } catch (PersistenceException e) { MessageBoxExceptionHandler.process(e); } catch (BusinessException e) { MessageBoxExceptionHandler.process(e); } } if (unDeleteItems.size() > 0) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { ItemReferenceDialog dialog = new ItemReferenceDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), unDeleteItems); dialog.open(); } }); } try { factory.saveProject(ProjectManager.getInstance().getCurrentProject()); } catch (PersistenceException e) { ExceptionHandler.process(e); } } /** * DOC xqliu Comment method "sourceFileOpening". * * @param node * @return */ private boolean sourceFileOpening(RepositoryNode node) { boolean result = false; if (node != null) { if (GlobalServiceRegister.getDefault().isServiceRegistered(ITDQRepositoryService.class)) { ITDQRepositoryService service = (ITDQRepositoryService) GlobalServiceRegister.getDefault() .getService(ITDQRepositoryService.class); if (service != null) { result = service.sourceFileOpening(node); } } } return result; } }; IRunnableWithProgress iRunnableWithProgress = new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { ISchedulingRule schedulingRule = workspace.getRoot(); // the update the project files need to be done in the workspace runnable to avoid all // notification // of changes before the end of the modifications. workspace.run(op, schedulingRule, IWorkspace.AVOID_UPDATE, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; try { PlatformUI.getWorkbench().getProgressService().run(false, false, iRunnableWithProgress); // fix for TDI-22986 , force build the .java if routine is deleted physical if (forceBuild) { IRunProcessService service = (IRunProcessService) GlobalServiceRegister.getDefault() .getService(IRunProcessService.class); service.buildJavaProject(); } } catch (Exception e) { ExceptionHandler.process(e); } synchUI(deleteActionCache); }
From source file:org.onosproject.t3.impl.TroubleshootManager.java
/** * Computes a trace for a give packet that start in the network at the given connect point. * * @param completePath the path traversed by the packet * @param in the input connect point * @param trace the trace to build * @param isDualHomed true if the trace we are doing starts or ends in a dual homed host * @return the build trace for that packet. *//*from w w w .ja va 2s . co m*/ private StaticPacketTrace getTrace(List<ConnectPoint> completePath, ConnectPoint in, StaticPacketTrace trace, boolean isDualHomed) { log.debug("------------------------------------------------------------"); //if the trace already contains the input connect point there is a loop if (pathContainsDevice(completePath, in.deviceId())) { trace.addResultMessage("Loop encountered in device " + in.deviceId()); completePath.add(in); trace.addCompletePath(completePath); trace.setSuccess(false); return trace; } //let's add the input connect point completePath.add(in); //If the trace has no outputs for the given input we stop here if (trace.getGroupOuputs(in.deviceId()) == null) { computePath(completePath, trace, null); trace.addResultMessage("No output out of device " + in.deviceId() + ". Packet is dropped"); trace.setSuccess(false); return trace; } //If the trace has outputs we analyze them all for (GroupsInDevice outputPath : trace.getGroupOuputs(in.deviceId())) { ConnectPoint cp = outputPath.getOutput(); log.debug("Connect point in {}", in); log.debug("Output path {}", cp); log.debug("{}", outputPath.getFinalPacket()); //Hosts for the the given output Set<Host> hostsList = hostService.getConnectedHosts(cp); //Hosts queried from the original ip or mac Set<Host> hosts = getHosts(trace); if (in.equals(cp) && trace.getInitialPacket().getCriterion(Criterion.Type.VLAN_VID) != null && outputPath.getFinalPacket().getCriterion(Criterion.Type.VLAN_VID) != null && ((VlanIdCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.VLAN_VID)).vlanId() .equals(((VlanIdCriterion) outputPath.getFinalPacket() .getCriterion(Criterion.Type.VLAN_VID)).vlanId())) { if (trace.getGroupOuputs(in.deviceId()).size() == 1 && computePath(completePath, trace, outputPath.getOutput())) { trace.addResultMessage("Connect point out " + cp + " is same as initial input " + in); trace.setSuccess(false); } } else if (!Collections.disjoint(hostsList, hosts)) { //If the two host collections contain the same item it means we reached the proper output log.debug("Stopping here because host is expected destination {}, reached through", completePath); if (computePath(completePath, trace, outputPath.getOutput())) { trace.addResultMessage("Reached required destination Host " + cp); trace.setSuccess(true); } break; } else if (cp.port().equals(PortNumber.CONTROLLER)) { //Getting the master when the packet gets sent as packet in NodeId master = mastershipService.getMasterFor(cp.deviceId()); trace.addResultMessage(PACKET_TO_CONTROLLER + " " + master.id()); computePath(completePath, trace, outputPath.getOutput()); handleVlanToController(outputPath, trace); } else if (linkService.getEgressLinks(cp).size() > 0) { //TODO this can be optimized if we use a Tree structure for paths. //if we already have outputs let's check if the one we are considering starts from one of the devices // in any of the ones we have. if (trace.getCompletePaths().size() > 0) { ConnectPoint inputForOutput = null; List<ConnectPoint> previousPath = new ArrayList<>(); for (List<ConnectPoint> path : trace.getCompletePaths()) { for (ConnectPoint connect : path) { //if the path already contains the input for the output we've found we use it if (connect.equals(in)) { inputForOutput = connect; previousPath = path; break; } } } //we use the pre-existing path up to the point we fork to a new output if (inputForOutput != null && completePath.contains(inputForOutput)) { List<ConnectPoint> temp = new ArrayList<>(previousPath); temp = temp.subList(0, previousPath.indexOf(inputForOutput) + 1); if (completePath.containsAll(temp)) { completePath = temp; } } } //let's add the ouput for the input completePath.add(cp); //let's compute the links for the given output Set<Link> links = linkService.getEgressLinks(cp); log.debug("Egress Links {}", links); //For each link we trace the corresponding device for (Link link : links) { ConnectPoint dst = link.dst(); //change in-port to the dst link in port Builder updatedPacket = DefaultTrafficSelector.builder(); outputPath.getFinalPacket().criteria().forEach(updatedPacket::add); updatedPacket.add(Criteria.matchInPort(dst.port())); log.debug("DST Connect Point {}", dst); //build the elements for that device traceInDevice(trace, updatedPacket.build(), dst, isDualHomed, completePath); //continue the trace along the path getTrace(completePath, dst, trace, isDualHomed); } } else if (edgePortService.isEdgePoint(outputPath.getOutput()) && trace.getInitialPacket().getCriterion(Criterion.Type.ETH_DST) != null && ((EthCriterion) trace.getInitialPacket().getCriterion(Criterion.Type.ETH_DST)).mac() .isMulticast()) { trace.addResultMessage("Packet is multicast and reached output " + outputPath.getOutput() + " which is enabled and is edge port"); trace.setSuccess(true); computePath(completePath, trace, outputPath.getOutput()); if (!hasOtherOutput(in.deviceId(), trace, outputPath.getOutput())) { return trace; } } else if (deviceService.getPort(cp) != null && deviceService.getPort(cp).isEnabled()) { EthTypeCriterion ethTypeCriterion = (EthTypeCriterion) trace.getInitialPacket() .getCriterion(Criterion.Type.ETH_TYPE); //We treat as correct output only if it's not LLDP or BDDP if (!(ethTypeCriterion.ethType().equals(EtherType.LLDP.ethType()) && !ethTypeCriterion.ethType().equals(EtherType.BDDP.ethType()))) { if (computePath(completePath, trace, outputPath.getOutput())) { if (hostsList.isEmpty()) { trace.addResultMessage("Packet is " + ((EthTypeCriterion) outputPath.getFinalPacket() .getCriterion(Criterion.Type.ETH_TYPE)).ethType() + " and reached " + cp + " with no hosts connected "); } else { IpAddress ipAddress = null; if (trace.getInitialPacket().getCriterion(Criterion.Type.IPV4_DST) != null) { ipAddress = ((IPCriterion) trace.getInitialPacket() .getCriterion(Criterion.Type.IPV4_DST)).ip().address(); } else if (trace.getInitialPacket().getCriterion(Criterion.Type.IPV6_DST) != null) { ipAddress = ((IPCriterion) trace.getInitialPacket() .getCriterion(Criterion.Type.IPV6_DST)).ip().address(); } if (ipAddress != null) { IpAddress finalIpAddress = ipAddress; if (hostsList.stream().anyMatch(host -> host.ipAddresses().contains(finalIpAddress)) || hostService.getHostsByIp(finalIpAddress).isEmpty()) { trace.addResultMessage("Packet is " + ((EthTypeCriterion) outputPath.getFinalPacket() .getCriterion(Criterion.Type.ETH_TYPE)).ethType() + " and reached " + cp + " with hosts " + hostsList); } else { trace.addResultMessage( "Wrong output " + cp + " for required destination ip " + ipAddress); trace.setSuccess(false); } } else { trace.addResultMessage("Packet is " + ((EthTypeCriterion) outputPath.getFinalPacket() .getCriterion(Criterion.Type.ETH_TYPE)).ethType() + " and reached " + cp + " with hosts " + hostsList); } } trace.setSuccess(true); } } } else { computePath(completePath, trace, cp); trace.setSuccess(false); if (deviceService.getPort(cp) == null) { //Port is not existent on device. log.warn("Port {} is not available on device.", cp); trace.addResultMessage("Port " + cp + "is not available on device. Packet is dropped"); } else { //No links means that the packet gets dropped. log.warn("No links out of {}", cp); trace.addResultMessage("No links depart from " + cp + ". Packet is dropped"); } } } return trace; }
From source file:com.atlassian.jira.webtests.JIRAWebTest.java
/** * A more robust version of {@link #assertOptionsEqual(String, String[])}. This version is different in that, it * does not care about the ordering (So its workable with different JDKs or when you dont know/care about the * order).//from w ww .j a v a 2s . co m */ public void assertOptionsEqualIgnoreOrder(String selectName, String[] expectedOptions) { List expectedOptionsList = Arrays.asList(expectedOptions); List actualOptionsList = Arrays.asList(getDialog().getOptionsFor(selectName)); assertTrue("The expected options '" + expectedOptionsList + "' does not equal '" + actualOptionsList + "'", expectedOptionsList.containsAll(actualOptionsList) && actualOptionsList.containsAll(expectedOptionsList)); }
From source file:org.xdi.oxauth.authorize.ws.rs.AuthorizeRestWebServiceImpl.java
public Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri, String state, String respMode, String nonce, String display, String prompt, Integer maxAge, String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr, String request, String requestUri, String requestSessionId, String sessionId, String accessToken, String method, String originHeaders, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) { scope = ServerUtil.urlDecode(scope); // it may be encoded in uma case // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final , // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate log.debug(// w w w . j a v a 2 s . co m "Attempting to request authorization: " + "responseType = {0}, clientId = {1}, scope = {2}, redirectUri = {3}, nonce = {4}, " + "state = {5}, request = {6}, isSecure = {7}, requestSessionId = {8}, sessionId = {9}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionId, sessionId); log.debug("Attempting to request authorization: " + "acrValues = {0}, amrValues = {1}, originHeaders = {4}", acrValuesStr, amrValuesStr, originHeaders); ResponseBuilder builder = Response.ok(); List<String> uiLocales = null; if (StringUtils.isNotBlank(uiLocalesStr)) { uiLocales = Util.splittedStringAsList(uiLocalesStr, " "); } List<ResponseType> responseTypes = ResponseType.fromString(responseType, " "); List<Prompt> prompts = Prompt.fromString(prompt, " "); List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " "); List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " "); ResponseMode responseMode = ResponseMode.getByValue(respMode); User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn()) ? userService.getUserByDn(sessionUser.getUserDn()) : null; try { sessionIdService.updateSessionIfNeeded(sessionUser, redirectUri, acrValuesStr); if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request, requestUri)) { if (clientId != null && redirectUri != null && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory .getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity( errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state)); } } else { Client client = clientService.getClient(clientId); JwtAuthorizationRequest jwtAuthorizationRequest = null; if (client != null) { List<String> scopes = new ArrayList<String>(); if (StringHelper.isNotEmpty(scope)) { Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope); scopes.addAll(grantedScopes); } // Validate redirectUri redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri); boolean validRedirectUri = redirectUri != null; if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) { if (validRedirectUri) { if (ConfigurationFactory.instance().getConfiguration().getFederationEnabled()) { if (!federationDataService.hasAnyActiveTrust(client)) { log.debug( "Forbid authorization. Client is not in any trust relationship however federation is enabled for server. Client id: {0}, client redirectUris: {1}", client.getClientId(), client.getRedirectUris()); return error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state).build(); } } if (StringUtils.isNotBlank(accessToken)) { AuthorizationGrant authorizationGrant = authorizationGrantList .getAuthorizationGrantByAccessToken(accessToken); if (authorizationGrant == null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.ACCESS_DENIED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } else { user = userService.getUser(authorizationGrant.getUserId()); sessionUser = sessionIdService.generateAuthenticatedSessionId(user.getDn(), prompt); } } if (StringUtils.isNotBlank(requestUri)) { boolean validRequestUri = false; try { URI reqUri = new URI(requestUri); String reqUriHash = reqUri.getFragment(); String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart(); ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment); clientRequest.setHttpMethod(HttpMethod.GET); ClientResponse<String> clientResponse = clientRequest.get(String.class); int status = clientResponse.getStatus(); if (status == 200) { request = clientResponse.getEntity(String.class); if (StringUtils.isBlank(reqUriHash)) { validRequestUri = true; } else { String hash = JwtUtil .base64urlencode(JwtUtil.getMessageDigestSHA256(request)); validRequestUri = StringUtils.equals(reqUriHash, hash); } } if (validRequestUri) { requestUri = null; } else { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_REQUEST_URI, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } catch (UnknownHostException e) { log.error(e.getMessage(), e); } catch (ConnectException e) { log.error(e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); } } boolean invalidOpenidRequestObject = false; if (StringUtils.isNotBlank(request)) { try { jwtAuthorizationRequest = new JwtAuthorizationRequest(request, client); if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes .containsAll(jwtAuthorizationRequest.getResponseTypes())) { throw new InvalidJwtException( "The responseType parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getClientId() != null && !jwtAuthorizationRequest.getClientId().equals(clientId)) { throw new InvalidJwtException( "The clientId parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes) || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) { throw new InvalidJwtException( "The scope parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getRedirectUri() != null && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) { throw new InvalidJwtException( "The redirectUri parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getState() != null && StringUtils.isNotBlank(state) && !jwtAuthorizationRequest.getState().equals(state)) { throw new InvalidJwtException( "The state parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getNonce() != null && StringUtils.isNotBlank(nonce) && !jwtAuthorizationRequest.getNonce().equals(nonce)) { throw new InvalidJwtException( "The nonce parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getDisplay() != null && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest .getDisplay().getParamName().equals(display)) { throw new InvalidJwtException( "The display parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty() && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) { throw new InvalidJwtException( "The prompt parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember() .getMaxAge().equals(maxAge)) { throw new InvalidJwtException( "The maxAge parameter is not the same in the JWT"); } } catch (InvalidJwtException e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } catch (Exception e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } } if (invalidOpenidRequestObject) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { AuthorizationGrant authorizationGrant = null; RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); if (jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null) { Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember() .getClaim(JwtClaimName.SUBJECT_IDENTIFIER); if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) { String userIdClaimValue = userIdClaim.getClaimValue().getValue(); if (user != null) { String userId = user.getUserId(); if (!userId.equalsIgnoreCase(userIdClaimValue)) { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.USER_MISMATCHED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } } } if (user == null) { identity.logout(); if (prompts.contains(Prompt.NONE)) { if (authenticationFilterService.isEnabled()) { Map<String, String> params = new HashMap<String, String>(); if (method.equals(HttpMethod.GET)) { params = QueryStringDecoder.decode(httpRequest.getQueryString()); } else { params = httpRequest.getParameterMap(); } String userDn = authenticationFilterService .processAuthenticationFilters(params); if (userDn != null) { sessionUser = sessionIdService .generateAuthenticatedSessionId(userDn, prompt); user = userService.getUserByDn(sessionUser.getUserDn()); Authenticator authenticator = (Authenticator) Component .getInstance(Authenticator.class, true); authenticator.authenticateExternallyWebService(user.getUserId()); identity.addRole("user"); } else { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } else { redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } else { if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); } redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } ClientAuthorizations clientAuthorizations = clientAuthorizationsService .findClientAuthorizations(user.getAttribute("inum"), client.getClientId()); if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.NONE) && Boolean.parseBoolean(client.getTrustedClient())) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } if (prompts.contains(Prompt.CONSENT) && !sessionUser.isPermissionGrantedForClient(clientId)) { prompts.remove(Prompt.CONSENT); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-37 : Validate authentication max age boolean validAuthenticationMaxAge = true; Integer authenticationMaxAge = null; if (maxAge != null) { authenticationMaxAge = maxAge; } else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) { authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge(); } GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC")); GregorianCalendar userAuthenticationTime = new GregorianCalendar( TimeZone.getTimeZone("UTC")); userAuthenticationTime.setTime(sessionUser.getAuthenticationTime()); if (authenticationMaxAge != null) { userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge); validAuthenticationMaxAge = userAuthenticationTime.after(now); } else if (client.getDefaultMaxAge() != null) { userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge()); validAuthenticationMaxAge = userAuthenticationTime.after(now); } if (!validAuthenticationMaxAge) { endSession(sessionId, httpRequest, httpResponse); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-87 : Checks whether client has groups. If yes then user must be in one of these groups otherwise forbid authorization. if (checkUserGroups(user, client)) { AuthorizationCode authorizationCode = null; if (responseTypes.contains(ResponseType.CODE)) { authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! authorizationCode = authorizationGrant.getAuthorizationCode(); redirectUriResponse.addResponseParameter("code", authorizationCode.getCode()); } AccessToken newAccessToken = null; if (responseTypes.contains(ResponseType.TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! } newAccessToken = authorizationGrant.createAccessToken(); redirectUriResponse.addResponseParameter("access_token", newAccessToken.getCode()); redirectUriResponse.addResponseParameter("token_type", newAccessToken.getTokenType().toString()); redirectUriResponse.addResponseParameter("expires_in", newAccessToken.getExpiresIn() + ""); } if (responseTypes.contains(ResponseType.ID_TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createAuthorizationGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store authentication acr values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification, call is asynchronous!!! } //Map<String, String> idTokenClaims = getClaims(user, authorizationGrant, scopes); IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, authorizationGrant.getAcrValues()); redirectUriResponse.addResponseParameter("id_token", idToken.getCode()); } if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) { redirectUriResponse.addResponseParameter("acr_values", acrValuesStr); } //if (Boolean.valueOf(requestSessionId) && StringUtils.isBlank(sessionId) && if (sessionUser.getId() == null) { final SessionId newSessionUser = sessionIdService .generateAuthenticatedSessionId(sessionUser.getUserDn(), prompt); String newSessionId = newSessionUser.getId(); sessionUser.setId(newSessionId); log.trace("newSessionId = {0}", newSessionId); } redirectUriResponse.addResponseParameter(Parameters.SESSION_ID.getParamName(), sessionUser.getId()); redirectUriResponse.addResponseParameter("state", state); if (scope != null && !scope.isEmpty()) { scope = authorizationGrant.checkScopesPolicy(scope); redirectUriResponse.addResponseParameter("scope", scope); } clientService.updatAccessTime(client, false); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } } } else { // Invalid redirectUri builder = error(Response.Status.BAD_REQUEST, AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state); // 400 } } else { // Invalid responseTypes builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity(errorResponseFactory .getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state)); } } else { builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); } } } catch (AcrChangedException e) { builder = Response.status(Response.Status.UNAUTHORIZED) .entity("Session already exist with ACR that is different " + "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: " + acrValuesStr); log.error(e.getMessage(), e); } catch (EntryPersistenceException e) { // Invalid clientId builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); log.error(e.getMessage(), e); } catch (SignatureException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (StringEncrypter.EncryptionException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (InvalidJwtException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (Exception e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } return builder.build(); }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * read grade information form and see if any grading information has been changed * @param data//from w w w. j a v a 2s. c o m * @param state * @param gradeOption * @return */ public boolean readGradeForm(RunData data, SessionState state, String gradeOption) { // whether user has changed anything from previous grading information boolean hasChange = false; ParameterParser params = data.getParameters(); String sId = params.getString("submissionId"); //Added by Branden Visser - Check that the state is consistent if (!checkSubmissionStateConsistency(state, sId)) { return false; } AssignmentSubmission submission = getSubmission(sId, "readGradeForm", state); // security check for allowing grading submission or not if (AssignmentService.allowGradeSubmission(sId)) { int typeOfGrade = -1; boolean withGrade = state.getAttribute(WITH_GRADES) != null ? ((Boolean) state.getAttribute(WITH_GRADES)).booleanValue() : false; boolean checkForFormattingErrors = true; // so that grading isn't held up by formatting errors String feedbackComment = processFormattedTextFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_COMMENT), checkForFormattingErrors); // comment value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackComment, submission.getFeedbackComment()) : hasChange; if (feedbackComment != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_COMMENT, feedbackComment); } String feedbackText = processAssignmentFeedbackFromBrowser(state, params.getCleanString(GRADE_SUBMISSION_FEEDBACK_TEXT)); // feedbackText value changed? hasChange = !hasChange && submission != null ? valueDiffFromStateAttribute(state, feedbackText, submission.getFeedbackText()) : hasChange; if (feedbackText != null) { state.setAttribute(GRADE_SUBMISSION_FEEDBACK_TEXT, feedbackText); } // any change inside attachment list? if (!hasChange && submission != null) { List stateAttachments = submission.getFeedbackAttachments(); List inputAttachments = (List) state.getAttribute(ATTACHMENTS); if (stateAttachments == null && inputAttachments != null || stateAttachments != null && inputAttachments == null || stateAttachments != null && inputAttachments != null && !(stateAttachments.containsAll(inputAttachments) && inputAttachments.containsAll(stateAttachments))) { hasChange = true; } } state.setAttribute(GRADE_SUBMISSION_FEEDBACK_ATTACHMENT, state.getAttribute(ATTACHMENTS)); String g = StringUtils.trimToNull(params.getCleanString(GRADE_SUBMISSION_GRADE)); if (submission != null) { Assignment a = submission.getAssignment(); int factor = a.getContent().getFactor(); typeOfGrade = a.getContent().getTypeOfGrade(); if (withGrade) { // any change in grade. Do not check for ungraded assignment type if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { String currentGrade = submission.getGrade(); String decSeparator = FormattedText.getDecimalSeparator(); if (currentGrade != null && currentGrade.indexOf(decSeparator) != -1) { currentGrade = scalePointGrade(state, submission.getGrade(), factor); } hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, g, factor), currentGrade); } else { hasChange = valueDiffFromStateAttribute(state, g, submission.getGrade()); } } if (g != null) { state.setAttribute(GRADE_SUBMISSION_GRADE, g); } else { state.removeAttribute(GRADE_SUBMISSION_GRADE); } // for points grading, one have to enter number as the points String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if ((grade != null)) { // the preview grade process might already scaled up the grade by "factor" if (!((String) state.getAttribute(STATE_MODE)) .equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { if (state.getAttribute(STATE_MESSAGE) == null) { validPointGrade(state, grade, factor); int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt(scalePointGrade(state, grade, factor)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[] { grade, displayGrade(state, String.valueOf(maxGrade), factor) })); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, grade, factor); M_log.warn(this + ":readGradeForm " + e.getMessage()); } } state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } // if ungraded and grade type is not "ungraded" type if ((grade == null || "ungraded".equals(grade)) && (typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) && "release".equals(gradeOption)) { addAlert(state, rb.getString("plespethe2")); } // check for grade overrides if (a.isGroup()) { User[] _users = submission.getSubmitters(); HashMap<String, String> scaledValues = new HashMap<String, String>(); for (int i = 0; _users != null && i < _users.length; i++) { String ug = StringUtil.trimToNull( params.getCleanString(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId())); if ("null".equals(ug)) ug = null; if (!hasChange && typeOfGrade != Assignment.UNGRADED_GRADE_TYPE) { if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { hasChange = valueDiffFromStateAttribute(state, scalePointGrade(state, ug, factor), submission.getGradeForUser(_users[i].getId())); } else { hasChange = valueDiffFromStateAttribute(state, ug, submission.getGradeForUser(_users[i].getId())); } } if (ug == null) { state.removeAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); } else { state.setAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), ug); } // for points grading, one have to enter number as the points String ugrade = (String) state .getAttribute(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId()); // do grade validation only for Assignment with Grade tool if (typeOfGrade == Assignment.SCORE_GRADE_TYPE) { if (ugrade != null && !(ugrade.equals("null"))) { // the preview grade process might already scaled up the grade by "factor" if (!((String) state.getAttribute(STATE_MODE)) .equals(MODE_INSTRUCTOR_PREVIEW_GRADE_SUBMISSION)) { validPointGrade(state, ugrade, factor); if (state.getAttribute(STATE_MESSAGE) == null) { int maxGrade = a.getContent().getMaxGradePoint(); try { if (Integer.parseInt( scalePointGrade(state, ugrade, factor)) > maxGrade) { if (state.getAttribute(GRADE_GREATER_THAN_MAX_ALERT) == null) { // alert user first when he enters grade bigger than max scale addAlert(state, rb.getFormattedMessage("grad2", new Object[] { ugrade, displayGrade(state, String.valueOf(maxGrade), factor) })); state.setAttribute(GRADE_GREATER_THAN_MAX_ALERT, Boolean.TRUE); } else { // remove the alert once user confirms he wants to give student higher grade state.removeAttribute(GRADE_GREATER_THAN_MAX_ALERT); } } } catch (NumberFormatException e) { alertInvalidPoint(state, ugrade, factor); M_log.warn(this + ":readGradeForm User " + e.getMessage()); } } scaledValues.put(GRADE_SUBMISSION_GRADE + "_" + _users[i].getId(), scalePointGrade(state, ugrade, factor)); } } } } // SAK-28182 If all grades are right place scaled values in state if (state.getAttribute(STATE_MESSAGE) == null) { for (Map.Entry<String, String> entry : scaledValues.entrySet()) { state.setAttribute(entry.getKey(), entry.getValue()); } } } } // allow resubmit number and due time if (params.getString("allowResToggle") != null && params.getString(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER) != null) { // read in allowResubmit params readAllowResubmitParams(params, state, submission); } else { state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_CLOSETIME); state.removeAttribute(AssignmentSubmission.ALLOW_RESUBMIT_NUMBER); if (!"read".equals(gradeOption)) { resetAllowResubmitParams(state); } } // record whether the resubmission options has been changed or not hasChange = hasChange || change_resubmit_option(state, submission); if (state.getAttribute(STATE_MESSAGE) == null) { String grade = (String) state.getAttribute(GRADE_SUBMISSION_GRADE); grade = (typeOfGrade == Assignment.SCORE_GRADE_TYPE) ? scalePointGrade(state, grade, factor) : grade; state.setAttribute(GRADE_SUBMISSION_GRADE, grade); } } } else { // generate alert addAlert(state, rb.getFormattedMessage("not_allowed_to_grade_submission", new Object[] { sId })); } return hasChange; }