target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testDecomposeVideoAndImage() throws Exception { LivePost livepost = buildLivePost("Love this song!! http: List<LivePost> liveposts = decomposer.decompose(livepost); assertEquals(4, liveposts.size()); assertTrue(liveposts.contains(livepost)); LivePost parent = null; ImagePost imagePost = null; VideoPost videoPost = null; for (LivePost lv : liveposts) { if (lv instanceof VideoPost) { videoPost = (VideoPost) lv; } else if (lv instanceof ImagePost) { imagePost = (ImagePost) lv; } else { parent = lv; } } assertEquals(2, parent.getAllRelatedResource_as().count()); assertEquals("http: assertEquals("http: }
public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; }
LivePostDecomposer { public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; } }
LivePostDecomposer { public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; } LivePostDecomposer(); }
LivePostDecomposer { public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; } LivePostDecomposer(); List<LivePost> decompose(LivePost livepost); }
LivePostDecomposer { public List<LivePost> decompose(LivePost livepost) throws DataMiningException { List<LivePost> liveposts = new ArrayList<LivePost>(); if (!livepost.hasTextualContent()) { throw new DataMiningException("Livepost "+livepost.asResource()+" cannot be decomposed, no textual content is provided."); } else { String text = livepost.getAllTextualContent().next(); Calendar timestamp = livepost.hasTimestamp() ? livepost.getTimestamp() : Calendar.getInstance(); LivePost superPost = dlpoFactory.createLivePost(livepost.asURI()); superPost.getModel().addAll(livepost.getModel().iterator()); try { LivePost subPost = null; for (String link : LinkExtractor.extract(text, true)) { URL url = null; try { url = new URL(link); } catch (MalformedURLException e) { logger.error(link+" is not a valid URL in livepost "+livepost.asResource(), e); continue; } superPost.addRelatedResource(new URIImpl(link)); ResourceModel linkMetadata = urlExtractor.extract(url); String type = linkMetadata.getString(OG.type); if (type == null) { continue; } else if ("audio".equals(type)) { subPost = dlpoFactory.createAudioPost(); } else if ("image".equals(type)) { subPost = dlpoFactory.createImagePost(); } else if ("video".equals(type)) { subPost = dlpoFactory.createVideoPost(); } superPost.addIsComposedOf(subPost.asResource()); subPost.setTimestamp(timestamp); subPost.setTextualContent(text); subPost.setDefiningResource(new URIImpl(link)); subPost.setDefiningResource(new URIImpl(link)); subPost.getModel().addAll(linkMetadata.getModel().iterator()); subPost.getModel().addAll(opengraphExtractor.extract(url).getModel().iterator()); liveposts.add(subPost); } } catch (ExtractionException e) { logger.error("Error occurred while decomposing livepost "+livepost.asResource(), e); } Status status = dlpoFactory.createStatus(); status.setTimestamp(timestamp); status.setTextualContent(text); superPost.addIsComposedOf(status); liveposts.add(status); liveposts.add(superPost); } return liveposts; } LivePostDecomposer(); List<LivePost> decompose(LivePost livepost); }
@Test public void testAddTwoStreams() throws Exception { Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); linkedin.setPrefLabel("LinkedIn"); resourceStore.createOrUpdate(null, linkedin); ResourceStore data = null; Collection<LivePost> messages = new ArrayList<LivePost>(); data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/liveposts-call1.ttl"), Syntax.Turtle); for (Status status : data.find(Status.class).distinct().results()) { messages.add((Status) status.castTo(Status.class)); } streamAccountUpdater.update(linkedin.asURI(), "/liveposts", messages); assertEquals(10, resourceStore.find(Status.class).distinct().results().size()); messages.clear(); data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/liveposts-call2.ttl"), Syntax.Turtle); for (Status status : data.find(Status.class).distinct().results()) { messages.add((Status) status.castTo(Status.class)); } streamAccountUpdater.update(linkedin.asURI(), "/liveposts", messages); assertEquals(13, resourceStore.find(Status.class).distinct().results().size()); }
@Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); }
StreamAccountUpdater extends AccountUpdaterBase implements AccountUpdater<LivePost> { @Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); } }
StreamAccountUpdater extends AccountUpdaterBase implements AccountUpdater<LivePost> { @Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); } StreamAccountUpdater(ResourceStore resourceStore); }
StreamAccountUpdater extends AccountUpdaterBase implements AccountUpdater<LivePost> { @Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); } StreamAccountUpdater(ResourceStore resourceStore); @Override void update(URI accountUri, String path, LivePost livepost); @Override void update(URI accountUri, String path, Collection<LivePost> liveposts); }
StreamAccountUpdater extends AccountUpdaterBase implements AccountUpdater<LivePost> { @Override public void update(URI accountUri, String path, LivePost livepost) throws AccountIntegrationException { Collection<LivePost> liveposts = new ArrayList<LivePost>(1); liveposts.add(livepost); update(accountUri, path, liveposts); } StreamAccountUpdater(ResourceStore resourceStore); @Override void update(URI accountUri, String path, LivePost livepost); @Override void update(URI accountUri, String path, Collection<LivePost> liveposts); }
@Test public void testAddContacts() throws Exception { Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); linkedin.setPrefLabel("LinkedIn"); pimoService.create(linkedin); ResourceStore data = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-persons.ttl"), Syntax.Turtle); Collection<PersonContact> contacts = data.find(PersonContact.class).distinct().results(); updater.update(linkedin.asURI(), "/connections", contacts); PersonGroup accountGroup = resourceStore.find(PersonGroup.class).where(NIE.dataSource).is(linkedin).first(); assertNotNull(accountGroup); List<Agent> members = accountGroup.getAllMembers_as().asList(); assertEquals(2, members.size()); List<URI> uris = new LinkedList<URI>(); for (Thing m : members) uris.add(m.asURI()); Person anna = resourceStore.find(Person.class) .where(PIMO.groundingOccurrence).is(BasicQuery.X) .where(BasicQuery.X, NAO.externalIdentifier).is("9V7WOs5KHr") .first(); assertTrue(uris.contains(anna.asURI())); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), FOAF.knows, anna)); Person norbert = resourceStore.find(Person.class) .where(PIMO.groundingOccurrence).is(BasicQuery.X) .where(BasicQuery.X, NAO.externalIdentifier).is("RYWVyGcfzR") .first(); assertTrue(uris.contains(norbert.asURI())); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), FOAF.knows, norbert)); }
@Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); @Override void update(URI accountUri, String path, PersonContact contact); @Override void update(URI accountUri, String path, Collection<PersonContact> contacts); }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); @Override void update(URI accountUri, String path, PersonContact contact); @Override void update(URI accountUri, String path, Collection<PersonContact> contacts); }
@Test public void testRepeatedUpdate() throws Exception { ResourceStore initialStore = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-connections-initial.ttl"), Syntax.Turtle); ResourceStore updatedStore = createResourceStore( this.getClass().getClassLoader().getResourceAsStream("account/linkedin-connections-updated.ttl"), Syntax.Turtle); Collection<PersonContact> initialContacts = initialStore.find(PersonContact.class).distinct().results(); Collection<PersonContact> updatedContacts = updatedStore.find(PersonContact.class).distinct().results(); Account linkedin = modelFactory.getDAOFactory().createAccount("urn:service:linkedin"); resourceStore.createOrUpdate(pimoService.getPimoUri(), linkedin); updater.update(linkedin.asURI(), "/connections", initialContacts); PersonContact initialContact = resourceStore.find(PersonContact.class).where(NAO.externalIdentifier).is("7N49Odr3Dk").first(); PersonName initialContactName = resourceStore.get(initialContact.getAllPersonName().next().asURI(), PersonName.class); assertEquals("Charlie", initialContactName.getNameGiven()); tripleStore.addStatement(pimoService.getPimoUri(), initialContact, NAO.hasTag, new URIImpl("urn:sometag")); updater.update(linkedin.asURI(), "/connections", updatedContacts); PersonContact updatedContact = resourceStore.find(PersonContact.class).where(NAO.externalIdentifier).is("7N49Odr3Dk").first(); PersonName updatedContactName = resourceStore.get(updatedContact.getAllPersonName().next().asURI(), PersonName.class); assertEquals(initialContact.asURI(), updatedContact.asURI()); assertEquals("Carmelo", updatedContactName.getNameGiven()); assertTrue(tripleStore.containsStatements(pimoService.getPimoUri(), updatedContact, NAO.hasTag, new URIImpl("urn:sometag"))); }
@Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); @Override void update(URI accountUri, String path, PersonContact contact); @Override void update(URI accountUri, String path, Collection<PersonContact> contacts); }
ProfileAccountUpdater extends AccountUpdaterBase implements AccountUpdater<PersonContact> { @Override public void update(URI accountUri, String path, PersonContact contact) throws AccountIntegrationException { logger.info("Updating "+path+" for "+accountUri+" with 1 contact."); URI accountPathGraph = getGraph(accountUri, path); removeResources(accountUri, path); if (path.contains("@me")) { PersonContact profile = (PersonContact) super.match(contact).castTo(PersonContact.class); profile.setPrefLabel(getProfilePrefLabel(profile, accountUri)); try { profile = profileEnricher.enrich(profile); } catch (DataMiningException e) { logger.error("Profile enrichment (fullname, postal address, etc.) failed for profile "+profile.asResource()+": "+e.getMessage(), e); } resourceStore.createOrUpdate(accountPathGraph, profile); if (!tripleStore.containsStatements(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile)) { tripleStore.addStatement(pimoService.getPimoUri(), pimoService.getUserUri(), PIMO.occurrence, profile); } if (!tripleStore.containsStatements(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri)) { tripleStore.addStatement(accountPathGraph, profile.asResource(), NIE.dataSource, accountUri); } } else { throw new RuntimeException("NOT YET IMPLEMENTED!"); } } ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService); ProfileAccountUpdater(ResourceStore resourceStore, PimoService pimoService, ProfileEnricher profileEnricher); @Override void update(URI accountUri, String path, PersonContact contact); @Override void update(URI accountUri, String path, Collection<PersonContact> contacts); }
@Test public void testConfirmCredentials() { authenticationController.confirmCredentials("", ""); }
@POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } }
AuthenticationController { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } } }
AuthenticationController { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } } }
AuthenticationController { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } } void setUserManager(UserManager userManager); void setAccessControlManager(AccessControlManager accessControlManager); @GET @Path("{userName}") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> getUser( @PathParam("userName") String userName); @POST @Path("{userName}")// can be @me - then updating the current user @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> updateUser( @PathParam("said") String said, @PathParam("userName") String userName, Request<AccountEntry> request); @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> deleteAccount(Request<AccountEntry> request, @PathParam("userName") String userName); @GET @Path("/username") String getCurrentUserName(); @GET @Path("/role") String getCurrentRole(); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<AccountEntry> getCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester); }
AuthenticationController { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") public Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester) { User user = userManager.getUserForAccountAndTenant(saidRequester, saidLocal); if (user == null) { return Response.badRequest("Useraccount was null", null); } User enabledUser = userManager.enable((user.getId())); if (enabledUser != null) { return Response.ok(); } else { return Response.badRequest("Useraccount was null", null); } } void setUserManager(UserManager userManager); void setAccessControlManager(AccessControlManager accessControlManager); @GET @Path("{userName}") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> getUser( @PathParam("userName") String userName); @POST @Path("{userName}")// can be @me - then updating the current user @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> updateUser( @PathParam("said") String said, @PathParam("userName") String userName, Request<AccountEntry> request); @DELETE @Path("{userName}") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<AccountEntry> deleteAccount(Request<AccountEntry> request, @PathParam("userName") String userName); @GET @Path("/username") String getCurrentUserName(); @GET @Path("/role") String getCurrentRole(); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<AccountEntry> getCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester); @POST @Produces(MediaType.APPLICATION_JSON) @Path("/credentials/{contact-said}") Response<?> confirmCredentials( @PathParam("said") String saidLocal, @PathParam("contact-said") String saidRequester); }
@Test public void testEmptyPostalAddressExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, ""); postalAddressExtractor.extract(resourceModel); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Galway, Ireland"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Galway", newResourceModel.get(NCO.locality)); assertEquals("Ireland", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction2() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Belfast, Northern Ireland, United Kingdom"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Belfast", newResourceModel.get(NCO.locality)); assertEquals("Northern Ireland", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction3() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Cumbria, England"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Cumbria", newResourceModel.get(NCO.region)); assertEquals("England", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction4() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Unit - 1019 PO Box 7169 Poole BH15 9EL"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("PO Box 7169", newResourceModel.get(NCO.pobox)); assertEquals("BH15 9EL", newResourceModel.get(NCO.postalcode)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction5() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "10b St Marys Road, Barnet, NW11 9UG, LONDON, Great Britain"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("10b St Marys Road", newResourceModel.get(NCO.streetAddress)); assertEquals("NW11 9UG", newResourceModel.get(NCO.postalcode)); assertEquals("LONDON", newResourceModel.get(NCO.locality)); assertEquals("Great Britain", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction6() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("USA", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction7() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); resourceModel.set(NCO.country, "United States"); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("United States", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testPostalAddressExtraction8() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI addr = model.createURI("urn:juan:loc36"); ResourceModel resourceModel = new ResourceModelImpl(addr); resourceModel.set(NAO.prefLabel, "Mississippi, USA"); resourceModel.set(NCO.country, ""); ResourceModel newResourceModel = postalAddressExtractor.extract(resourceModel); assertEquals("Mississippi", newResourceModel.get(NCO.region)); assertEquals("USA", newResourceModel.get(NCO.country)); }
public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
PostalAddressExtractor extends Base { public ResourceModel extract(ResourceModel postalAddress) throws DataMiningException { ResourceModel result = new ResourceModelImpl(postalAddress.getModel(), postalAddress.getIdentifier()); String content = postalAddress.getString(NAO.prefLabel); if ((content == null) || (content.trim().isEmpty())) { logger.info("PostalAddress "+postalAddress.getIdentifier()+" doesn't specify the full postal address as the NAO.prefLabel; " + "skipping postal address extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("PostalAddress"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("LocationStreet"); annotTypesRequired.add("LocationCity"); annotTypesRequired.add("LocationRegion"); annotTypesRequired.add("LocationPostCode"); annotTypesRequired.add("LocationPOBox"); annotTypesRequired.add("LocationCountry"); annotTypesRequired.add("LocationProvince"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityValue = null; String entityType = annot.getType(); if ((entityType.equals("LocationCountry")) && ((!(result.has(NCO.country))) || ((result.get(NCO.country)).equals("")))) { entityValue = annot.getFeatures().get("country").toString(); result.set(NCO.country, entityValue); } else if ((entityType.equals("LocationProvince")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("province").toString(); result.set(NCO.region, entityValue); } else if ((entityType.equals("LocationCity")) && ((!(result.has(NCO.locality))) || ((result.get(NCO.locality)).equals("")))) { entityValue = annot.getFeatures().get("city").toString(); result.set(NCO.locality, entityValue); } else if ((entityType.equals("LocationStreet")) && ((!(result.has(NCO.streetAddress))) || ((result.get(NCO.streetAddress)).equals("")))) { entityValue = annot.getFeatures().get("street").toString(); result.set(NCO.streetAddress, entityValue); } else if ((entityType.equals("LocationPostCode")) && ((!(result.has(NCO.postalcode))) || ((result.get(NCO.postalcode)).equals("")))) { entityValue = annot.getFeatures().get("postcode").toString(); result.set(NCO.postalcode, entityValue); } else if ((entityType.equals("LocationPOBox")) && ((!(result.has(NCO.pobox))) || ((result.get(NCO.pobox)).equals("")))) { entityValue = annot.getFeatures().get("pobox").toString(); result.set(NCO.pobox, entityValue); } else if ((entityType.equals("LocationRegion")) && ((!(result.has(NCO.region))) || ((result.get(NCO.region)).equals("")))) { entityValue = annot.getFeatures().get("region").toString(); result.set(NCO.region, entityValue); } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } return result; } PostalAddressExtractor(); ResourceModel extract(ResourceModel postalAddress); }
@Test public void testEmptyFullnameExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, ""); fullnameExtractor.extract(resourceModel); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Ignore @Test public void testSaveEvaluationOK(){ Request<Evaluation> request = buildSaveEvaluationRequest(); Response<Evaluation> response = controller.saveEvaluation(said, request); assertNotNull(response); Evaluation ev = response.getMessage().getData().getEntries().iterator().next(); assertNotNull(ev); assertEquals(ev.getTenantId(),"hashedTenant"); assertEquals(ev.getCreated(),12345678); assertEquals(ev.getClientId(),"0.1.1"); assertEquals(ev.getAction(),"add people to group"); assertEquals(ev.getCurrPlace(),"hashedPlace"); assertEquals(ev.getCurrSituationId(),"hashedSituation"); assertEquals(ev.getType(),"evaluation"); assertEquals(ev.getGuid(),"dumbGUID"); }
@POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } }
PSEvaluationController { @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } } }
PSEvaluationController { @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } } }
PSEvaluationController { @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } } @Autowired void setEvaluationManager(EvaluationManager em); @Autowired void setUserManager(UserManager userManager); @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request); }
PSEvaluationController { @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") public Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request) { try { RequestValidator.validateRequest(request); Data<Evaluation> data = request.getMessage().getData(); Evaluation ev = (Evaluation) data.getEntries().iterator().next(); User user = userManager.getCurrentUser(); boolean saved = false; if (userManager.validateUserCanLogEvaluationData(user)){ if (evaluationManager.saveEvaluation(ev, said)){ return Response.ok(data); }else{ return Response.serverError("Could not save evaluation due to invalid data. Check server logs", null); } } return Response.serverError("Evaluation not saved, evaluation omitted for user.", null); } catch (Exception e) { return Response.serverError(e.getMessage(), e); } } @Autowired void setEvaluationManager(EvaluationManager em); @Autowired void setUserManager(UserManager userManager); @POST @Path("/@me") @Consumes(MediaType.APPLICATION_JSON + ";charset=UTF-8") @Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8") Response<Evaluation> saveEvaluation(@PathParam("said") String said, Request<Evaluation> request); }
@Test public void testFullnameExtraction() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Dr. John Doe Jr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Dr.", newResourceModel.get(NCO.nameHonorificPrefix)); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Doe", newResourceModel.get(NCO.nameFamily)); assertEquals("Jr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction2() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Doe-Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Doe-Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction3() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction4() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell-Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell-Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction5() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John O'Connell Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("O'Connell Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction6() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Prof. John Smith"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Prof.", newResourceModel.get(NCO.nameHonorificPrefix)); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction7() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Sr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction8() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); resourceModel.set(NCO.nameHonorificSuffix, "Jr."); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Jr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction9() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "John Smith Sr."); resourceModel.set(NCO.nameGiven, ""); resourceModel.set(NCO.nameHonorificSuffix, ""); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("John", newResourceModel.get(NCO.nameGiven)); assertEquals("Smith", newResourceModel.get(NCO.nameFamily)); assertEquals("Sr.", newResourceModel.get(NCO.nameHonorificSuffix)); assertEquals("male", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction10() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void shouldDeserializeJSONLD() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@graph`:[{`@id`:`urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455`,`@type`:[`http: PersonContact resource = JSONLDUtils.deserialize(json, PersonContact.class); Model metadata = resource.getModel(); URI profile = new URIImpl("urn:uuid:d030b056-cddd-4a8b-9828-a54dbca6495e"); URI email = new URIImpl("urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455"); assertEquals(profile, profile.asURI()); assertTrue("Must contain a nco:PersonContact resource", metadata.contains(profile, RDF.type, NCO.PersonContact)); assertEquals("Test", ModelUtils.findObject(metadata, profile, NAO.prefLabel).asLiteral().getValue()); assertTrue("Must contain a nco:EmailAddress resource", metadata.contains(email, RDF.type, NCO.EmailAddress)); assertEquals("[email protected]", ModelUtils.findObject(metadata, email, NCO.emailAddress).asLiteral().getValue()); }
public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
@Test public void testFullnameExtraction11() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael Rivera"); resourceModel.set(NCO.nameGiven, ""); resourceModel.set(NCO.nameFamily, ""); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); assertEquals("Rivera", newResourceModel.get(NCO.nameFamily)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction12() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Ismael 'Joe' Rivera"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Ismael", newResourceModel.get(NCO.nameGiven)); assertEquals("'Joe'", newResourceModel.get(NCO.nameAdditional)); assertEquals("Rivera", newResourceModel.get(NCO.nameFamily)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testFullnameExtraction13() throws ModelRuntimeException, IOException, DataMiningException { Model model = RDF2Go.getModelFactory().createModel(); model.open(); URI name = model.createURI("urn:juan:personName4"); ResourceModel resourceModel = new ResourceModelImpl(name); resourceModel.set(NCO.fullname, "Jane O' Donnell"); ResourceModel newResourceModel = fullnameExtractor.extract(resourceModel); assertEquals("Jane", newResourceModel.get(NCO.nameGiven)); assertEquals("O' Donnell", newResourceModel.get(NCO.nameFamily)); assertEquals("female", newResourceModel.get(NCO.gender)); }
public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
FullnameExtractor extends Base { public ResourceModel extract(ResourceModel personName) throws DataMiningException { ResourceModel result = new ResourceModelImpl(personName.getModel(), personName.getIdentifier()); String content = personName.getString(NCO.fullname); if ((content == null) || (content.trim().isEmpty())) { logger.info("PersonName "+personName.getIdentifier()+" doesn't specify the contact's fullname as the NCO.fullname; " + "skipping fullname extraction..."); return result; } Document doc = null; try { doc = Factory.newDocument(content); synchronized(application) { Corpus corpus = Factory.newCorpus("Fullname"+System.currentTimeMillis()); corpus.add(doc); application.setCorpus(corpus); application.execute(); AnnotationSet defaultAnnotSet = doc.getAnnotations(); Set<String> annotTypesRequired = new HashSet<String>(); annotTypesRequired.add("PersonEntities"); AnnotationSet entityAnnSet = defaultAnnotSet.get(new HashSet<String>(annotTypesRequired)); List<Annotation> entityAnnots = gate.Utils.inDocumentOrder(entityAnnSet); for (Annotation annot : entityAnnots) { String entityType = annot.getType(); String firstname = null; String surname = null; String prefix = null; String suffix = null; String gender = null; if (entityType.equals("PersonEntities")) { if ((!(annot.getFeatures().get("prefix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificPrefix))) || ((result.get(NCO.nameHonorificPrefix)).equals("")))) { prefix = annot.getFeatures().get("prefix").toString(); result.set(NCO.nameHonorificPrefix, prefix); } if ((!(annot.getFeatures().get("firstname").toString().isEmpty())) && ((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals("")))) { firstname = annot.getFeatures().get("firstname").toString(); result.set(NCO.nameGiven, firstname); } if ((!(annot.getFeatures().get("surname").toString().isEmpty())) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { surname = annot.getFeatures().get("surname").toString(); result.set(NCO.nameFamily, surname); } if ((!(annot.getFeatures().get("suffix").toString().isEmpty())) && ((!(result.has(NCO.nameHonorificSuffix))) || ((result.get(NCO.nameHonorificSuffix)).equals("")))) { suffix = annot.getFeatures().get("suffix").toString(); result.set(NCO.nameHonorificSuffix, suffix); } if ((!(annot.getFeatures().get("gender").toString().isEmpty())) && ((!(result.has(NCO.gender))) || ((result.get(NCO.gender)).equals("")))) { gender = annot.getFeatures().get("gender").toString(); result.set(NCO.gender, gender); } } } corpus.cleanup(); corpus.clear(); } } catch (ResourceInstantiationException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } catch (ExecutionException e) { throw new DataMiningException("Failed to extract named entities from '"+content+"'", e); } finally { if (doc != null) { Factory.deleteResource(doc); } } if (((!(result.has(NCO.nameGiven))) || ((result.get(NCO.nameGiven)).equals(""))) && ((!(result.has(NCO.nameAdditional))) || ((result.get(NCO.nameAdditional)).equals(""))) && ((!(result.has(NCO.nameFamily))) || ((result.get(NCO.nameFamily)).equals("")))) { String[] fullname = content.split(" "); if (fullname.length == 1) { result.set(NCO.nameGiven, fullname[0]); } else if (fullname.length == 2) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameFamily, fullname[1]); } else if (fullname.length == 3) { result.set(NCO.nameGiven, fullname[0]); result.set(NCO.nameAdditional, fullname[1]); result.set(NCO.nameFamily, fullname[2]); } } return result; } FullnameExtractor(); ResourceModel extract(ResourceModel personName); }
@Test public void testUpdateCurrentPlace() { try { RawContextNotification notification = createNotification(user1, currentPlace); SpaTem spatem = liveContextService.get(SpaTem.class); ClosableIterator<Place> places = spatem.getAllCurrentPlace(); rawContextUpdater.contextChanged(notification); spatem = liveContextService.get(SpaTem.class); places = spatem.getAllCurrentPlace(); assertTrue(places.hasNext()); } catch (Exception e) { fail(e.getMessage()); } }
@Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } }
LocationContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
LocationContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
LocationContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void setLocationManager(LocationManager locationManager); void setPlaceProcessor(PlaceProcessor placeProcessor); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
LocationContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Current Place Raw Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void setLocationManager(LocationManager locationManager); void setPlaceProcessor(PlaceProcessor placeProcessor); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
@Test public void testHour() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(AFTERNOON)); }
protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
@Test public void testDayOfWeek() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(FRIDAY)); }
protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
@Test public void testWeekend() throws Exception { assertFalse(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(WEEKEND)); assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY20AT0839).contains(WEEKEND)); }
protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
@Test public void testFindTimePeriodsByWeek() throws Exception { assertTrue(timePeriodUpdater.findTimePeriods(this.resourceStore, MAY18AT1339).contains(WEEK20)); }
protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
TimePeriodUpdater implements LiveContextUpdater { protected List<URI> findTimePeriods(ResourceStore resourceStore, Calendar when) { int hour = when.get(Calendar.HOUR_OF_DAY); int dayOfWeek = getDayOfWeekFromMonday(when); int dayOfMonth = when.get(Calendar.DAY_OF_MONTH); int weekOfYear = when.get(Calendar.WEEK_OF_YEAR); int month = when.get(Calendar.MONTH) + 1; int year = when.get(Calendar.YEAR); String query = StringUtils.strjoinNL( "PREFIX dpo: <http: "SELECT DISTINCT ?instance WHERE {", " {", " ?instance a dpo:TimePeriod ;", " dpo:minHour ?minHour ;", " dpo:maxHour ?maxHour .", " FILTER(?minHour <= "+hour+") .", " FILTER(?maxHour >= "+hour+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfWeek ?minDayOfWeek ;", " dpo:maxDayOfWeek ?maxDayOfWeek .", " FILTER(?minDayOfWeek <= "+dayOfWeek+") .", " FILTER(?maxDayOfWeek >= "+dayOfWeek+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minDayOfMonth ?minDayOfMonth ;", " dpo:maxDayOfMonth ?maxDayOfMonth .", " FILTER(?minDayOfMonth <= "+dayOfMonth+") .", " FILTER(?maxDayOfMonth >= "+dayOfMonth+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minWeek ?minWeek ;", " dpo:maxWeek ?maxWeek .", " FILTER(?minWeek <= "+weekOfYear+") .", " FILTER(?maxWeek >= "+weekOfYear+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minMonth ?minMonth ;", " dpo:maxMonth ?maxMonth .", " FILTER(?minMonth <= "+month+") .", " FILTER(?maxMonth >= "+month+") .", " } UNION {", " ?instance a dpo:TimePeriod ;", " dpo:minYear ?minYear ;", " dpo:maxYear ?maxYear .", " FILTER(?minYear <= "+year+") .", " FILTER(?maxYear >= "+year+") .", " }", "}"); ClosableIterator<QueryRow> rows = resourceStore.sparqlSelect(query).iterator(); List<URI> results = new ArrayList<URI>(); while (rows.hasNext()) { results.add(rows.next().getValue("instance").asURI()); } return results; } void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); @Override void update(); }
@Test public void testUpdateActivity() { try { List<Node> activities = new ArrayList<Node>(); RawContextNotification notification = createNotification(user1,currentActivity); rawContextUpdater.contextChanged(notification); State state = liveContextService.get(State.class); ClosableIterator<Statement> currentIt = state.getModel().findStatements(state, DCON.currentActivity, Variable.ANY); while (currentIt.hasNext()) { Node object = currentIt.next().getObject(); if (object instanceof URI) { activities.add(object); } } currentIt.close(); assertTrue(activities.size() == 1); } catch (Exception e) { fail(e.getMessage()); } }
@Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } }
ActivityContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
ActivityContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
ActivityContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
ActivityContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw Activity Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
@Test public void testActivityNoRecentData() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place1") }; String activity = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((activity == null) || (!activity.equalsIgnoreCase(""))); }
protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
@Test public void shouldDeserializedJSONLDWithContext() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@context`:{`nao`:`http: PersonContact resource = JSONLDUtils.deserialize(json, PersonContact.class); Model metadata = resource.getModel(); URI profile = new URIImpl("urn:uuid:6c329b90-737d-46cd-ae2f-eb86cddea172"); URI email = new URIImpl("urn:uuid:4182dcd4-a510-4b0c-8145-271a3dcfe455"); assertEquals(profile, profile.asURI()); assertTrue("Must contain a nco:PersonContact resource", metadata.contains(profile, RDF.type, NCO.PersonContact)); assertEquals("Test Test", ModelUtils.findObject(metadata, profile, NAO.prefLabel).asLiteral().getValue()); assertTrue("Must contain a nco:EmailAddress resource", metadata.contains(email, RDF.type, NCO.EmailAddress)); assertEquals("[email protected]", ModelUtils.findObject(metadata, email, NCO.emailAddress).asLiteral().getValue()); }
public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
@Test public void testActivityDifferentPlaces() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((180) * 1000), 600, "place2"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE - 20) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place1") }; String situation = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((situation == null) || (!situation.equalsIgnoreCase(""))); }
protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
@Test public void testActivityOK() { IContextElement[] addrs = { ContextHelper.createCivilAddress(System.currentTimeMillis() - ((15) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((180) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE - 20) * 1000), 600, "place1"), ContextHelper.createCivilAddress(System.currentTimeMillis() - ((Defaults.ACTIVITY_PERIOD + Defaults.ACTIVITY_TOLERANCE + 10) * 1000), 600, "place2") }; String situation = activityDetector.getActivity(Constants.ENTITY_ME,addrs); assertFalse((situation == null) || (!situation.equalsIgnoreCase("@place1"))); }
protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
ActivityDetector implements IContextProvider { protected String getActivity(IEntity entity, IContextElement[] addrs) { if (addrs.length != 0) { int index = Utility.getFirstSignificativeItem(addrs,Defaults.ACTIVITY_PERIOD,Defaults.ACTIVITY_TOLERANCE); if (index == -1) { logger.debug("Received civil addresses are too recent to infer activity"); return ""; } else { logger.debug("Significative civil address for activity:"); for (int i=0; i<addrs.length; i++) { String prefix = ""; if (i <= index) prefix = "*" + i; else prefix = "" + i; logger.debug(prefix + " - " + (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue() + " " + (String)addrs[i].getMetadata().getMetadatumValue(Factory.createScope(Constants.SCOPE_METADATA_TIMESTAMP)).getValue()); } } String placeName = (String)addrs[0].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); for (int i=1; i<=index; i++) { String currentPlace = (String)addrs[i].getContextData().getContextValue(Factory.createScope(Constants.SCOPE_LOCATION_CIVILADDRESS_PLACE_NAME)).getValue().getValue(); if (!currentPlace.equalsIgnoreCase(placeName)) return ""; } return "@" + placeName; } return ""; } void setContextProcessor(IContextProcessor contextProcessor); void setServiceGateway(ServiceGateway serviceGateway); void setPolicyManager(PolicyManager policyManager); void setProviderManager(IProviderManager providerManager); void setAccountManager(AccountManager accountManager); void setPersonManager(PersonManager personManager); void setPersonGroupManager(PersonGroupManager personGroupManager); void setTenantManager(TenantManager tenantManager); void setUserManager(UserManager userManager); void init(); @Override IContextDataset getContext(Tenant t, IEntity entity, IScope scope, IContextDataset inputContextDataset); }
@Test public void testUpdateWifi() { try { Tenant t1 = entityFactory.buildTenant(); t1.setName(user1.getEntityIDAsString()); t1.setId(new Long(2)); RawContextNotification notification = createNotification(t1,user1,wifi); rawContextUpdater.contextChanged(notification); Connectivity conn = liveContextService.get(Connectivity.class); assertTrue(conn.getAllConnection().hasNext()); } catch (Exception e) { fail(e.getMessage()); } }
@Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } }
WiFiContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
WiFiContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } }
WiFiContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
WiFiContextUpdater implements LiveContextUpdater, IContextListener { @Override public void contextChanged(RawContextNotification notification) throws Exception { String name = notification.getName(); logger.debug("Raw WiFi Context notification received: " + name); StringTokenizer tok = new StringTokenizer(name,","); IEntity entity = Factory.createEntity(tok.nextToken()); IScope scope = Factory.createScope(tok.nextToken()); Tenant t = new Tenant(); t.setId(notification.getTenant()); IContextDataset dataset; try { dataset = this.contextProcessor.getContext(t,entity, scope); if (!dataset.equals(IContextDataset.EMPTY_CONTEXT_DATASET)) { IContextElement[] ces = dataset.getContextElements(scope); if (ces != null && ces.length == 1) { this.rawContextQueue.add(ces[0]); update(); } } } catch (ContextException e) { logger.error(e.toString()); } } void setContextProcessor(IContextProcessor contextProcessor); void setConnectionProvider(ConnectionProvider connectionProvider); void setTenantManager(TenantManager tenantManager); void init(); @Override void contextChanged(RawContextNotification notification); @Override void update(); }
@Test public void testShareWithAccount() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); Account accountSender = createAccount("[email protected]", pimoService.getUser()); accessSpace.setSharedThrough(accountSender); Account accountR1B = createAccount("[email protected]", personR1); accessSpace.addIncludes(accountR1B); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); Set<URI> recipients = new HashSet<URI>(); recipients.add(accountR1B.asURI()); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1B.toString(), notification.getTarget()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareWithPerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); Set<URI> recipients = new HashSet<URI>(); recipients.add(accountR1.asURI()); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareWithGroup() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(2, notifierManager.external.size()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareWithGroupExcludeAccount() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); accessSpace.addExcludes(accountR2); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareWithGroupExcludePerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1, personR2); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); accessSpace.addExcludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR2.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareWithGroupAndAddPerson() throws Exception { LivePost livePost = createLivePost("Hello sharing!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); PersonGroup group = createPersonGroup("Friends", personR1); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(group); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); DimeExternalNotification notification = null; Event event = null; event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, preference); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(Type.LIVEPOST.toString(), notification.getItemType()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); tripleStore.addStatement(pimoService.getPimoUri(), livePost, NSO.sharedWith, personR1); group.addMember(personR2); tripleStore.addStatement(pimoService.getPimoUri(), group, PIMO.hasMember, personR2); notifierManager.external.clear(); event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, group); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); notification = notifierManager.external.get(0); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(Type.LIVEPOST.toString(), notification.getItemType()); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR2.toString(), notification.getTarget()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test public void testShareAndUpdateLivePost() throws Exception { LivePost livePost = createLivePost("Text updated!", pimoService.getUser()); PrivacyPreference preference = modelFactory.getPPOFactory().createPrivacyPreference(); preference.setLabel(PrivacyPreferenceType.LIVEPOST.name()); preference.setCreator(pimoService.getUser()); preference.setAppliesToResource(livePost); AccessSpace accessSpace = modelFactory.getNSOFactory().createAccessSpace(); accessSpace.setSharedThrough(accountSender); accessSpace.addIncludes(personR1); preference.addAccessSpace(accessSpace); preference.getModel().addAll(accessSpace.getModel().iterator()); tripleStore.addAll(pimoService.getPimoUri(), preference.getModel().iterator()); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, livePost); notifier.onReceive(event); assertEquals(1, notifierManager.external.size()); DimeExternalNotification notification = notifierManager.external.get(0); assertEquals(accountSender.toString(), notification.getSender()); assertEquals(accountR1.toString(), notification.getTarget()); assertEquals(livePost.toString(), notification.getItemID()); assertEquals(DimeExternalNotification.OP_SHARE, notification.getOperation()); assertEquals(Type.get(livePost).toString(), notification.getItemType()); }
@Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
SharingNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { if (notifierManager == null) { logger.warn("NotifierManager bean not set for SharingNotifier: " + "notifications for sharing actions won't be sent!"); return; } Tenant tenant = TenantHelper.getTenant(event.getTenantId()); Connection connection = null; ResourceStore resourceStore = null; PimoService pimoService = null; PrivacyPreferenceService ppoService = null; try { org.ontoware.rdfreactor.schema.rdfs.Resource resource = event.getData(); if (resource == null) { return; } String[] allowedActions = new String[] { Event.ACTION_RESOURCE_ADD, Event.ACTION_RESOURCE_MODIFY, Event.ACTION_RESOURCE_DELETE }; if (!Arrays.contains(allowedActions, event.getAction())) { return; } URI[] allowedTypes = new URI[] { PPO.PrivacyPreference, DLPO.LivePost, NIE.DataObject, PIMO.PersonGroup }; boolean typeAllowed = false; for (URI allowedType : allowedTypes) { if (event.is(allowedType)) { typeAllowed = true; break; } } if (!typeAllowed) { return; } connection = connectionProvider.getConnection(event.getTenant()); resourceStore = connection.getResourceStore(); pimoService = connection.getPimoService(); ppoService = connection.getPrivacyPreferenceService(); if (event.is(PPO.PrivacyPreference) && (Event.ACTION_RESOURCE_ADD.equals(event.getAction()) || Event.ACTION_RESOURCE_MODIFY.equals(event.getAction()))) { PrivacyPreference preference = ppoService.get(resource.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, true, tenant); } else if (event.is(PPO.PrivacyPreference) && Event.ACTION_RESOURCE_DELETE.equals(event.getAction())) { } else if (event.is(DLPO.LivePost) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { LivePost livePost = resourceStore.get(resource.asURI(), LivePost.class); PrivacyPreference preference = ppoService.getForLivePost(livePost); if (preference != null) { sendNotifications(connection, preference, livePost, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(NIE.DataObject) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { try { DataObject dataObject = resourceStore.get(resource.asURI(), DataObject.class); PrivacyPreference preference = ppoService.getForDataObject(dataObject); if (preference != null) { sendNotifications(connection, preference, dataObject, true, tenant); } } catch (NotFoundException e) { logger.error("A 'resource modified' event was received for " + resource.asURI() + " (livepost), but it could not be found in the RDF store", e); } } else if (event.is(PIMO.PersonGroup) && Event.ACTION_RESOURCE_MODIFY.equals(event.getAction())) { Collection<Resource> ppUris = resourceStore.find(PrivacyPreference.class) .distinct() .where(PPO.hasAccessSpace).is(Query.X) .where(Query.X, NSO.includes).is(resource.asURI()) .ids(); for (Resource ppUri : ppUris) { PrivacyPreference preference = ppoService.get(ppUri.asURI()); org.ontoware.rdfreactor.schema.rdfs.Resource sharedItem = null; try { sharedItem = getSharedItem(preference, ppoService, pimoService); } catch (NotFoundException e) { logger.error("Privacy preference " + preference + " could not be shared.", e); return; } sendNotifications(connection, preference, sharedItem, false, tenant); } } } catch (RepositoryException e) { logger.error("Cannot connect with the RDF repository '" + Long.parseLong(event.getTenant()) + "': " + e, e); return; } } SharingNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); void setConnectionProvider(ConnectionProvider connectionProvider); void setServiceGateway(ServiceGateway serviceGateway); @Override void onReceive(Event event); }
@Test(expected=IllegalArgumentException.class) public void shouldRaiseErrorTwoObjectsSameType() throws JsonParseException, JsonMappingException, JSONLDProcessingError { String json = "{`@context`:{`nao`:`http: JSONLDUtils.deserialize(json, PersonContact.class); }
public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
JSONLDUtils { public static <T extends Resource> T deserialize(Object object, Class<T> returnType) throws JsonParseException, JsonMappingException, JSONLDProcessingError { RDF2GoTripleCallback callback = new RDF2GoTripleCallback(); ModelSet modelSet = toRDF(object, callback); URI subject = null; ClosableIterator<Statement> statements = modelSet.findStatements(Variable.ANY, Variable.ANY, RDF.type, Variable.ANY); while (statements.hasNext()) { Statement statement = statements.next(); URI type = statement.getObject().asURI(); if (returnType.equals(guessClass(type))) { if (subject == null) { subject = statement.getSubject().asURI(); } else if (!subject.equals(statement.getSubject())) { throw new IllegalArgumentException("The following JSON contains more than one resource of type '" + returnType.getName() + "', please consider calling instead deserializeCollection(Object):\n" + JSONUtils.toString(object)); } } } statements.close(); if (subject == null) { throw new IllegalArgumentException("The following JSON does not contain any resource of type '" + returnType.getName() + "':\n" + JSONUtils.toString(object)); } Model resourceModel = RDF2Go.getModelFactory().createModel().open(); resourceModel.addAll(modelSet.iterator()); Resource resource = new Resource(resourceModel, subject, false); modelSet.close(); return (T) resource.castTo(returnType); } static T deserialize(Object object, Class<T> returnType); static T deserialize(String jsonObject, Class<T> returnType); @Deprecated static List<? extends Resource> deserializeCollection(List<Object> collection); @Deprecated static List<? extends Resource> deserializeCollection(String jsonArray); static Object serialize(T resource); static Object serialize(Map<String, String> prefixes, T resource); static String serializeAsString(T resource); static String serializeAsString(Map<String, String> prefixes, T resource); @Deprecated static List<Object> serializeCollection(T... collection); @Deprecated static List<Object> serializeCollection(Map<String, String> prefixes, T... collection); }
@Test public void testCreatePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_ADD, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.asURI().toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_CREATE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
@Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
@Test public void testUpdatePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_MODIFY, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.asURI().toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_UPDATE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
@Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
@Test public void testRemovePersonGroup() { PersonGroup group = modelFactory.getPIMOFactory().createPersonGroup(); group.setCreator(new URIImpl("urn:test")); Event event = new Event(connection.getName(), Event.ACTION_RESOURCE_DELETE, group); notifier.onReceive(event); assertEquals(1, notifierManager.internal.size()); DimeInternalNotification notification = notifierManager.internal.get(0); assertEquals(group.toString(), notification.getItemID()); assertEquals(DimeInternalNotification.OP_REMOVE, notification.getOperation()); assertEquals(Type.get(group).getLabel(), notification.getItemType()); }
@Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
CRUDNotifier implements BroadcastReceiver { @Override public void onReceive(Event event) { final String action = event.getAction(); if (!ArrayUtils.contains(ACTIONS, action)) { return; } final String itemId = event.getIdentifier().toString(); final Resource resource = event.getData(); if (NOTIFY_ACTIONS.containsKey(action)) { if (resource == null) { logger.debug("Impossible to find type of resource (no metadata provided in the event), no notification will be sent [item="+itemId+", action="+action+"]"); } else { final Type itemType = Type.get(resource); final ProfileAttributeType itemTypeProfileAttribute = ProfileAttributeType.get(resource); if (itemType == null && itemTypeProfileAttribute == null) { logger.debug("Type is undefined, no notification will be sent [item="+resource+", action="+action+"]"); return; } final String type = (itemTypeProfileAttribute == null) ? itemType.toString() : "profileattribute"; String creatorId = null; Node creator = ModelUtils.findObject(resource.getModel(), resource, NAO.creator); if (creator != null) { creatorId = creator.toString(); } final Long tenant = Long.parseLong(event.getTenant()); final String operation = NOTIFY_ACTIONS.get(action); if(operation.equals(DimeInternalNotification.OP_CREATE) || operation.equals(DimeInternalNotification.OP_REMOVE )) try { Node rdfType = ModelUtils.findObject(resource.getModel(), resource, RDF.type); if (rdfType != null && !rdfType.asURI().equals(PPO.PrivacyPreference)) logEventManager.setLog(operation, type,Tenant.find(tenant)); else if(type.equals("profilecard")) logEventManager.setLog(operation, type,Tenant.find(tenant)); } catch (EventLoggerException e) { logger.error("A sharing process could not be logged",e); } final SystemNotification notification = new SystemNotification(tenant, operation, itemId, type, creatorId); try { logger.debug("Pushing internal notification: "+notification.toString()); notifierManager.pushInternalNotification(notification); } catch (NotifierException e) { logger.error("Error while pushing notification ["+notification+"].", e); } } } } CRUDNotifier(); @Autowired void setLogEventManager(LogEventManager logEventManager); void setNotifierManager(NotifierManager notifierManager); @Override void onReceive(Event event); }
@Test public void testGetAdapterName() { AMETICDummyAdapter adapter; try { adapter = createAdapter(); assert (adapter.getAdapterName().equals("AMETICDummyAdapter")); } catch (ServiceNotAvailableException e) { e.printStackTrace(); fail ("Service not available: "+e.getMessage()); } }
public String getAdapterName() { return AMETICDummyAdapter.adapterName; }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { public String getAdapterName() { return AMETICDummyAdapter.adapterName; } }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { public String getAdapterName() { return AMETICDummyAdapter.adapterName; } AMETICDummyAdapter(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { public String getAdapterName() { return AMETICDummyAdapter.adapterName; } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { public String getAdapterName() { return AMETICDummyAdapter.adapterName; } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); final static String adapterName; }
@Test public void testGetRaw() throws Exception { AMETICDummyAdapter adapter = createAdapter(); ServiceResponse[] attendees = adapter.getRaw("/event/@me/173/@all"); assertTrue (attendees[0].getResponse().length() > 0); ServiceResponse[] eventDetails = adapter.getRaw("/event/@me/173"); assertTrue (eventDetails[0].getResponse().length() > 0); ServiceResponse[] allEvents = adapter.getRaw("/event/@all"); assertTrue (allEvents[0].getResponse().length() > 0); }
@Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); final static String adapterName; }
@Test public void testRegister() throws Exception { AMETICDummyAdapter adapter = createAdapter(); adapter.register("ameticadmin", "ameticpass"); ServiceResponse[] attendees = adapter.getRaw("/event/@me/173/@all"); assertTrue (attendees[0].getResponse().length() > 0); }
@Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); }
AMETICDummyAdapter extends BasicAuthServiceAdapter implements ExternalServiceAdapter { @Override public ServiceResponse[] getRaw(String attribute) throws AttributeNotSupportedException, ServiceNotAvailableException, ServiceException { if (!this.isConnected()) { throw new ServiceNotAvailableException(); } AttributeMap attributeMap = new AttributeMap(); String genericAttribute = attributeMap.getAttribute(attribute); Map<String, String> ids = attributeMap.extractIds(genericAttribute, attribute); if (genericAttribute.equals(AttributeMap.EVENT_ATTENDEES)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_DETAILS)) { String url = "/ameticevents/" + ids.get(AttributeMap.EVENT_ID) + "/info"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } else if (genericAttribute.equals(AttributeMap.EVENT_ALL)) { String url = "/ameticevents/@all"; ServiceResponse[] r = new ServiceResponse[1]; r[0] = new ServiceResponse(ServiceResponse.XML, attribute, url, this.proxy.get(url)); return r; } throw new AttributeNotSupportedException(attribute, this); } AMETICDummyAdapter(); String getAdapterName(); @Override void _set(String attribute, Object value); @Override void _delete(String attribute); @Override ServiceResponse[] getRaw(String attribute); @Override Boolean isConnected(); final static String adapterName; }
@Test public void testGetDefinitionSetId() { assertThat(domainValidator.getDefinitionSetId()).isEqualTo(DMNDefinitionSet.class.getName()); }
@Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); }
DMNDomainValidatorImpl implements DMNDomainValidator { @Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); } }
DMNDomainValidatorImpl implements DMNDomainValidator { @Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); } @Inject DMNDomainValidatorImpl(final DMNMarshallerStandalone dmnMarshaller, final DMNDiagramUtils dmnDiagramUtils, final DMNMarshallerImportsHelperStandalone importsHelper, final DMNIOHelper dmnIOHelper); }
DMNDomainValidatorImpl implements DMNDomainValidator { @Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); } @Inject DMNDomainValidatorImpl(final DMNMarshallerStandalone dmnMarshaller, final DMNDiagramUtils dmnDiagramUtils, final DMNMarshallerImportsHelperStandalone importsHelper, final DMNIOHelper dmnIOHelper); @PostConstruct void setupValidator(); @Override String getDefinitionSetId(); @Override @SuppressWarnings("unchecked") void validate(final Diagram diagram, final Consumer<Collection<DomainViolation>> resultConsumer); @Override Collection<DomainViolation> validate(final Diagram diagram, final String diagramXml); }
DMNDomainValidatorImpl implements DMNDomainValidator { @Override public String getDefinitionSetId() { return BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class); } @Inject DMNDomainValidatorImpl(final DMNMarshallerStandalone dmnMarshaller, final DMNDiagramUtils dmnDiagramUtils, final DMNMarshallerImportsHelperStandalone importsHelper, final DMNIOHelper dmnIOHelper); @PostConstruct void setupValidator(); @Override String getDefinitionSetId(); @Override @SuppressWarnings("unchecked") void validate(final Diagram diagram, final Consumer<Collection<DomainViolation>> resultConsumer); @Override Collection<DomainViolation> validate(final Diagram diagram, final String diagramXml); }
@Test public void testRenderCenteredEmptyTextWithPlaceHolder() throws Exception { final BaseGridCell<String> cell = new BaseGridCell<>(new BaseGridCellValue<>(null, PLACE_HOLDER)); RendererUtils.getCenteredCellText(cellContext, cell); assertCenteredRenderingPlaceholder(placeHolderText); }
public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; }
RendererUtils { public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; } }
RendererUtils { public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; } }
RendererUtils { public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); final Group g = GWT.create(Group.class); String value = gridCell.getValue().getValue(); final Text t; if (!StringUtils.isEmpty(value)) { t = theme.getBodyText(); } else { value = gridCell.getValue().getPlaceHolder(); t = theme.getPlaceholderText(); } t.setText(value); t.setListening(false); t.setX(context.getCellWidth() / 2); t.setY(context.getCellHeight() / 2); g.add(t); return g; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderExpressionCellText() throws Exception { final BaseGridCell<String> cell = new BaseGridCell<>(new BaseGridCellValue<>(VALUE)); RendererUtils.getExpressionCellText(cellContext, cell); assertExpressionRendering(); }
public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); }
RendererUtils { public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); } }
RendererUtils { public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); } }
RendererUtils { public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, gridCell.getValue().getValue()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderExpressionHeaderText() throws Exception { when(headerMetaData.getTitle()).thenReturn(VALUE); RendererUtils.getExpressionHeaderText(headerMetaData, headerContext); assertExpressionRendering(); }
public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); }
RendererUtils { public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); } }
RendererUtils { public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); } }
RendererUtils { public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context) { final GridRenderer gridRenderer = context.getRenderer(); final GridRendererTheme theme = gridRenderer.getTheme(); return getExpressionText(theme, headerMetaData.getTitle()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderHeaderContentWithNameAndDataTypeHeaderMetaData() { final ValueAndDataTypeHeaderMetaData metaData = mock(ValueAndDataTypeHeaderMetaData.class); when(metaData.getTitle()).thenReturn(TITLE); when(metaData.getTypeRef()).thenReturn(TYPE_REF); RendererUtils.getValueAndDataTypeHeaderText(metaData, headerContext, BLOCK_WIDTH, ROW_HEIGHT); assertHasNameAndDataTypeRendering(); }
public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); }
RendererUtils { public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); } }
RendererUtils { public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); } }
RendererUtils { public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { return getNameAndDataTypeText(context.getRenderer().getTheme(), headerMetaData.getTitle(), headerMetaData.getTypeRef(), blockWidth, blockHeight); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderHeaderContentWithInformationItemCell() { final InformationItemCell.HasNameAndDataTypeCell informationItemCell = mock(InformationItemCell.HasNameAndDataTypeCell.class); final Name name = new Name(TITLE); when(informationItemCell.getName()).thenReturn(name); when(informationItemCell.getTypeRef()).thenReturn(TYPE_REF); when(informationItemCell.hasData()).thenReturn(true); RendererUtils.getNameAndDataTypeCellText(informationItemCell, bodyContext); assertHasNameAndDataTypeRendering(); }
public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); }
RendererUtils { public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); } }
RendererUtils { public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); } }
RendererUtils { public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context) { if (!hasNameAndDataTypeCell.hasData()) { final BaseGridCellValue<String> cell = new BaseGridCellValue<>(null, hasNameAndDataTypeCell.getPlaceHolderText()); return getCenteredCellText(context, new BaseGridCell<>(cell)); } return getNameAndDataTypeText(context.getRenderer().getTheme(), hasNameAndDataTypeCell.getName().getValue(), hasNameAndDataTypeCell.getTypeRef(), context.getCellWidth(), context.getCellHeight()); } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderEditableHeaderText() { when(headerMetaData.getTitle()).thenReturn(VALUE); RendererUtils.getEditableHeaderText(headerMetaData, headerContext, WIDTH, HEIGHT); assertCenteredRendering(headerText1); }
public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; }
RendererUtils { public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getHeaderText(); final String value = headerMetaData.getTitle(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(value); text.setListening(false); headerGroup.add(text); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderEditableHeaderPlaceHolderText() { when(headerMetaData.getPlaceHolder()).thenReturn(Optional.of(VALUE)); RendererUtils.getEditableHeaderPlaceHolderText(headerMetaData, headerContext, WIDTH, HEIGHT); assertCenteredRendering(placeHolderText); }
public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testRenderEditableHeaderPlaceHolderTextWhenEmpty() { when(headerMetaData.getPlaceHolder()).thenReturn(Optional.empty()); RendererUtils.getEditableHeaderPlaceHolderText(headerMetaData, headerContext, WIDTH, HEIGHT); verify(headerGroup, never()).add(any(IPrimitive.class)); }
public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); }
RendererUtils { public static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { final Group headerGroup = GWT.create(Group.class); headerMetaData.getPlaceHolder().ifPresent(placeHolder -> { final GridRenderer renderer = context.getRenderer(); final GridRendererTheme theme = renderer.getTheme(); final Text text = theme.getPlaceholderText(); text.setX(blockWidth / 2); text.setY(blockHeight / 2); text.setText(placeHolder); text.setListening(false); headerGroup.add(text); }); return headerGroup; } static Group getExpressionCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getCenteredCellText(final GridBodyCellRenderContext context, final GridCell<String> gridCell); static Group getNameAndDataTypeCellText(final InformationItemCell.HasNameAndDataTypeCell hasNameAndDataTypeCell, final GridBodyCellRenderContext context); static Group getExpressionHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context); static Group getValueAndDataTypeHeaderText(final ValueAndDataTypeHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static Group getEditableHeaderPlaceHolderText(final EditableHeaderMetaData headerMetaData, final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight); static double getExpressionTextLineHeight(final GridRendererTheme theme); static final double EXPRESSION_TEXT_PADDING; static final String FONT_STYLE_TYPE_REF; static final double SPACING; }
@Test public void testGridWidget() { assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(mock(GridWidget.class))).isFalse(); }
public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
@Test public void testBaseGrid() { when(gridWidget.isOnlyVisualChangeAllowed()).thenReturn(false); assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(gridWidget)).isFalse(); }
public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
@Test public void testParseFEELListMultipleCommasInside() { final List<String> actualList = service.parseFEELList("\"Sao Paulo, SP, South America\",\"New York, NY, North America\""); final List<String> expectedList = asList("\"Sao Paulo, SP, South America\"", "\"New York, NY, North America\""); assertEquals(expectedList, actualList); }
@Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); }
DMNParseServiceImpl implements DMNParseService { @Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); } }
DMNParseServiceImpl implements DMNParseService { @Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); } }
DMNParseServiceImpl implements DMNParseService { @Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); } @Override List<String> parseFEELList(final String source); @Override RangeValue parseRangeValue(final String source); }
DMNParseServiceImpl implements DMNParseService { @Override public List<String> parseFEELList(final String source) { return parse(source) .map(this::getTextElements) .orElseGet(ArrayList::new); } @Override List<String> parseFEELList(final String source); @Override RangeValue parseRangeValue(final String source); }
@Test public void testBaseGridWhenOnlyVisualChangeAllowed() { when(gridWidget.isOnlyVisualChangeAllowed()).thenReturn(true); assertThat(DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(gridWidget)).isTrue(); }
public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
DynamicReadOnlyUtils { public static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget) { if (gridWidget instanceof BaseGrid) { final BaseGrid baseGrid = (BaseGrid) gridWidget; return baseGrid.isOnlyVisualChangeAllowed(); } return false; } static boolean isOnlyVisualChangeAllowed(final GridWidget gridWidget); }
@Test public void testIsMultiSelectZeroSelections() { assertThat(SelectionUtils.isMultiSelect(uiModel)).isFalse(); }
public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiSelectSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiSelect(uiModel)).isFalse(); }
public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiSelectMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(0, 1); assertThat(SelectionUtils.isMultiSelect(uiModel)).isTrue(); }
public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiSelect(final GridData uiModel) { return uiModel.getSelectedCells().size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiRowZeroSelections() { assertThat(SelectionUtils.isMultiRow(uiModel)).isFalse(); }
public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiRowSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiRow(uiModel)).isFalse(); }
public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiRowMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(1, 0); assertThat(SelectionUtils.isMultiRow(uiModel)).isTrue(); }
public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiRow(final GridData uiModel) { return uiModel.getSelectedCells() .stream() .map(GridData.SelectedCell::getRowIndex) .distinct() .collect(Collectors.toList()) .size() > 1; } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiColumnZeroSelections() { assertThat(SelectionUtils.isMultiColumn(uiModel)).isFalse(); }
public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiColumnSingleSelection() { uiModel.selectCell(0, 0); assertThat(SelectionUtils.isMultiColumn(uiModel)).isFalse(); }
public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiColumnMultipleSelections() { uiModel.selectCell(0, 0); uiModel.selectCell(0, 1); assertThat(SelectionUtils.isMultiColumn(uiModel)).isTrue(); }
public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void test_function_java_WB_model() throws IOException { final DMNMarshallerStandalone m = getDMNMarshaller(); @SuppressWarnings("unchecked") final Graph<?, Node<?, ?>> g = m.unmarshall(createMetadata(), this.getClass().getResourceAsStream("/DROOLS-2372.dmn")); final Stream<Node<?, ?>> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(g.nodes().iterator(), Spliterator.ORDERED), false); final Optional<Decision> wbDecision = stream .filter(n -> n.getContent() instanceof ViewImpl) .map(n -> (ViewImpl) n.getContent()) .filter(n -> n.getDefinition() instanceof Decision) .map(n -> (Decision) n.getDefinition()) .findFirst(); wbDecision.ifPresent(d -> { assertTrue(d.getExpression() instanceof FunctionDefinition); final FunctionDefinition wbFunction = (FunctionDefinition) d.getExpression(); assertEquals(FunctionDefinition.Kind.JAVA, wbFunction.getKind()); }); final DMNRuntime runtime = roundTripUnmarshalMarshalThenUnmarshalDMN(this.getClass().getResourceAsStream("/DROOLS-2372.dmn")); final DMNModel dmnModel = runtime.getModels().get(0); final BusinessKnowledgeModelNode bkmNode = dmnModel.getBusinessKnowledgeModels().iterator().next(); final org.kie.dmn.model.api.FunctionDefinition dmnFunction = bkmNode.getBusinessKnowledModel().getEncapsulatedLogic(); assertEquals(FunctionKind.JAVA, dmnFunction.getKind()); }
@Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { @Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; } }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { @Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { @Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { @Override @SuppressWarnings("unchecked") public Graph unmarshall(final Metadata metadata, final InputStream input) throws IOException { final Map<String, HasComponentWidths> hasComponentWidthsMap = new HashMap<>(); final BiConsumer<String, HasComponentWidths> hasComponentWidthsConsumer = (uuid, hcw) -> { if (Objects.nonNull(uuid)) { hasComponentWidthsMap.put(uuid, hcw); } }; final org.kie.dmn.model.api.Definitions dmnXml = marshaller.unmarshal(new InputStreamReader(input)); final List<org.kie.dmn.model.api.DRGElement> diagramDrgElements = dmnXml.getDrgElement(); final Optional<org.kie.dmn.model.api.dmndi.DMNDiagram> dmnDDDiagram = findDMNDiagram(dmnXml); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = dmnMarshallerImportsHelper.getImportDefinitions(metadata, dmnXml.getImport()); final Map<Import, PMMLDocumentMetadata> pmmlDocuments = dmnMarshallerImportsHelper.getPMMLDocuments(metadata, dmnXml.getImport()); final List<DMNShape> dmnShapes = dmnDDDiagram.map(this::getUniqueDMNShapes).orElse(emptyList()); final List<org.kie.dmn.model.api.DRGElement> importedDrgElements = getImportedDrgElementsByShape(dmnShapes, importDefinitions); final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(); drgElements.addAll(diagramDrgElements); drgElements.addAll(importedDrgElements); removeDrgElementsWithoutShape(drgElements, dmnShapes); final Map<String, Entry<org.kie.dmn.model.api.DRGElement, Node>> elems = drgElements.stream().collect(toMap(org.kie.dmn.model.api.DRGElement::getId, dmn -> new SimpleEntry<>(dmn, dmnToStunner(dmn, hasComponentWidthsConsumer, importedDrgElements)))); final Set<org.kie.dmn.model.api.DecisionService> dmnDecisionServices = new HashSet<>(); for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { ddExtAugmentStunner(dmnDDDiagram, kv.getValue()); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { final org.kie.dmn.model.api.DRGElement elem = kv.getKey(); final Node currentNode = kv.getValue(); if (isImportedDRGElement(importedDrgElements, elem)) { continue; } if (elem instanceof org.kie.dmn.model.api.Decision) { final org.kie.dmn.model.api.Decision decision = (org.kie.dmn.model.api.Decision) elem; for (org.kie.dmn.model.api.InformationRequirement ir : decision.getInformationRequirement()) { connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(INFO_REQ_ID, ir, ir.getRequiredDecision(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.KnowledgeRequirement kr : decision.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : decision.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.BusinessKnowledgeModel) { final org.kie.dmn.model.api.BusinessKnowledgeModel bkm = (org.kie.dmn.model.api.BusinessKnowledgeModel) elem; for (org.kie.dmn.model.api.KnowledgeRequirement kr : bkm.getKnowledgeRequirement()) { connectEdgeToNodes(KNOWLEDGE_REQ_ID, kr, kr.getRequiredKnowledge(), elems, dmnXml, currentNode); } for (org.kie.dmn.model.api.AuthorityRequirement ar : bkm.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.KnowledgeSource) { final org.kie.dmn.model.api.KnowledgeSource ks = (org.kie.dmn.model.api.KnowledgeSource) elem; for (org.kie.dmn.model.api.AuthorityRequirement ar : ks.getAuthorityRequirement()) { connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredInput(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredDecision(), elems, dmnXml, currentNode); connectEdgeToNodes(AUTH_REQ_ID, ar, ar.getRequiredAuthority(), elems, dmnXml, currentNode); } } else if (elem instanceof org.kie.dmn.model.api.DecisionService) { final org.kie.dmn.model.api.DecisionService ds = (org.kie.dmn.model.api.DecisionService) elem; dmnDecisionServices.add(ds); for (org.kie.dmn.model.api.DMNElementReference er : ds.getEncapsulatedDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } for (org.kie.dmn.model.api.DMNElementReference er : ds.getOutputDecision()) { final String reqInputID = getId(er); final Node requiredNode = getRequiredNode(elems, reqInputID); if (Objects.nonNull(requiredNode)) { connectDSChildEdge(currentNode, requiredNode); } } } } final Map<String, Node<View<TextAnnotation>, ?>> textAnnotations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.TextAnnotation.class::isInstance) .map(org.kie.dmn.model.api.TextAnnotation.class::cast) .collect(Collectors.toMap(org.kie.dmn.model.api.TextAnnotation::getId, dmn -> textAnnotationConverter.nodeFromDMN(dmn, hasComponentWidthsConsumer))); textAnnotations.values().forEach(n -> ddExtAugmentStunner(dmnDDDiagram, n)); final List<org.kie.dmn.model.api.Association> associations = dmnXml.getArtifact().stream() .filter(org.kie.dmn.model.api.Association.class::isInstance) .map(org.kie.dmn.model.api.Association.class::cast) .collect(Collectors.toList()); for (org.kie.dmn.model.api.Association a : associations) { final String sourceId = getId(a.getSourceRef()); final Node sourceNode = Optional.ofNullable(elems.get(sourceId)).map(Entry::getValue).orElse(textAnnotations.get(sourceId)); final String targetId = getId(a.getTargetRef()); final Node targetNode = Optional.ofNullable(elems.get(targetId)).map(Entry::getValue).orElse(textAnnotations.get(targetId)); @SuppressWarnings("unchecked") final Edge<View<Association>, ?> myEdge = (Edge<View<Association>, ?>) factoryManager.newElement(idOfDMNorWBUUID(a), ASSOCIATION_ID).asEdge(); final Id id = new Id(a.getId()); final Description description = new Description(a.getDescription()); final Association definition = new Association(id, description); myEdge.getContent().setDefinition(definition); connectEdge(myEdge, sourceNode, targetNode); setConnectionMagnets(myEdge, a.getId(), dmnXml); } for (Entry<org.kie.dmn.model.api.DRGElement, Node> kv : elems.values()) { PointUtils.convertToRelativeBounds(kv.getValue()); } final Graph graph = factoryManager.newDiagram("prova", BindableAdapterUtils.getDefinitionSetId(DMNDefinitionSet.class), metadata).getGraph(); elems.values().stream().map(Map.Entry::getValue).forEach(graph::addNode); textAnnotations.values().forEach(graph::addNode); final Node<?, ?> dmnDiagramRoot = findDMNDiagramRoot(graph); final Definitions definitionsStunnerPojo = DefinitionsConverter.wbFromDMN(dmnXml, importDefinitions, pmmlDocuments); loadImportedItemDefinitions(definitionsStunnerPojo, importDefinitions); ((View<DMNDiagram>) dmnDiagramRoot.getContent()).getDefinition().setDefinitions(definitionsStunnerPojo); final List<String> references = new ArrayList<>(); dmnDecisionServices.forEach(ds -> references.addAll(ds.getEncapsulatedDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); dmnDecisionServices.forEach(ds -> references.addAll(ds.getOutputDecision().stream().map(org.kie.dmn.model.api.DMNElementReference::getHref).collect(Collectors.toList()))); final Map<org.kie.dmn.model.api.DRGElement, Node> elemsToConnectToRoot = elems.values().stream() .filter(elem -> !references.contains("#" + elem.getKey().getId())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); elemsToConnectToRoot.values().stream() .forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); textAnnotations.values().stream().forEach(node -> connectRootWithChild(dmnDiagramRoot, node)); final Optional<ComponentsWidthsExtension> extension = findComponentsWidthsExtension(dmnDDDiagram); extension.ifPresent(componentsWidthsExtension -> { if (componentsWidthsExtension.getComponentsWidths() != null) { hasComponentWidthsMap.forEach((uuid, hasComponentWidths) -> componentsWidthsExtension .getComponentsWidths() .stream() .filter(componentWidths -> componentWidths.getDmnElementRef().getLocalPart().equals(uuid)) .findFirst() .ifPresent(componentWidths -> { final List<Double> widths = hasComponentWidths.getComponentWidths(); widths.clear(); widths.addAll(componentWidths.getWidths()); })); } }); return graph; } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
@Test public void testIsMultiHeaderColumnZeroSelections() { assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isFalse(); }
public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiHeaderColumnSingleSelection() { uiModel.selectHeaderCell(0, 0); assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isFalse(); }
public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testIsMultiHeaderColumnMultipleSelections() { uiModel.selectHeaderCell(0, 0); uiModel.selectHeaderCell(0, 1); assertThat(SelectionUtils.isMultiHeaderColumn(uiModel)).isTrue(); }
public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
SelectionUtils { public static boolean isMultiHeaderColumn(final GridData uiModel) { return isMultiColumn(uiModel.getSelectedHeaderCells()); } static boolean isMultiSelect(final GridData uiModel); static boolean isMultiRow(final GridData uiModel); static boolean isMultiColumn(final GridData uiModel); static boolean isMultiHeaderColumn(final GridData uiModel); }
@Test public void testNull() { assertThat(NameUtils.normaliseName(null)).isEmpty(); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testEmpty() { assertThat(NameUtils.normaliseName("")).isEmpty(); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testLeadingWhitespace() { assertThat(NameUtils.normaliseName(" hello")).isEqualTo("hello"); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testTrailingWhitespace() { assertThat(NameUtils.normaliseName("hello ")).isEqualTo("hello"); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testCompactWhitespace() { assertThat(NameUtils.normaliseName("hello world")).isEqualTo("hello world"); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testCompleteNormalisation() { assertThat(NameUtils.normaliseName(" hello world ")).isEqualTo("hello world"); }
public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
NameUtils { public static String normaliseName(final String name) { if (Objects.isNull(name)) { return ""; } String value = name; if (StringUtils.nonEmpty(value)) { value = value.trim(); value = value.replaceAll(NORMALIZE_TO_SINGLE_WHITE_SPACE, WHITESPACE_STRING); } return value; } private NameUtils(); static String normaliseName(final String name); }
@Test public void testGetTypeRefOfExpression() { when(hasExpression.asDMNModelInstrumentedBase()).thenReturn(mock(DMNModelInstrumentedBase.class)); when(expression.getTypeRef()).thenReturn(TYPE_REF); assertThat(TypeRefUtils.getTypeRefOfExpression(expression, hasExpression).getTypeRef()).isEqualTo(TYPE_REF); }
public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } static HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression); }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } static HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression); }
@Test public void testGetImportedDrgElementsByShape() { final DMNMarshallerStandalone marshaller = spy(getDMNMarshaller()); final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = mock(List.class); final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions = mock(Map.class); final org.kie.dmn.model.api.DRGElement ref1 = mock(org.kie.dmn.model.api.DRGElement.class); final org.kie.dmn.model.api.DRGElement ref2 = mock(org.kie.dmn.model.api.DRGElement.class); final org.kie.dmn.model.api.DRGElement ref3 = mock(org.kie.dmn.model.api.DRGElement.class); final List<DMNShape> dmnShapes = new ArrayList<>(); final DMNShape shape1 = mock(DMNShape.class); final DMNShape shape2 = mock(DMNShape.class); final DMNShape shape3 = mock(DMNShape.class); dmnShapes.add(shape1); dmnShapes.add(shape2); dmnShapes.add(shape3); doReturn("REF1").when(marshaller).getDmnElementRef(shape1); doReturn("REF2").when(marshaller).getDmnElementRef(shape2); doReturn("REF3").when(marshaller).getDmnElementRef(shape3); when(dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions)).thenReturn(importedDRGElements); doReturn(Optional.of(ref1)).when(marshaller).getReference(importedDRGElements, "REF1"); doReturn(Optional.of(ref2)).when(marshaller).getReference(importedDRGElements, "REF2"); doReturn(Optional.of(ref3)).when(marshaller).getReference(importedDRGElements, "REF3"); final List<DRGElement> actual = marshaller.getImportedDrgElementsByShape(dmnShapes, importDefinitions); assertEquals(ref1, actual.get(0)); assertEquals(ref2, actual.get(1)); assertEquals(ref3, actual.get(2)); }
List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { List<org.kie.dmn.model.api.DRGElement> getImportedDrgElementsByShape(final List<DMNShape> dmnShapes, final Map<Import, org.kie.dmn.model.api.Definitions> importDefinitions) { final List<org.kie.dmn.model.api.DRGElement> importedDRGElements = dmnMarshallerImportsHelper.getImportedDRGElements(importDefinitions); return dmnShapes .stream() .map(shape -> { final String dmnElementRef = getDmnElementRef(shape); final Optional<org.kie.dmn.model.api.DRGElement> ref = getReference(importedDRGElements, dmnElementRef); return ref.orElse(null); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }
@Test public void testGetTypeRefOfExpressionWhenHasExpressionHasVariable() { when(hasExpression.asDMNModelInstrumentedBase()).thenReturn(decision); when(decision.getVariable()).thenReturn(decisionVariable); when(decisionVariable.getTypeRef()).thenReturn(TYPE_REF); assertThat(TypeRefUtils.getTypeRefOfExpression(expression, hasExpression).getTypeRef()).isEqualTo(TYPE_REF); }
public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } static HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression); }
TypeRefUtils { public static <E extends Expression> HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression) { HasTypeRef hasTypeRef = expression; final DMNModelInstrumentedBase base = hasExpression.asDMNModelInstrumentedBase(); if (base instanceof HasVariable) { final HasVariable hasVariable = (HasVariable) base; hasTypeRef = hasVariable.getVariable(); } return hasTypeRef; } static HasTypeRef getTypeRefOfExpression(final E expression, final HasExpression hasExpression); }
@Test public void testBind() { control.bind(session); assertNotNull(control.getExpressionEditor()); verify(editor).bind(session); verify(canvasHandler).addDomainObjectListener(any(CanvasDomainObjectListener.class)); }
@Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testBindDomainObjectListenerWithNodeMatch() { final Definition definition = mock(Definition.class); when(graph.nodes()).thenReturn(Collections.singletonList(node)); when(node.getContent()).thenReturn(definition); when(definition.getDefinition()).thenReturn(domainObject); when(domainObject.getDomainObjectUUID()).thenReturn("uuid"); control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); domainObjectListener.update(domainObject); verify(canvasElementUpdatedEvent).fire(canvasElementUpdatedEventCaptor.capture()); final CanvasElementUpdatedEvent canvasElementUpdatedEvent = canvasElementUpdatedEventCaptor.getValue(); assertThat(canvasElementUpdatedEvent.getCanvasHandler()).isEqualTo(canvasHandler); assertThat(canvasElementUpdatedEvent.getElement()).isEqualTo(node); }
@Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testBindDomainObjectListenerWithNoNodeMatch() { when(graph.nodes()).thenReturn(Collections.emptyList()); control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); domainObjectListener.update(domainObject); verify(canvasElementUpdatedEvent, never()).fire(any(CanvasElementUpdatedEvent.class)); }
@Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override public void bind(final DMNSession session) { final ExpressionEditorView.Presenter editor = makeExpressionEditor(view, decisionNavigator, dmnGraphUtils, dmnDiagramsSession); editor.bind(session); this.session = Optional.of(session); this.expressionEditor = Optional.of(editor); this.refreshEditorDomainObjectListener = new RefreshEditorDomainObjectListener(session); session.getCanvasHandler().addDomainObjectListener(refreshEditorDomainObjectListener); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testDoInit() { assertNull(control.getExpressionEditor()); control.doInit(); assertNull(control.getExpressionEditor()); }
@Override protected void doInit() { }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doInit() { } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doInit() { } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doInit() { } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doInit() { } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testDoDestroy() { control.bind(session); verify(canvasHandler).addDomainObjectListener(domainObjectListenerCaptor.capture()); control.doDestroy(); assertNull(control.getExpressionEditor()); final CanvasDomainObjectListener domainObjectListener = domainObjectListenerCaptor.getValue(); verify(canvasHandler).removeDomainObjectListener(domainObjectListener); }
@Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @Override protected void doDestroy() { view = null; decisionNavigator = null; session.ifPresent(s -> s.getCanvasHandler().removeDomainObjectListener(refreshEditorDomainObjectListener)); session = Optional.empty(); expressionEditor = Optional.empty(); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testOnCanvasFocusedSelectionEventWhenNotBound() { control.onCanvasFocusedSelectionEvent(event); verifyNoMoreInteractions(editor); }
@SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { @SuppressWarnings("unused") public void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event) { session.ifPresent(s -> { if (Objects.equals(s.getCanvasHandler(), event.getCanvasHandler())) { expressionEditor.ifPresent(ExpressionEditorView.Presenter::exit); } }); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testOnCanvasElementUpdated() { control.bind(session); final CanvasElementUpdatedEvent event = new CanvasElementUpdatedEvent(canvasHandler, node); control.onCanvasElementUpdated(event); verify(editor).handleCanvasElementUpdated(event); }
public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); } }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
ExpressionEditorControlImpl extends AbstractCanvasControl<AbstractCanvas> implements ExpressionEditorControl { public void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event) { expressionEditor.ifPresent(editor -> editor.handleCanvasElementUpdated(event)); } @Inject ExpressionEditorControlImpl(final ExpressionEditorView view, final DecisionNavigatorPresenter decisionNavigator, final DMNGraphUtils dmnGraphUtils, final DMNDiagramsSession dmnDiagramsSession, final Event<CanvasElementUpdatedEvent> canvasElementUpdatedEvent, final DRDNameChanger drdNameChanger); @Override void bind(final DMNSession session); @Override ExpressionEditorView.Presenter getExpressionEditor(); @SuppressWarnings("unused") void onCanvasFocusedSelectionEvent(final @Observes CanvasSelectionEvent event); void onCanvasElementUpdated(final @Observes CanvasElementUpdatedEvent event); }
@Test public void testFromDMNModelUndefinedExpressionType() { setup(false); expression = null; mapper.fromDMNModel(0, 0); assertFromDMNModelUndefinedExpressionType(false); }
@Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex, final int columnIndex); @Override void toDMNModel(final int rowIndex, final int columnIndex, final Supplier<Optional<GridCellValue<?>>> cell); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex, final int columnIndex); @Override void toDMNModel(final int rowIndex, final int columnIndex, final Supplier<Optional<GridCellValue<?>>> cell); }
@Test public void testFromDMNModelWhenOnlyVisualChangeAllowed() { setup(true); expression = null; mapper.fromDMNModel(0, 0); assertFromDMNModelUndefinedExpressionType(true); }
@Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex, final int columnIndex); @Override void toDMNModel(final int rowIndex, final int columnIndex, final Supplier<Optional<GridCellValue<?>>> cell); }
ExpressionContainerUIModelMapper extends BaseUIModelMapper<Expression> { @Override public void fromDMNModel(final int rowIndex, final int columnIndex) { final String uuid = nodeUUID.get(); final GridData uiModel = this.uiModel.get(); final Optional<Expression> expression = dmnModel.get(); final Optional<HasName> hasName = this.hasName.get(); final boolean isOnlyVisualChangeAllowed = this.isOnlyVisualChangeAllowedSupplier.get(); final HasExpression hasExpression = this.hasExpression.get(); final Optional<ExpressionEditorDefinition<Expression>> expressionEditorDefinition = expressionEditorDefinitions.get().getExpressionEditorDefinition(expression); expressionEditorDefinition.ifPresent(definition -> { Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> editor = expressionGridCache.get().getExpressionGrid(uuid); if (!editor.isPresent()) { final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> oEditor = definition.getEditor(parent, Optional.of(uuid), hasExpression, hasName, isOnlyVisualChangeAllowed, 0); expressionGridCache.get().putExpressionGrid(uuid, oEditor); editor = oEditor; } final Optional<BaseExpressionGrid<? extends Expression, ? extends GridData, ? extends BaseUIModelMapper>> _editor = editor; uiModel.setCell(0, 0, () -> new ContextGridCell<>(new ExpressionCellValue(_editor), listSelector)); }); } ExpressionContainerUIModelMapper(final GridCellTuple parent, final Supplier<GridData> uiModel, final Supplier<Optional<Expression>> dmnModel, final Supplier<String> nodeUUID, final Supplier<HasExpression> hasExpression, final Supplier<Optional<HasName>> hasName, final Supplier<Boolean> isOnlyVisualChangeAllowedSupplier, final Supplier<ExpressionEditorDefinitions> expressionEditorDefinitions, final Supplier<ExpressionGridCache> expressionGridCache, final ListSelectorView.Presenter listSelector); @Override void fromDMNModel(final int rowIndex, final int columnIndex); @Override void toDMNModel(final int rowIndex, final int columnIndex, final Supplier<Optional<GridCellValue<?>>> cell); }
@Test public void testGetDmnElementRef() { final DMNMarshallerStandalone marshaller = spy(getDMNMarshaller()); final String expected = "localPart"; final DMNShape shape = mock(DMNShape.class); final javax.xml.namespace.QName ref = mock(javax.xml.namespace.QName.class); when(ref.getLocalPart()).thenReturn(expected); when(shape.getDmnElementRef()).thenReturn(ref); final String actual = marshaller.getDmnElementRef(shape); assertEquals(expected, actual); }
String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); } }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); }
DMNMarshallerStandalone implements DiagramMarshaller<Graph, Metadata, Diagram<Graph, Metadata>> { String getDmnElementRef(final DMNShape dmnShape) { return Optional .ofNullable(dmnShape.getDmnElementRef()) .map(QName::getLocalPart) .orElse(""); } protected DMNMarshallerStandalone(); @Inject DMNMarshallerStandalone(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final FactoryManager factoryManager, final DMNMarshallerImportsHelperStandalone dmnMarshallerImportsHelper, final DMNMarshaller marshaller); @Override @SuppressWarnings("unchecked") Graph unmarshall(final Metadata metadata, final InputStream input); static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectRootWithChild(final Node dmnDiagramRoot, final Node child); @SuppressWarnings({"rawtypes", "unchecked"}) static void connectEdge(final Edge edge, final Node source, final Node target); @Override @SuppressWarnings("unchecked") String marshall(final Diagram<Graph, Metadata> diagram); @Override DiagramMetadataMarshaller<Metadata> getMetadataMarshaller(); static final String INFO_REQ_ID; static final String KNOWLEDGE_REQ_ID; static final String AUTH_REQ_ID; static final String ASSOCIATION_ID; }