@Override public float getSimilarity(Object o1, Object o2) { Collection<SxE> sxeVector1 = parse(o1); if (sxeVector1 == null || sxeVector1.isEmpty()) return 0; Collection<SxE> sxeVector2 = parse(o2); if (sxeVector2 == null || sxeVector2.isEmpty()) return 0; float similarity = -1; for (SxE sxe1 : sxeVector1) { for (SxE sxe2 : sxeVector2) { if (sxe1.season == sxe2.season && sxe1.episode == sxe2.episode && sxe1.season >= 0 && sxe2.season >= 0) { // vectors have at least one perfect episode match in common (require season >= 0 as to // put less trust in single-number matches) return 1; } if ((sxe1.season >= 0 && sxe1.season == sxe2.season) || (sxe1.episode >= 0 && sxe1.episode == sxe2.episode)) { // at least we have a partial match similarity = 0.5f; } } } return similarity; }
/** * Generate Query object for GeneralLedgerEntry search. * * @param fieldValues * @return */ protected ReportQueryByCriteria getGeneralLedgerReportQuery(Map fieldValues) { Collection docTypeCodes = getDocumentType(fieldValues); Collection activityStatusCodes = getActivityStatusCode(fieldValues); Criteria criteria = OJBUtility.buildCriteriaFromMap(fieldValues, new GeneralLedgerEntry()); // set document type code criteria if (!docTypeCodes.isEmpty()) { criteria.addIn( CabPropertyConstants.GeneralLedgerEntry.FINANCIAL_DOCUMENT_TYPE_CODE, docTypeCodes); } // set activity status code criteria if (!activityStatusCodes.isEmpty()) { criteria.addIn( CabPropertyConstants.GeneralLedgerEntry.ACTIVITY_STATUS_CODE, activityStatusCodes); } ReportQueryByCriteria query = QueryFactory.newReportQuery(GeneralLedgerEntry.class, criteria); List attributeList = buildAttributeList(false); // set the selection attributes String[] attributes = (String[]) attributeList.toArray(new String[attributeList.size()]); query.setAttributes(attributes); return query; }
/** * Handles activation of the editor or it's associated views. * <!-- * begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected void handleActivate() { // Recompute the read only state. // if (editingDomain.getResourceToReadOnlyMap() != null) { editingDomain.getResourceToReadOnlyMap().clear(); // Refresh any actions that may become enabled or disabled. // setSelection(getSelection()); } if (!removedResources.isEmpty()) { if (handleDirtyConflict()) { getSite().getPage().closeEditor(RmapEditor.this, false); } else { removedResources.clear(); changedResources.clear(); savedResources.clear(); } } else if (!changedResources.isEmpty()) { changedResources.removeAll(savedResources); handleChangedResources(); changedResources.clear(); savedResources.clear(); } }
private void addNewClause( Collection<String> elements, Collection<String> additional, Project project, boolean isExtends) throws IncorrectOperationException { if (elements.isEmpty() && additional.isEmpty()) return; StringBuilder classText = new StringBuilder(); classText.append("class A "); classText.append(isExtends ? "extends " : "implements "); for (String str : elements) { classText.append(str); classText.append(", "); } for (String str : additional) { classText.append(str); classText.append(", "); } classText.delete(classText.length() - 2, classText.length()); classText.append(" {}"); final GrTypeDefinition definition = GroovyPsiElementFactory.getInstance(project).createTypeDefinition(classText.toString()); GroovyPsiElement clause = isExtends ? definition.getExtendsClause() : definition.getImplementsClause(); assert clause != null; PsiElement addedClause = myClass.addBefore(clause, myClass.getBody()); JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClause); }
@Test public void testGetSetFiltered() throws PersistenceLayerException { setUpPC(); TransparentPlayerCharacter pc = new TransparentPlayerCharacter(); initializeObjects(); assertTrue(parse(getSubTokenName() + "|CROSSCLASS[TYPE=Masterful]")); finishLoad(); ChooseInformation<?> info = primaryProf.get(ObjectKey.CHOOSE_INFO); pc.classSet.add(cl1); Collection<?> set = info.getSet(pc); assertEquals(2, set.size()); assertTrue(set.contains(s2)); assertTrue(set.contains(s3)); pc.skillCostMap.put(s2, cl1, SkillCost.CLASS); set = info.getSet(pc); assertFalse(set.isEmpty()); assertEquals(1, set.size()); assertTrue(set.contains(s3)); pc.skillCostMap.put(s4, cl1, SkillCost.CROSS_CLASS); pc.skillCostMap.put(s5, cl1, SkillCost.CROSS_CLASS); set = info.getSet(pc); assertFalse(set.isEmpty()); assertEquals(2, set.size()); assertTrue(set.contains(s3)); assertTrue(set.contains(s4)); }
@Override protected boolean process(Matcher m) { if (data.isGoalSet()) { if (data.isGoalSkillMaxed()) { printMessage("Goal %s: full", data.getGoalSkill()); } else { Collection<SkillMaxInfo> skillmaxinfo = selectGreaterThanGoalPercent(data.getSkillMaxes(), data.getGoalPercent()); if (skillmaxinfo.isEmpty()) { printMessage("None of your guilds offer more %s", data.getGoalSkill()); } else { Collection<SkillMaxInfo> available = selectAvailableOnThisLevel(skillmaxinfo); if (available.isEmpty()) { printMessage("Goal %s: needs level", data.getGoalSkill()); } else { int neededExp = data.getImproveGoalSkillCost(); int currentExp = Integer.parseInt(m.group(1)); if (currentExp < neededExp) { printMessage( "Goal %s: %d You need: %d", data.getGoalSkill(), neededExp, neededExp - currentExp); } else { printMessage( "Goal %s: %d You have enough to advance in: %s", data.getGoalSkill(), neededExp, concatGuildNames(selectGuildNames(available))); } } } } } return false; }
public static JpsRemoteProto.Message.Request createCompileRequest( final JpsRemoteProto.Message.Request.CompilationRequest.Type command, String project, Collection<String> modules, Collection<String> artifacts, Map<String, String> userData, Collection<String> paths) { final JpsRemoteProto.Message.Request.CompilationRequest.Builder builder = JpsRemoteProto.Message.Request.CompilationRequest.newBuilder().setCommandType(command); builder.setProjectId(project); if (!modules.isEmpty()) { builder.addAllModuleName(modules); } if (!artifacts.isEmpty()) { builder.addAllArtifactName(artifacts); } if (!userData.isEmpty()) { for (Map.Entry<String, String> entry : userData.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (key != null && value != null) { builder.addBuilderParameter(createPair(key, value)); } } } if (!paths.isEmpty()) { builder.addAllFilePath(paths); } return JpsRemoteProto.Message.Request.newBuilder() .setRequestType(JpsRemoteProto.Message.Request.Type.COMPILE_REQUEST) .setCompileRequest(builder.build()) .build(); }
@Override public void validate(final MavenEnvironment env) throws ValidationException { if (!env.outdir().exists() || "pom".equals(env.project().getPackaging()) || env.exclude("dependencies", "")) { Logger.info(this, "No dependency analysis in this project"); return; } final Collection<String> unused = DependenciesValidator.unused(env); if (!unused.isEmpty()) { Logger.warn( this, "Unused declared dependencies found:%s%s", DependenciesValidator.SEP, StringUtils.join(unused, DependenciesValidator.SEP)); } final Collection<String> used = DependenciesValidator.used(env); if (!used.isEmpty()) { Logger.warn( this, "Used undeclared dependencies found:%s%s", DependenciesValidator.SEP, StringUtils.join(used, DependenciesValidator.SEP)); } final Integer failures = used.size() + unused.size(); if (failures > 0) { throw new ValidationException("%d dependency problem(s) found", failures); } Logger.info(this, "No dependency problems found"); }
@Test public void shouldCreateValidUnsubscribeRequest() throws OXFException, XmlException { ParameterContainer parameters = new ParameterContainer(); parameters.addParameterShell(SESRequestBuilder_00.UNSUBSCRIBE_SES_URL, "http://ses.host"); parameters.addParameterShell(SESRequestBuilder_00.UNSUBSCRIBE_REFERENCE, "urn:n52:dummy"); SESRequestBuilder_00 request = new SESRequestBuilder_00(); String asText = request.buildUnsubscribeRequest(parameters); EnvelopeDocument envelope = EnvelopeDocument.Factory.parse(asText); Collection<XmlError> errors = XMLBeansParser.validate(envelope); Assert.assertTrue("Unsubscribe request is not valid: " + errors, errors.isEmpty()); parameters = new ParameterContainer(); parameters.addParameterShell(SESRequestBuilder_00.UNSUBSCRIBE_SES_URL, "http://ses.host"); parameters.addParameterShell( SESRequestBuilder_00.UNSUBSCRIBE_REFERENCE_XML, "<muse-wsa:ResourceId " + "xmlns:muse-wsa=\"http://ws.apache.org/muse/addressing\" wsa:IsReferenceParameter=\"true\" " + " xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + "Subscription-2</muse-wsa:ResourceId>"); asText = request.buildUnsubscribeRequest(parameters); envelope = EnvelopeDocument.Factory.parse(asText); errors = XMLBeansParser.validate(envelope); Assert.assertTrue("Unsubscribe request is not valid: " + errors, errors.isEmpty()); }
// adds unsigned certs & revocation infos (CRL or OCSP) to existing certs & revocation info list // ('certificates' and 'crls' CMS fields) public void appendValidationValues(Collection certificateValues, Collection revocationValues) { try { Store certStore = cmsSignedData.getCertificates(); Store crlStore = cmsSignedData.getCRLs(); if (certificateValues != null && !certificateValues.isEmpty()) { Collection<Certificate> existingCerts = getSignatureCertificateInfo(); Set<Certificate> newCerts = new HashSet<Certificate>(existingCerts); // 'Set' to avoid duplicates newCerts.addAll(certificateValues); certStore = new JcaCertStore(newCerts); } if (revocationValues != null && !revocationValues.isEmpty()) { Collection<CRL> existingCrls = getUnsignedCRLs(); Set<CRL> newCrls = new HashSet<CRL>(existingCrls); // 'Set' to avoid duplicates // FIXME : also add OCSP info (use OtherRevocationInfoFormat of RevocationInfoChoices, see // RFC 3852) for (Object o : revocationValues) { if (o instanceof CRL) newCrls.add((CRL) o); } crlStore = new JcaCRLStore(newCrls); } cmsSignedData = CMSSignedData.replaceCertificatesAndCRLs( cmsSignedData, certStore, cmsSignedData.getAttributeCertificates(), crlStore); } catch (Exception e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } }
@Test public void persistir() throws Exception { Trabalho trabalho; trabalho = new Trabalho(); trabalho.setTitulo("Teste"); trabalho.setResumo("Trabalho de Teste"); Curso curso; curso = new Curso(); curso.setSigla("SEG"); curso.setCodigo("SEG"); curso.setSituacao(Situacao.ATIVO); curso.setNome("Seguranca em Redes"); trabalho.setCurso(curso); Pessoa docente; docente = new Pessoa(); docente.setNome("Pesquisador"); docente.setCodigo("00000000000"); docente.setGraduacao(Graduacao.MESTRE); docente.setEmail("*****@*****.**"); Usuario orientador; orientador = new Usuario(); orientador.setSenha("senha"); orientador.setPessoa(docente); orientador.setLogin("00000000000"); orientador.setSituacao(Situacao.ATIVO); orientador.setGrupo(GrupoUsuario.DOCENTE); trabalho.setOrientador(orientador); Pessoa aluno; aluno = new Pessoa(); aluno.setNome("Aluno"); aluno.setCodigo("11111111111"); aluno.setEmail("*****@*****.**"); Usuario orientado; orientado = new Usuario(); orientado.setPessoa(aluno); orientado.setSenha("senha"); orientado.setLogin("11111111111"); orientado.setSituacao(Situacao.ATIVO); orientado.setGrupo(GrupoUsuario.ALUNO); trabalho.adicionarAluno(orientado); TrabalhoDao trabalhoDao = new TrabalhoDao(manager); Collection<Trabalho> trabalhos; trabalhos = trabalhoDao.buscar(new Trabalho(), new Paginacao()); assertThat(trabalhos.isEmpty(), is(true)); trabalhoDao.persistir(trabalho); trabalhos = trabalhoDao.buscar(new Trabalho(), new Paginacao()); assertThat(trabalhos.isEmpty(), is(false)); }
@Override public Set<File> generateFilePaths(SequencerPoolPartition partition) throws SubmissionException { Set<File> filePaths = new HashSet<File>(); if ((partition.getSequencerPartitionContainer().getRun().getFilePath()) == null) { throw new SubmissionException("No valid run filepath!"); } Pool<? extends Poolable> pool = partition.getPool(); if (pool == null) { throw new SubmissionException("partition.getPool=null!"); } else { Collection<Experiment> experiments = pool.getExperiments(); if (experiments.isEmpty()) { throw new SubmissionException("Collection or experiments is empty"); } else { Collection<? extends Dilution> libraryDilutions = pool.getDilutions(); if (libraryDilutions.isEmpty()) { throw new SubmissionException("Collection of libraryDilutions is empty"); } else { for (Dilution l : libraryDilutions) { Set<File> files = generateFilePath(partition, l); filePaths.addAll(files); } } } } return filePaths; }
public static SVNAdminArea upgrade(SVNAdminArea area) throws SVNException { if (isUpgradeEnabled() && !ourFactories.isEmpty()) { Collection enabledFactories = getSelector().getEnabledFactories(area.getRoot(), ourFactories, true); if (!enabledFactories.isEmpty()) { SVNAdminAreaFactory newestFactory = (SVNAdminAreaFactory) enabledFactories.iterator().next(); SVNAdminArea newArea = newestFactory.doChangeWCFormat(area); if (newArea != null && newArea != area && newArea.getWCAccess() != null) { SVNEvent event = SVNEventFactory.createSVNEvent( newArea.getRoot(), SVNNodeKind.DIR, null, SVNRepository.INVALID_REVISION, SVNEventAction.UPGRADE, null, null, null); newArea.getWCAccess().handleEvent(event, ISVNEventHandler.UNKNOWN); } area = newArea; } } return area; }
@GET @Path("/all") @AnonymousAllowed public Response getLinks(@QueryParam("gadgetId") Long gadgetId) { final ApplicationUser applicationUser = authenticationContext.getUser(); final User user = applicationUser.getDirectoryUser(); if (this.justStarted) { Map<String, String> userPrefs = portletConfigurationManager.getByPortletId(gadgetId).getUserPrefs(); // TODO: pass in the name of used UserPref as ajax parameter String allLinks = userPrefs.get("allLinks"); if (customlinks.isEmpty() && allLinks != null && allLinks != "") userPrefProcess(allLinks); this.justStarted = false; } if (customlinks.isEmpty()) { CacheControl cc = new CacheControl(); cc.setNoCache(true); return Response.ok(new Warning()).cacheControl(cc).build(); } CacheControl cc = new CacheControl(); cc.setNoCache(true); return Response.ok(customlinks).cacheControl(cc).build(); }
/** * Returns the destination of a relation. The destination of a relation is defined as the * modelelement that receives this relation. If there are more then 1 destinations, only the first * is returned. If there is no destination, null is returned. Examples of sources include * classifiers that are types to associationends, usecases that are bases to extend and include * relations and so on. In the case of an association, the destination is defined as the type of * the second element in the connections list. * * @param relation * @return MModelElement */ public MModelElement getDestination(MRelationship relation) { if (relation instanceof MAssociation) { MAssociation assoc = (MAssociation) relation; List conns = assoc.getConnections(); if (conns.size() <= 1) return null; return ((MAssociationEnd) conns.get(1)).getType(); } if (relation instanceof MGeneralization) { MGeneralization gen = (MGeneralization) relation; return gen.getChild(); } if (relation instanceof MDependency) { MDependency dep = (MDependency) relation; Collection col = dep.getClients(); if (col.isEmpty()) return null; return (MModelElement) (col.toArray())[0]; } if (relation instanceof MFlow) { MFlow flow = (MFlow) relation; Collection col = flow.getTargets(); if (col.isEmpty()) return null; return (MModelElement) (col.toArray())[0]; } if (relation instanceof MExtend) { MExtend extend = (MExtend) relation; return extend.getBase(); } if (relation instanceof MInclude) { MInclude include = (MInclude) relation; return include.getAddition(); } return null; }
@Override public BiologicalEntity getOrCreateBiologicalEntity( String bioentityName, URI bioentityURI, Collection<String> bioentityTypeName, Collection<URI> bioentityTypeURI, Study... studies) { // ping to keep caches alive ping(); if (!biologicalEntityCache.containsKey(bioentityURI)) { if (!bioentityTypeURI.isEmpty()) { biologicalEntityCache.put( bioentityURI, new SimpleBiologicalEntity(bioentityURI, bioentityName, bioentityTypeURI, studies)); } else if (!bioentityTypeName.isEmpty()) { biologicalEntityCache.put( bioentityURI, new SimpleBiologicalEntity( bioentityURI, bioentityName, mintBioentityTypeURIs(bioentityTypeName), studies)); } else { biologicalEntityCache.put( bioentityURI, new SimpleBiologicalEntity( bioentityURI, bioentityName, getDefaultTargetTypeUri(), studies)); } } return biologicalEntityCache.get(bioentityURI); }
/** * Grammatically and semantically validates the JPQL query. If the query is not valid, then an * exception will be thrown. * * @param queryContext The context used to query information about the application metadata and * cached information * @param expression The {@link org.eclipse.persistence.jpa.jpql.parser.Expression Expression} to * validate grammatically and semantically */ private void validate( JPQLQueryContext queryContext, org.eclipse.persistence.jpa.jpql.parser.Expression expression) { if (validationLevel != ParserValidationType.None) { Collection<JPQLQueryProblem> problems = new LinkedList<JPQLQueryProblem>(); // Validate the JPQL query grammatically (based on the JPQL grammar) EclipseLinkGrammarValidator grammar = new EclipseLinkGrammarValidator(jpqlGrammar()); grammar.setProblems(problems); expression.accept(grammar); if (!problems.isEmpty()) { throw buildException(queryContext, problems, HermesParser_GrammarValidator_ErrorMessage); } // Validate the JPQL query semantically (contextually) EclipseLinkSemanticValidator semantic = new EclipseLinkSemanticValidator(queryContext); semantic.setProblems(problems); expression.accept(semantic); if (!problems.isEmpty()) { throw buildException(queryContext, problems, HermesParser_SemanticValidator_ErrorMessage); } } }
public void testGetPossibleEndTagsInContext() throws ParseException { HtmlParseResult result = parse( "<!DOCTYPE html><html><head><title>hello</title></head><body><div>ahoj</div></body></html>"); assertNotNull(result.root()); Node body = ElementUtils.query(result.root(), "html/body"); Collection<HtmlTag> possible = result.getPossibleCloseTags(body).keySet(); assertFalse(possible.isEmpty()); HtmlTag htmlTag = new HtmlTagImpl("html"); HtmlTag headTag = new HtmlTagImpl("head"); HtmlTag bodyTag = new HtmlTagImpl("body"); HtmlTag divTag = new HtmlTagImpl("div"); Iterator<HtmlTag> possibleItr = possible.iterator(); assertEquals(bodyTag, possibleItr.next()); assertEquals(htmlTag, possibleItr.next()); assertFalse(possible.contains(divTag)); Node head = ElementUtils.query(result.root(), "html/head"); possible = result.getPossibleOpenTags(head); assertTrue(!possible.isEmpty()); HtmlTag titleTag = new HtmlTagImpl("title"); assertTrue(possible.contains(titleTag)); assertFalse(possible.contains(headTag)); }
protected static void printAndInterpretTemplateLines( Collection<String> templateLines, boolean forcePrintHitHeader, boolean newLineBetweenHits, NodeOrRelationship entity, GraphDatabaseShellServer server, Session session, Output out) throws ShellException, RemoteException { if (templateLines.isEmpty() || forcePrintHitHeader) { out.println(getDisplayName(server, session, entity, true)); } if (!templateLines.isEmpty()) { Map<String, Object> data = new HashMap<String, Object>(); data.put("i", entity.getId()); for (String command : templateLines) { String line = TextUtil.templateString(command, data); server.interpretLine(session.getId(), line, out); } } if (newLineBetweenHits) { out.println(); } }
@Override public String[] unparse(LoadContext context, CDOMObject cdo) { Changes<Type> changes = context.getObjectContext().getListChanges(cdo, ListKey.TYPE); if (changes == null || changes.isEmpty()) { return null; } StringBuilder sb = new StringBuilder(); Collection<?> added = changes.getAdded(); boolean globalClear = changes.includesGlobalClear(); if (globalClear) { sb.append(Constants.LST_DOT_CLEAR); } if (added != null && !added.isEmpty()) { if (globalClear) { sb.append(Constants.DOT); } sb.append(StringUtil.join(added, Constants.DOT)); } Collection<Type> removed = changes.getRemoved(); if (removed != null && !removed.isEmpty()) { if (sb.length() > 0) { sb.append(Constants.DOT); } sb.append("REMOVE."); sb.append(StringUtil.join(removed, Constants.DOT)); } if (sb.length() == 0) { context.addWriteMessage( getTokenName() + " was expecting non-empty changes to include " + "added items or global clear"); return null; } return new String[] {sb.toString()}; }
private List<HighlightInfo> getHighlights() { if (myReadAccessRanges.isEmpty() && myWriteAccessRanges.isEmpty()) { return Collections.emptyList(); } Set<Pair<Object, TextRange>> existingMarkupTooltips = new HashSet<Pair<Object, TextRange>>(); for (RangeHighlighter highlighter : myEditor.getMarkupModel().getAllHighlighters()) { existingMarkupTooltips.add( Pair.create( highlighter.getErrorStripeTooltip(), new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset()))); } List<HighlightInfo> result = new ArrayList<HighlightInfo>(myReadAccessRanges.size() + myWriteAccessRanges.size()); for (TextRange range : myReadAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_READ, existingMarkupTooltips), result); } for (TextRange range : myWriteAccessRanges) { ContainerUtil.addIfNotNull( createHighlightInfo( range, HighlightInfoType.ELEMENT_UNDER_CARET_WRITE, existingMarkupTooltips), result); } return result; }
public void actionPerformed(ActionEvent e) { if (!isEnabled()) return; if (getEditLayer().isUploadDiscouraged()) { if (UploadAction.warnUploadDiscouraged(getEditLayer())) { return; } } UploadHullBuilder builder = new UploadHullBuilder(); UploadSelectionDialog dialog = new UploadSelectionDialog(); Collection<OsmPrimitive> modifiedCandidates = getModifiedPrimitives(getEditLayer().data.getAllSelected()); Collection<OsmPrimitive> deletedCandidates = getDeletedPrimitives(getEditLayer().data); if (modifiedCandidates.isEmpty() && deletedCandidates.isEmpty()) { JOptionPane.showMessageDialog( Main.parent, tr("No changes to upload."), tr("Warning"), JOptionPane.INFORMATION_MESSAGE); return; } dialog.populate(modifiedCandidates, deletedCandidates); dialog.setVisible(true); if (dialog.isCanceled()) return; Collection<OsmPrimitive> toUpload = builder.build(dialog.getSelectedPrimitives()); if (toUpload.isEmpty()) { JOptionPane.showMessageDialog( Main.parent, tr("No changes to upload."), tr("Warning"), JOptionPane.INFORMATION_MESSAGE); return; } uploadPrimitives(getEditLayer(), toUpload); }
@Override protected Gist run(Account account) throws Exception { PageIterator<Gist> pages = new PageIterator<>( new PageIterator.GitHubRequest<List<Gist>>() { @Override public GithubClient<List<Gist>> execute(int page) { return new PublicGistsClient(context, 1); } }, 1); pages.next(); int randomPage = 1 + (int) (Math.random() * ((pages.getLastPage() - 1) + 1)); Collection<Gist> gists = pages.getRequest().execute(randomPage).executeSync(); // Make at least two tries since page numbers are volatile if (gists.isEmpty()) { randomPage = 1 + (int) (Math.random() * ((pages.getLastPage() - 1) + 1)); gists = pages.getRequest().execute(randomPage).executeSync(); } if (gists.isEmpty()) throw new IllegalArgumentException(getContext().getString(R.string.no_gists_found)); return store.addGist(gists.iterator().next()); }
private String getRemotCoreUrl(String collectionName, String origCorename) { ClusterState clusterState = cores.getZkController().getClusterState(); Collection<Slice> slices = clusterState.getActiveSlices(collectionName); boolean byCoreName = false; if (slices == null) { slices = new ArrayList<>(); // look by core name byCoreName = true; getSlicesForCollections(clusterState, slices, true); if (slices.isEmpty()) { getSlicesForCollections(clusterState, slices, false); } } if (slices.isEmpty()) { return null; } if (collectionsList == null) collectionsList = new ArrayList<>(); collectionsList.add(collectionName); String coreUrl = getCoreUrl(collectionName, origCorename, clusterState, slices, byCoreName, true); if (coreUrl == null) { coreUrl = getCoreUrl(collectionName, origCorename, clusterState, slices, byCoreName, false); } return coreUrl; }
private boolean merge(boolean mergeDialogInvokedFromNotification) { try { final Collection<VirtualFile> initiallyUnmergedFiles = getUnmergedFiles(myRoots); if (initiallyUnmergedFiles.isEmpty()) { LOG.info("merge: no unmerged files"); return mergeDialogInvokedFromNotification ? true : proceedIfNothingToMerge(); } else { showMergeDialog(initiallyUnmergedFiles); final Collection<VirtualFile> unmergedFilesAfterResolve = getUnmergedFiles(myRoots); if (unmergedFilesAfterResolve.isEmpty()) { LOG.info("merge no more unmerged files"); return mergeDialogInvokedFromNotification ? true : proceedAfterAllMerged(); } else { LOG.info("mergeFiles unmerged files remain: " + unmergedFilesAfterResolve); if (mergeDialogInvokedFromNotification) { notifyUnresolvedRemainAfterNotification(); } else { notifyUnresolvedRemain(); } } } } catch (VcsException e) { if (myVcs.getExecutableValidator().checkExecutableAndNotifyIfNeeded()) { notifyException(e); } } return false; }
/** * Update index (delete and remove files) * * @param project the project * @param root a vcs root * @param added added/modified files to commit * @param removed removed files to commit * @param exceptions a list of exceptions to update * @return true if index was updated successfully */ private static boolean updateIndex( final Project project, final VirtualFile root, final Collection<FilePath> added, final Collection<FilePath> removed, final List<VcsException> exceptions) { boolean rc = true; if (!added.isEmpty()) { try { GitFileUtils.addPaths(project, root, added); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } if (!removed.isEmpty()) { try { GitFileUtils.delete(project, root, removed, "--ignore-unmatch"); } catch (VcsException ex) { exceptions.add(ex); rc = false; } } return rc; }
/** * Helper to add srcs and deps Soy files to a SoyFileSet builder. Also does sanity checks. * * @param sfsBuilder The SoyFileSet builder to add to. * @param inputPrefix The input path prefix to prepend to all the file paths. * @param srcs The srcs from the --srcs flag. Exactly one of 'srcs' and 'args' must be nonempty. * @param args The old-style srcs from the command line (that's how they were specified before we * added the --srcs flag). Exactly one of 'srcs' and 'args' must be nonempty. * @param deps The deps from the --deps flag, or empty list if not applicable. * @param exitWithErrorFn A function that exits with an error message followed by a usage message. */ static void addSoyFilesToBuilder( Builder sfsBuilder, String inputPrefix, Collection<String> srcs, Collection<String> args, Collection<String> deps, Collection<String> indirectDeps, Function<String, Void> exitWithErrorFn) { if (srcs.isEmpty() && args.isEmpty()) { exitWithErrorFn.apply("Must provide list of source Soy files (--srcs)."); } if (!srcs.isEmpty() && !args.isEmpty()) { exitWithErrorFn.apply( "Found source Soy files from --srcs and from args (please use --srcs only)."); } // Create Set versions of each of the arguments, and de-dupe. If something is included as // multiple file kinds, we'll keep the strongest one; a file in both srcs and deps will be a // src, and one in both deps and indirect_deps will be a dep. // TODO(gboyer): Maybe stop supporting old style (srcs from command line args) at some point. Set<String> srcsSet = ImmutableSet.<String>builder().addAll(srcs).addAll(args).build(); Set<String> depsSet = Sets.difference(ImmutableSet.copyOf(deps), srcsSet); Set<String> indirectDepsSet = Sets.difference(ImmutableSet.copyOf(indirectDeps), Sets.union(srcsSet, depsSet)); for (String src : srcsSet) { sfsBuilder.addWithKind(new File(inputPrefix + src), SoyFileKind.SRC); } for (String dep : depsSet) { sfsBuilder.addWithKind(new File(inputPrefix + dep), SoyFileKind.DEP); } for (String dep : indirectDepsSet) { sfsBuilder.addWithKind(new File(inputPrefix + dep), SoyFileKind.INDIRECT_DEP); } }
/** * Returns the source of a relation. The source of a relation is defined as the modelelement that * propagates this relation. If there are more then 1 sources, only the first is returned. If * there is no source, null is returned. Examples of sources include classifiers that are types to * associationends, usecases that are bases to extend and include relations and so on. * * @param relation * @return MModelElement */ public MModelElement getSource(MRelationship relation) { if (relation instanceof MAssociation) { MAssociation assoc = (MAssociation) relation; List conns = assoc.getConnections(); if (conns.isEmpty()) return null; return ((MAssociationEnd) conns.get(0)).getType(); } if (relation instanceof MGeneralization) { MGeneralization gen = (MGeneralization) relation; return gen.getParent(); } if (relation instanceof MDependency) { MDependency dep = (MDependency) relation; Collection col = dep.getSuppliers(); if (col.isEmpty()) return null; return (MModelElement) (col.toArray())[0]; } if (relation instanceof MFlow) { MFlow flow = (MFlow) relation; Collection col = flow.getSources(); if (col.isEmpty()) return null; return (MModelElement) (col.toArray())[0]; } if (relation instanceof MExtend) { MExtend extend = (MExtend) relation; return extend.getExtension(); // we have to follow the arrows.. } if (relation instanceof MInclude) { MInclude include = (MInclude) relation; return include.getBase(); } return null; }
public String[] unparse(LoadContext context, Race race) { Changes<RaceSubType> changes = context.getObjectContext().getListChanges(race, ListKey.RACESUBTYPE); if (changes == null || changes.isEmpty()) { return null; } List<String> list = new ArrayList<String>(); Collection<RaceSubType> removedItems = changes.getRemoved(); if (changes.includesGlobalClear()) { if (removedItems != null && !removedItems.isEmpty()) { context.addWriteMessage( "Non-sensical relationship in " + getTokenName() + ": global .CLEAR and local .CLEAR. performed"); return null; } list.add(Constants.LST_DOT_CLEAR); } else if (removedItems != null && !removedItems.isEmpty()) { list.add(Constants.LST_DOT_CLEAR_DOT + StringUtil.join(removedItems, "|.CLEAR.")); } Collection<RaceSubType> added = changes.getAdded(); if (added != null && !added.isEmpty()) { list.add(StringUtil.join(added, Constants.PIPE)); } if (list.isEmpty()) { return null; } return list.toArray(new String[list.size()]); }
protected Collection<EnforcedRelation> match( TIntHashSet subset, TIntObjectHashMap<Collection<EnforcedRelation>> index) { TIntIterator keyI = subset.iterator(); int firstKey = keyI.next(); if (index.get(firstKey) == null) { return Collections.emptyList(); } Collection<EnforcedRelation> result = new ArrayList<EnforcedRelation>(index.get(firstKey)); if (result.isEmpty()) { return Collections.emptyList(); } while (keyI.hasNext()) { int key = keyI.next(); if (result.isEmpty()) return result; Collection<EnforcedRelation> rest = index.get(key); if (rest == null) { return Collections.emptyList(); } result.retainAll(rest); } return result; }