List of usage examples for java.util SortedSet iterator
Iterator<E> iterator();
From source file:org.tolweb.content.preparers.PageCoPreparer.java
@SuppressWarnings("unchecked") public void processContent() { Element page = new Element(PageContentElements.PAGE, ContentPreparer.NS); page.addAttribute(new Attribute(PageContentAttributes.ID, "" + getMappedPage().getPageId())); String pageNodeNameUrl = getMappedPage().getMappedNode().getName(); try {/* w ww . ja va 2 s .c o m*/ pageNodeNameUrl = URLEncoder.encode(pageNodeNameUrl, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } String nodeIdString = "" + getMappedPage().getMappedNode().getId(); pageNodeNameUrl = StringUtils.notEmpty(pageNodeNameUrl) ? pageNodeNameUrl + "/" + nodeIdString : nodeIdString; String pageUrl = "http://tolweb.org/" + pageNodeNameUrl; page.addAttribute(new Attribute(PageContentAttributes.PAGE_URL, pageUrl)); page.addAttribute(new Attribute(PageContentAttributes.PAGE_STATUS, getMappedPage().getStatus())); page.addAttribute(new Attribute(PageContentAttributes.DATE_CREATED, getSafeString(getMappedPage().getFirstOnlineString()))); page.addAttribute(new Attribute(PageContentAttributes.DATE_CHANGED, safeToString(getMappedPage().getContentChangedDate()))); Element group = new Element(PageContentElements.GROUP, ContentPreparer.NS); page.appendChild(group); group.addAttribute(new Attribute(PageContentAttributes.NODE, "" + getMappedPage().getMappedNode().getId())); group.addAttribute(new Attribute(PageContentAttributes.EXTINCT, (getMappedPage().getMappedNode().getExtinct() == 2) ? "true" : "false")); group.addAttribute(new Attribute(PageContentAttributes.PHYLESIS, getPhylesisString(getMappedPage().getMappedNode().getPhylesis()))); group.addAttribute(new Attribute(PageContentAttributes.LEAF, getMappedPage().getMappedNode().getIsLeaf() ? "true" : "false")); Element groupDesc = new Element(PageContentElements.GROUP_DESCRIPTION, ContentPreparer.NS); String groupDescText = getMappedPage().getMappedNode().getDescription(); groupDesc.appendChild(new Text(groupDescText)); if (StringUtils.notEmpty(groupDescText)) { group.appendChild(groupDesc); } Element groupCmt = new Element(PageContentElements.GROUP_COMMENT, ContentPreparer.NS); String groupCmtText = getMappedPage().getLeadText(); groupCmt.appendChild(new Text(groupCmtText)); if (StringUtils.notEmpty(groupCmtText)) { group.appendChild(groupCmt); } Element names = new Element(PageContentElements.NAMES, ContentPreparer.NS); page.appendChild(names); Element name = new Element(PageContentElements.NAME, ContentPreparer.NS); names.appendChild(name); name.appendChild(new Text(getMappedPage().getMappedNode().getName())); name.addAttribute(new Attribute(PageContentAttributes.ITALICIZE_NAME, Boolean.valueOf(getMappedPage().getMappedNode().getItalicizeName()).toString())); name.addAttribute(new Attribute(PageContentAttributes.AUTHORITY, getSafeString(getMappedPage().getMappedNode().getNameAuthority()))); name.addAttribute(new Attribute(PageContentAttributes.AUTH_DATE, safeToString(getMappedPage().getMappedNode().getAuthorityDate()))); name.addAttribute(new Attribute(PageContentAttributes.NAME_COMMENT, getSafeString(getMappedPage().getMappedNode().getNameComment()))); name.addAttribute(new Attribute(PageContentAttributes.NEW_COMBINATION, Boolean.valueOf(getMappedPage().getMappedNode().getIsNewCombination()).toString())); name.addAttribute(new Attribute(PageContentAttributes.COMBINATION_AUTHOR, getSafeString(getMappedPage().getMappedNode().getCombinationAuthor()))); name.addAttribute(new Attribute(PageContentAttributes.COMBINATION_DATE, safeToString(getMappedPage().getMappedNode().getCombinationDate()))); Element othernames = new Element(PageContentElements.OTHERNAMES, ContentPreparer.NS); SortedSet otherNamesSet = getMappedPage().getMappedNode().getSynonyms(); for (Iterator itr = otherNamesSet.iterator(); itr.hasNext();) { MappedOtherName moname = (MappedOtherName) itr.next(); Element othername = new Element(PageContentElements.OTHERNAME, ContentPreparer.NS); othername.addAttribute(new Attribute(PageContentAttributes.ID, "" + moname.getId())); othername.addAttribute(new Attribute(PageContentAttributes.ITALICIZE_NAME, Boolean.valueOf(moname.getItalicize()).toString())); othername.addAttribute( new Attribute(PageContentAttributes.AUTHORITY, getSafeString(moname.getAuthority()))); othername.addAttribute( new Attribute(PageContentAttributes.AUTH_DATE, safeToString(moname.getAuthorityYear()))); othername.addAttribute( new Attribute(PageContentAttributes.NAME_COMMENT, getSafeString(moname.getComment()))); othername.addAttribute(new Attribute(PageContentAttributes.IS_IMPORTANT, Boolean.valueOf(moname.getIsImportant()).toString())); othername.addAttribute(new Attribute(PageContentAttributes.IS_PREFERRED, Boolean.valueOf(moname.getIsPreferred()).toString())); othername.addAttribute(new Attribute(PageContentAttributes.SEQUENCE, safeToString(moname.getOrder()))); } if (!otherNamesSet.isEmpty()) { names.appendChild(othernames); } List children = getMappedPage().getMappedNode().getChildren(); boolean isTerminal = children != null && children.isEmpty(); // add this if not a leaf or writeaslist is false... or is terminal (e.g. no children) if (getMappedPage().getMappedNode().getIsLeaf() && !isTerminal) { Element subgroups = new Element(PageContentElements.SUBGROUPS, ContentPreparer.NS); page.appendChild(subgroups); if (!getMappedPage().getWriteAsList()) { Element treeimage = new Element(PageContentElements.TREEIMAGE, ContentPreparer.NS); ContributorLicenseInfo currDefault = new ContributorLicenseInfo( ContributorLicenseInfo.TREE_IMAGE_LICENSE); treeimage.addAttribute(new Attribute(PageContentAttributes.LICENSE, currDefault.toShortString())); String treeImageName = getMappedPage().getGroupName().replaceAll("\\s", "_"); treeimage .appendChild(new Text("http://www.tolweb.org/Public/treeImages/" + treeImageName + ".png")); subgroups.appendChild(treeimage); } Element newicktree = new Element(PageContentElements.NEWICKTREE, ContentPreparer.NS); subgroups.appendChild(newicktree); Element taxonlist = new Element(PageContentElements.TAXON_LIST, ContentPreparer.NS); taxonlist.appendChild(new Text(StringEscapeUtils.escapeXml(getTaxonListAsHTML()))); subgroups.appendChild(taxonlist); Element treecomment = new Element(PageContentElements.TREE_COMMENT, ContentPreparer.NS); subgroups.appendChild(treecomment); treecomment.appendChild(new Text(StringEscapeUtils.escapeXml(getMappedPage().getPostTreeText()))); } Element sections = new Element(PageContentElements.SECTIONS, ContentPreparer.NS); page.appendChild(sections); SortedSet textSections = getMappedPage().getTextSections(); for (Iterator itr = textSections.iterator(); itr.hasNext();) { MappedTextSection mtxt = (MappedTextSection) itr.next(); Element section = new Element(PageContentElements.SECTION, ContentPreparer.NS); section.addAttribute(new Attribute(PageContentAttributes.ID, "" + mtxt.getTextSectionId())); section.addAttribute(new Attribute(PageContentAttributes.SECTION_TITLE, mtxt.getHeading())); section.addAttribute(new Attribute(PageContentAttributes.PAGE_ORDER, safeToString(mtxt.getOrder()))); section.addAttribute( new Attribute(PageContentAttributes.COPYRIGHT_DATE, getMappedPage().getCopyrightDate())); section.addAttribute(new Attribute(PageContentAttributes.LICENSE, getLicenseShortName(getMappedPage().getUsePermission()))); section.addAttribute(new Attribute(PageContentAttributes.AUTHORS, getAuthorsIdString(getMappedPage().getContributors()))); section.addAttribute(new Attribute(PageContentAttributes.CORRESPONDENTS, getCorrespondentsIdString(getMappedPage().getContributors()))); section.addAttribute(new Attribute(PageContentAttributes.COPYRIGHT_OWNERS, getCopyrightOwnersIdString(getMappedPage().getContributors()))); section.addAttribute(new Attribute(PageContentAttributes.OTHER_COPYRIGHT, getSafeString(getMappedPage().getCopyrightHolder()))); section.addAttribute(new Attribute(PageContentAttributes.CONTENT_CHANGED, safeToString(getMappedPage().getContentChangedDate()))); // add the section-text text element Element sectionText = new Element(PageContentElements.SECTION_TEXT, ContentPreparer.NS); sectionText.appendChild(new Text(processSectionText(mtxt.getText(), pageUrl))); section.appendChild(sectionText); Element sectionMedia = new Element(PageContentElements.SECTION_MEDIA, ContentPreparer.NS); processSectionMedia(sectionMedia); section.appendChild(sectionMedia); // add the section-source element Element sectionSource = new Element(PageContentElements.SECTION_SOURCE, ContentPreparer.NS); // TODO add attribute data to section-source section.appendChild(sectionSource); String sectionAnchor = mtxt.getHeadingNoSpaces(); sectionSource.addAttribute(new Attribute(PageContentAttributes.SOURCE_COLLECTION, "0")); sectionSource.addAttribute(new Attribute(PageContentAttributes.SOURCE_TITLE, mtxt.getHeading())); sectionSource.addAttribute(new Attribute(PageContentAttributes.SOURCE_URL, "http://tolweb.org/" + pageNodeNameUrl + "#" + sectionAnchor)); sectionSource.addAttribute(new Attribute(PageContentAttributes.MORE_SOURCE, "[future-use]")); sections.appendChild(section); } Element refs = new Element(PageContentElements.REFERENCES, ContentPreparer.NS); page.appendChild(refs); TextPreparer txtPrep = new TextPreparer(); List refsList = txtPrep.getNewlineSeparatedList(getMappedPage().getReferences()); for (Iterator itr = refsList.iterator(); itr.hasNext();) { String ref = (String) itr.next(); // only add the reference element if it's not empty if (StringUtils.notEmpty(ref)) { Element refEl = new Element(PageContentElements.REFERENCE, ContentPreparer.NS); refEl.appendChild(new Text(StringEscapeUtils.escapeXml(ref))); refs.appendChild(refEl); } } Element internetInfo = new Element(PageContentElements.INTERNET_INFO, ContentPreparer.NS); page.appendChild(internetInfo); internetInfo.appendChild(new Text(StringEscapeUtils.escapeXml(getMappedPage().getInternetInfo()))); getElement().appendChild(page); }
From source file:org.tolweb.content.preparers.EolContentPreparer.java
@SuppressWarnings("unchecked") private void addTextSectionDataObjects(MappedPage mpage, DaoBundle daos, Element taxon, HashMap<Integer, String> embeddedMedia) { SortedSet textSections = mpage.getTextSections(); for (Iterator<MappedTextSection> itr = textSections.iterator(); itr.hasNext();) { MappedTextSection mtxt = itr.next(); addTextSectionDataObject(mpage, daos, taxon, embeddedMedia, mtxt); }/*w w w . j av a 2 s . c o m*/ }
From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImpl.java
@Override public AvailableBlock retrieveTargetBlock(IScheduleOwner owner, Date startDate, Date endDate) { SortedSet<AvailableBlock> expanded = retrieveBlocksForDayInternal(owner, startDate); // truncate startDate and endDate to the second final Date truncatedStart = DateUtils.truncate(startDate, Calendar.MINUTE); final Date truncatedEnd = DateUtils.truncate(endDate, Calendar.MINUTE); if (expanded.size() > 0) { for (Iterator<AvailableBlock> expandedIterator = expanded.iterator(); expandedIterator.hasNext();) { AvailableBlock block = expandedIterator.next(); if (block.getStartTime().equals(truncatedStart)) { if (block.getEndTime().equals(truncatedEnd)) { return block; }//w w w. j a v a2 s.c o m // start time matches but end time doesn't // check to see if the next block has matching end if (expandedIterator.hasNext()) { AvailableBlock nextBlock = expandedIterator.next(); if (nextBlock.getEndTime().equals(truncatedEnd)) { // start and end represent a double length block, combine and return AvailableBlock combined = AvailableBlockBuilder.createBlock(block.getStartTime(), nextBlock.getEndTime(), block.getVisitorLimit(), block.getMeetingLocation()); return combined; } } } if (block.getStartTime().after(truncatedStart)) { // iterated past the target block, can short circuit and say we didn't find it return null; } } } // block not found, return null return null; }
From source file:com.springsource.hq.plugin.tcserver.plugin.appmgmt.TomcatJmxApplicationManager.java
private Set<Application> createApplicationStatusMapping(Properties configProperties, String serviceName, String hostName, boolean tomcat7) throws PluginException { SortedSet<Application> applications = fetchApplications(configProperties, serviceName, hostName); Iterator<Application> applicationsIterator = applications.iterator(); while (applicationsIterator.hasNext()) { Application application = applicationsIterator.next(); try {/*w ww . jav a 2s . c om*/ fetchAndApplyApplicationStatus(configProperties, serviceName, hostName, application); fetchAndApplySessionCount(configProperties, hostName, application, tomcat7); } catch (PluginException pe) { LOGGER.warn(String.format( "Failed to collect details for application '%s' deployed on service '%s' and host '%s'", application.getName(), serviceName, hostName), pe); applicationsIterator.remove(); } } return applications; }
From source file:com.spotify.heroic.filter.AndFilter.java
static Filter optimize(final SortedSet<Filter> filters) { final SortedSet<Filter> result = new TreeSet<>(); for (final Filter f : filters) { if (f instanceof NotFilter) { // Optimize away expressions which are always false. // Example: foo = bar and !(foo = bar) if (filters.contains(((NotFilter) f).getFilter())) { return FalseFilter.get(); }/*from w ww .j a v a 2s . com*/ } else if (f instanceof StartsWithFilter) { // Optimize away prefixes which encompass each other. // Example: foo ^ hello and foo ^ helloworld -> foo ^ helloworld if (FilterUtils.containsPrefixedWith(filters, (StartsWithFilter) f, (inner, outer) -> FilterUtils.prefixedWith(inner.getValue(), outer.getValue()))) { continue; } } else if (f instanceof MatchTagFilter) { // Optimize matchTag expressions which are always false. // Example: foo = bar and foo = baz if (FilterUtils.containsConflictingMatchTag(filters, (MatchTagFilter) f)) { return FalseFilter.get(); } } else if (f instanceof MatchKeyFilter) { // Optimize matchTag expressions which are always false. // Example: $key = bar and $key = baz if (FilterUtils.containsConflictingMatchKey(filters, (MatchKeyFilter) f)) { return FalseFilter.get(); } } result.add(f); } if (result.isEmpty()) { return FalseFilter.get(); } if (result.size() == 1) { return result.iterator().next(); } return new AndFilter(ImmutableList.copyOf(result)); }
From source file:org.jclouds.aws.s3.jets3t.JCloudsS3ServiceLiveTest.java
@Test public void testListAllBucketsImpl() throws InterruptedException, ExecutionException, TimeoutException, S3ServiceException { String bucketName = getContainerName(); try {/* ww w.j a v a 2 s . c o m*/ // Ensure there is at least 1 bucket in S3 account to list and compare. S3Bucket[] jsBuckets = service.listAllBuckets(); SortedSet<org.jclouds.aws.s3.domain.BucketMetadata> jcBuckets = context.getApi().listOwnedBuckets(); assert jsBuckets.length == jcBuckets.size(); Iterator<org.jclouds.aws.s3.domain.BucketMetadata> jcBucketsIter = jcBuckets.iterator(); for (S3Bucket jsBucket : jsBuckets) { assert jcBucketsIter.hasNext(); org.jclouds.aws.s3.domain.BucketMetadata jcBucket = jcBucketsIter.next(); assert jsBucket.getName().equals(jcBucket.getName()); } } finally { returnContainer(bucketName); } }
From source file:org.jahia.services.content.nodetypes.initializers.TemplatesChoiceListInitializerImpl.java
public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition declaringPropertyDefinition, String param, List<ChoiceListValue> values, Locale locale, Map<String, Object> context) { if (context == null) { return new ArrayList<ChoiceListValue>(); }//from w w w . ja va 2 s . c o m JCRNodeWrapper node = (JCRNodeWrapper) context.get("contextNode"); JCRNodeWrapper parentNode = (JCRNodeWrapper) context.get("contextParent"); ExtendedNodeType realNodeType = (ExtendedNodeType) context.get("contextType"); String propertyName = context.containsKey("dependentProperties") ? ((List<String>) context.get("dependentProperties")).get(0) : null; JCRSiteNode site = null; SortedSet<View> views = new TreeSet<View>(); boolean subViews = false; try { if (node != null) { site = node.getResolveSite(); } if (site == null && parentNode != null) { site = parentNode.getResolveSite(); } final List<String> nodeTypeList = new ArrayList<String>(); String nextParam = ""; if (param.contains(",")) { nextParam = StringUtils.substringAfter(param, ","); param = StringUtils.substringBefore(param, ","); } if ("subnodes".equals(param)) { subViews = true; if (propertyName == null) { propertyName = "j:allowedTypes"; } if (context.containsKey(propertyName)) { List<String> types = (List<String>) context.get(propertyName); for (String type : types) { nodeTypeList.add(type); } } else if (node != null && node.hasProperty(propertyName)) { JCRPropertyWrapper property = node.getProperty(propertyName); if (property.isMultiple()) { Value[] types = property.getValues(); for (Value type : types) { nodeTypeList.add(type.getString()); } } else { nodeTypeList.add(property.getValue().getString()); } } else if (node != null && !"j:allowedTypes".equals(propertyName) && node.hasProperty("j:allowedTypes")) { Value[] types = node.getProperty("j:allowedTypes").getValues(); for (Value type : types) { nodeTypeList.add(type.getString()); } } else if (node != null) { // No restrictions get node type list from already existing nodes NodeIterator nodeIterator = node.getNodes(); while (nodeIterator.hasNext()) { Node next = (Node) nodeIterator.next(); String name = next.getPrimaryNodeType().getName(); if (!nodeTypeList.contains(name) && next.isNodeType("jnt:content")) { nodeTypeList.add(name); } } } param = nextParam; } else if ("reference".equals(param)) { if (propertyName == null) { propertyName = Constants.NODE; } if (context.containsKey(propertyName)) { JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession(); List<String> refNodeUuids = (List<String>) context.get(propertyName); for (String refNodeUuid : refNodeUuids) { try { JCRNodeWrapper refNode = session.getNodeByUUID(refNodeUuid); nodeTypeList.addAll(refNode.getNodeTypes()); } catch (Exception e) { logger.warn("Referenced node not found to retrieve its nodetype for initializer", e); } } } else if (node != null && node.hasProperty(propertyName)) { try { JCRNodeWrapper refNode = (JCRNodeWrapper) node.getProperty(propertyName).getNode(); nodeTypeList.addAll(refNode.getNodeTypes()); } catch (ItemNotFoundException e) { } } else if (node != null && !Constants.NODE.equals(propertyName) && node.hasProperty(Constants.NODE)) { try { JCRNodeWrapper refNode = (JCRNodeWrapper) node.getProperty(Constants.NODE).getNode(); nodeTypeList.addAll(refNode.getNodeTypes()); } catch (ItemNotFoundException e) { } } param = nextParam; } else if ("mainresource".equals(param)) { JCRNodeWrapper matchingParent; JCRNodeWrapper parent; if (node == null) { parent = (JCRNodeWrapper) context.get("contextParent"); site = parent.getResolveSite(); } else { parent = node.getParent(); } try { while (true) { if (parent.isNodeType("jnt:template")) { matchingParent = parent; break; } parent = parent.getParent(); } if (matchingParent.hasProperty("j:applyOn")) { Value[] vs = matchingParent.getProperty("j:applyOn").getValues(); for (Value v : vs) { nodeTypeList.add(v.getString()); } } } catch (ItemNotFoundException e) { } if (nodeTypeList.isEmpty()) { nodeTypeList.add("jnt:page"); } param = nextParam; } else if (param != null && param.indexOf(":") > 0) { nodeTypeList.add(param); param = nextParam; } else { if (node != null) { nodeTypeList.addAll(node.getNodeTypes()); } else if (realNodeType != null) { nodeTypeList.add(realNodeType.getName()); } } if (nodeTypeList.isEmpty()) { nodeTypeList.add("nt:base"); } SortedSet<ViewWrapper> wrappedViews = new TreeSet<ViewWrapper>(); Set<ViewWrapper> wrappedViewsSet = new HashSet<ViewWrapper>(); for (String s : nodeTypeList) { SortedSet<View> viewsSet = RenderService.getInstance() .getViewsSet(NodeTypeRegistry.getInstance().getNodeType(s), site, "html"); if (!viewsSet.isEmpty()) { // use of wrapper class to get a simpler equals method, based on the key // to keep only views in common between sub nodes for (Iterator<View> iterator = viewsSet.iterator(); iterator.hasNext();) { wrappedViewsSet.add(new ViewWrapper(iterator.next())); } if (subViews && !wrappedViews.isEmpty()) { wrappedViews.retainAll(wrappedViewsSet); } else { wrappedViews.addAll(wrappedViewsSet); } } wrappedViewsSet.clear(); } for (Iterator<ViewWrapper> iterator = wrappedViews.iterator(); iterator.hasNext();) { views.add(iterator.next().getView()); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } List<ChoiceListValue> vs = new ArrayList<ChoiceListValue>(); for (View view : views) { HashMap<String, Object> map = new HashMap<String, Object>(); fillProperties(map, view.getDefaultProperties()); fillProperties(map, view.getProperties()); boolean isStudio = site != null && site.getPath().startsWith("/modules"); if (isViewVisible(view.getKey(), param, map, isStudio)) { JahiaTemplatesPackage pkg = view.getModule() != null ? view.getModule() : ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackageById(JahiaTemplatesPackage.ID_DEFAULT); String displayName = Messages.get(pkg, declaringPropertyDefinition.getResourceBundleKey() + "." + JCRContentUtils.replaceColon(view.getKey()), locale, view.getKey()); ChoiceListValue c = new ChoiceListValue(displayName, map, new ValueImpl(view.getKey(), PropertyType.STRING, false)); try { final Resource imagePath = pkg.getResource( File.separator + "img" + File.separator + c.getValue().getString() + ".png"); if (imagePath != null && imagePath.exists()) { String s = Jahia.getContextPath(); if (s.equals("/")) { s = ""; } c.addProperty("image", s + (pkg.getRootFolderPath().startsWith("/") ? "" : "/") + pkg.getRootFolderPath() + "/img/" + c.getValue().getString() + ".png"); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } vs.add(c); } } Collections.sort(vs); return vs; }
From source file:BayesianAnalyzer.java
/** * Compute the spamminess probability of the interesting tokens in * the tokenProbabilities SortedSet./*from w w w .j a v a 2s. c o m*/ * * @param tokenProbabilities * @param workCorpus * @return Computed spamminess. */ private double computeOverallProbability(SortedSet tokenProbabilityStrengths, Map workCorpus) { double p = 1.0; double np = 1.0; double tempStrength = 0.5; int count = MAX_INTERESTING_TOKENS; Iterator iterator = tokenProbabilityStrengths.iterator(); while ((iterator.hasNext()) && (count-- > 0 || tempStrength >= INTERESTINGNESS_THRESHOLD)) { TokenProbabilityStrength tps = (TokenProbabilityStrength) iterator.next(); tempStrength = tps.strength; // System.out.println(tps); double theDoubleValue = DEFAULT_TOKEN_PROBABILITY; // initialize it to the default Double theDoubleObject = (Double) workCorpus.get(tps.token); // if either the original token or a degeneration was found use the double value, otherwise use the default if (theDoubleObject != null) { theDoubleValue = theDoubleObject.doubleValue(); } p *= theDoubleValue; np *= (1.0 - theDoubleValue); // System.out.println("Token:" + tps.token + ", p=" + theDoubleValue + ", overall p=" + p / (p + np)); } return (p / (p + np)); }
From source file:de.interactive_instruments.ShapeChange.Target.JSON.JsonSchema.java
public void process(ClassInfo ci) { int cat = ci.category(); if (options.matchesEncRule(ci.encodingRule("json"), "geoservices")) { if (cat != Options.FEATURE && cat != Options.OBJECT) { return; }/*from w w w . j a v a2 s.co m*/ } else if (options.matchesEncRule(ci.encodingRule("json"), "geoservices_extended")) { if (cat != Options.FEATURE && cat != Options.OBJECT && cat != Options.DATATYPE && cat != Options.UNION) { return; } } Context ctx = new Context(); try { if (!diagnosticsOnly) ctx.writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(new File(subDirectoryFile, ci.name() + ".json")), "UTF-8")); write(ctx, "{"); newLine(ctx); write(ctx, "\t" + "\"$schema\":\"" + schemaURI + "\","); newLine(ctx); write(ctx, "\t" + "\"id\":\"" + baseURI + "/" + subdir + "/" + ci.name() + ".json\","); newLine(ctx); String s = ci.aliasName(); write(ctx, "\t" + "\"title\":\"" + (s == null || s.isEmpty() ? ci.name() : s) + "\","); newLine(ctx); String s2 = ci.derivedDocumentation(documentationTemplate, documentationNoValue); if (includeDocumentation && !s2.isEmpty()) { write(ctx, "\t" + "\"description\":\"" + escape(s2).trim() + "\","); newLine(ctx); } write(ctx, "\t" + "\"type\":\"object\","); newLine(ctx); write(ctx, "\t" + "\"properties\":{"); newLine(ctx); // add entityType for features and objects if (cat == Options.FEATURE || cat == Options.OBJECT) { write(ctx, "\t\t" + "\"entityType\":{"); newLine(ctx); write(ctx, "\t\t\t" + "\"title\":\"feature/object type\","); newLine(ctx); write(ctx, "\t\t\t" + "\"type\":\"string\","); newLine(ctx); write(ctx, "\t\t\t" + "\"default\":\"" + (s == null || s.isEmpty() ? ci.name() : s) + "\""); newLine(ctx); write(ctx, "\t\t},"); newLine(ctx); } // add geometry for features and objects if (cat == Options.FEATURE || cat == Options.OBJECT) { String geomType = determineGeometryType(ci); if (geomType != null) { write(ctx, "\t\t" + "\"geometry\":{"); newLine(ctx); write(ctx, "\t\t\t" + "\"$ref\":\"" + geomType + "\""); newLine(ctx); write(ctx, "\t\t},"); newLine(ctx); } } else if (cat == Options.DATATYPE || cat == Options.UNION) { verifyNoGeometry(ci); } write(ctx, "\t\t" + "\"attributes\":{"); newLine(ctx); write(ctx, "\t\t\t" + "\"title\":\"feature attributes\","); newLine(ctx); write(ctx, "\t\t\t" + "\"type\":\"object\","); newLine(ctx); write(ctx, "\t\t\t" + "\"properties\":{"); newLine(ctx); SortedSet<String> st = ci.supertypes(); if (st != null) { for (Iterator<String> i = st.iterator(); i.hasNext();) { String sid = i.next(); ClassInfo cix = model.classById(sid); if (cix != null) { String cn = cix.name(); if (notImplemented(cn)) result.addWarning(this, 104, ci.name(), cn); else ctx = ProcessProperties(ctx, cix); } } } ctx = ProcessProperties(ctx, ci); newLine(ctx); write(ctx, "\t\t\t}"); if (JSON_SCHEMA_URI_DRAFT_04.equals(schemaURI)) { // TODO add required keyword: way of defining required properties is different for JSON Schema draft v04 } newLine(ctx); write(ctx, "\t\t}"); newLine(ctx); write(ctx, "\t}"); if (ctx.links != null) { write(ctx, ","); newLine(ctx); String[] lines = ctx.links.split("\n"); for (int i = 0; i < lines.length; i++) { write(ctx, lines[i]); newLine(ctx); } write(ctx, "\t]"); } newLine(ctx); write(ctx, "}"); newLine(ctx); if (ctx.writer != null) { ctx.writer.close(); result.addResult(getTargetID(), subDirectoryFile.getPath(), ci.name() + ".json", ci.qname()); } } catch (IOException e) { // Opening the file went wrong, skip class result.addError(this, 11, ci.name() + ".json"); return; } }
From source file:de.interactive_instruments.ShapeChange.Model.EA.EADocument.java
public void executeCommonInitializationProcedure() throws ShapeChangeAbortException { // determine if specific packages should not be loaded this.excludedPackageNames = options.getExcludedPackages(); /** Cache classes and packages */ // First set up initial evaluation tasks of packages consisting // of the models in the repository class EvalTask { PackageInfoEA fatherPI;//w w w .j av a2 s .c o m org.sparx.Package eaPackage; EvalTask(PackageInfoEA fpi, org.sparx.Package p) { fatherPI = fpi; eaPackage = p; } } StatusBoard.getStatusBoard().statusChanged(STATUS_EADOCUMENT_READMODEL); LinkedList<EvalTask> evalp = new LinkedList<EvalTask>(); Collection<org.sparx.Package> model = repository.GetModels(); for (org.sparx.Package p : model) { // Check if this model and all its contents shall be excluded String name = p.GetName(); if (excludedPackageNames != null && excludedPackageNames.contains(name)) { // stop processing this model and continue with the next continue; } evalp.addLast(new EvalTask(null, p)); } // Now remove tasks from the list, adding further tasks as we proceed // until we have no more tasks to evaluate while (evalp.size() > 0) { // Remove next evaluation task EvalTask et = evalp.removeFirst(); org.sparx.Package pack = et.eaPackage; PackageInfoEA fpi = et.fatherPI; // Check if this package and all its contents shall be excluded from // the model String name = pack.GetName(); if (excludedPackageNames != null && excludedPackageNames.contains(name)) { // stop processing this package and continue with the next continue; } // Add to package cache. The PackageInfo Ctor does the necessary // parent/child linkage of packages Element packelmt = pack.GetElement(); PackageInfoEA pi = new PackageInfoEA(this, fpi, pack, packelmt); fPackageById.put(pi.id(), pi); if (packelmt != null) this.fPackageByElmtId.put(new Integer(packelmt.GetElementID()).toString(), pi); // Now pick all classes and add these to their to caches. for (org.sparx.Element elmt : pack.GetElements()) { String type = elmt.GetType(); if (!type.equals("DataType") && !type.equals("Class") && !type.equals("Interface") && !type.equals("Enumeration")) continue; ClassInfoEA ci = new ClassInfoEA(this, pi, elmt); fClassById.put(ci.id(), ci); // TODO What's happening to identical class names? How is this // supposed to be handled? Open issue.While classifier names // have to be // unique per app schema only, it is a legacy from Rational Rose // that it is expected that classifier names are unique in the // whole // model. The correct solution would be to add namespace // qualifiers. fClassByName.put(ci.name(), ci); } // Add next level packages for further evaluation for (org.sparx.Package pnxt : pack.GetPackages()) { evalp.addLast(new EvalTask(pi, pnxt)); } } StatusBoard.getStatusBoard().statusChanged(STATUS_EADOCUMENT_ESTABLISHCLASSES); /** * Now that all classes are collected, in a second go establish class * derivation hierarchy and all other associations between classes. */ for (ClassInfoEA ci : fClassById.values()) { // Generalization - class derivation hierarchy ci.establishClassDerivationHierarchy(); // Other associations where the class is source or target ci.establishAssociations(); } String checkingConstraints = options.parameter("checkingConstraints"); if (checkingConstraints == null || !checkingConstraints.toLowerCase().trim().equals("disabled")) { StatusBoard.getStatusBoard().statusChanged(STATUS_EADOCUMENT_READCONSTARINTS); // TODO The following may be removed when constraints have been // tested. /** In a third go collect all constraints */ for (ClassInfoEA ci : fClassById.values()) { ci.constraints(); SortedMap<StructuredNumber, PropertyInfo> props = ci.properties(); for (PropertyInfo pi : props.values()) pi.constraints(); } } /** * Loop over all schemas (i.e packages with a target namespace) and * store the schema location, so that it can be added in import * statements */ SortedSet<PackageInfo> schemas = schemas(""); for (Iterator<PackageInfo> i = schemas.iterator(); i.hasNext();) { PackageInfo pi = i.next(); options.addSchemaLocation(pi.targetNamespace(), pi.xsdDocument()); } // ============================== // load diagrams if so requested String loadDiagrams = options.parameter("loadDiagrams"); if (loadDiagrams != null && loadDiagrams.equalsIgnoreCase("true")) { java.io.File tmpDir = options.imageTmpDir(); if (tmpDir.exists()) { // probably content from previous run, delete the content of the directory try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { result.addWarning(null, 34, tmpDir.getAbsolutePath()); } if (!tmpDir.exists()) { try { FileUtils.forceMkdir(tmpDir); } catch (IOException e) { result.addWarning(null, 32, tmpDir.getAbsolutePath()); } } } AtomicInteger imgIdCounter = new AtomicInteger(0); SortedSet<? extends PackageInfo> selectedSchema = this.selectedSchemas(); for (PackageInfo pi : selectedSchema) { if (pi == null) { continue; } // Only process schemas in a namespace and name that matches a // user-selected pattern if (options.skipSchema(null, pi)) continue; saveDiagrams(imgIdCounter, "img", tmpDir, escapeFileName(tmpDir.getName()), pi); } } }