Search in sources :

Example 6 with DefaultNeedModelWrapper

use of won.protocol.util.DefaultNeedModelWrapper in project webofneeds by researchstudio-sat.

the class SolrMatcherEvaluation method createNeedId.

public static String createNeedId(Dataset need) {
    String title = "";
    String description = "";
    try {
        DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(need);
        title = needModelWrapper.getTitles(NeedContentPropertyType.ALL).iterator().next();
        title = title.replaceAll("[^A-Za-z0-9 ]", "_");
        title = title.replaceAll("NOT", "_");
        title = title.replaceAll("AND", "_");
        title = title.replaceAll("OR", "_");
        description = needModelWrapper.getSomeDescription(NeedContentPropertyType.ALL);
    } catch (IncorrectPropertyCountException e) {
    // do nothing
    }
    if (title.isEmpty()) {
        throw new IllegalArgumentException("need has no title!!");
    }
    return title + "_" + (title + description).hashCode();
}
Also used : DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) IncorrectPropertyCountException(won.protocol.exception.IncorrectPropertyCountException)

Example 7 with DefaultNeedModelWrapper

use of won.protocol.util.DefaultNeedModelWrapper in project webofneeds by researchstudio-sat.

the class WonOwnerMailSender method createContext.

private VelocityContext createContext(String toEmail, String localNeed, String remoteNeed, String localConnection, String textMsg) {
    String ownerAppLink = uriService.getOwnerProtocolOwnerURI().toString();
    VelocityContext velocityContext = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(new EscapeHtmlReference());
    ec.attachToContext(velocityContext);
    if (remoteNeed != null) {
        Dataset needDataset = linkedDataSource.getDataForResource(URI.create(remoteNeed));
        DefaultNeedModelWrapper remoteNeedWrapper = new DefaultNeedModelWrapper(needDataset);
        String remoteNeedTitle = remoteNeedWrapper.getSomeTitleFromIsOrAll("en", "de");
        velocityContext.put("remoteNeedTitle", remoteNeedTitle);
        String linkRemoteNeed = uriService.getOwnerProtocolOwnerURI() + OWNER_REMOTE_NEED_LINK + remoteNeed;
        velocityContext.put("linkRemoteNeed", linkRemoteNeed);
    }
    if (localNeed != null) {
        Dataset localNeedDataset = linkedDataSource.getDataForResource(URI.create(localNeed));
        DefaultNeedModelWrapper localNeedWrapper = new DefaultNeedModelWrapper(localNeedDataset);
        String localNeedTitle = localNeedWrapper.getSomeTitleFromIsOrAll("en", "de");
        String linkLocalNeed = ownerAppLink + OWNER_LOCAL_NEED_LINK + localNeed;
        velocityContext.put("linkLocalNeed", linkLocalNeed);
        velocityContext.put("localNeedTitle", localNeedTitle);
    }
    if (localConnection != null) {
        String linkConnection = ownerAppLink + String.format(OWNER_CONNECTION_LINK, localNeed, localConnection, ConnectionState.CONNECTED.getURI().toString());
        velocityContext.put("linkConnection", linkConnection);
    }
    if (textMsg != null) {
        velocityContext.put("textMsg", textMsg);
    }
    return velocityContext;
}
Also used : DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) EscapeHtmlReference(org.apache.velocity.app.event.implement.EscapeHtmlReference) VelocityContext(org.apache.velocity.VelocityContext) Dataset(org.apache.jena.query.Dataset) EventCartridge(org.apache.velocity.app.event.EventCartridge)

Example 8 with DefaultNeedModelWrapper

use of won.protocol.util.DefaultNeedModelWrapper in project webofneeds by researchstudio-sat.

the class NeedIndexer method indexNeedModel.

public void indexNeedModel(Model needModel, String id, boolean useTestCore) throws IOException, JsonLdError {
    // create the json from rdf model
    StringWriter sw = new StringWriter();
    RDFDataMgr.write(sw, needModel, Lang.JSONLD);
    String jsonld = sw.toString();
    Object jsonObject = JsonUtils.fromString(jsonld);
    Object frame = JsonUtils.fromString(" {\"@type\": \"" + WON.NEED + "\"} ");
    JsonLdOptions options = new JsonLdOptions();
    Map<String, Object> framed = JsonLdProcessor.frame(jsonObject, frame, options);
    // add the uri of the need as id field to avoid multiple adding of needs but instead allow updates
    framed.put("id", id);
    // add latitude and longitude values in one field for Solr spatial queries
    DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(needModel, null);
    for (Resource contentNode : needModelWrapper.getContentNodes(NeedContentPropertyType.IS)) {
        Coordinate coordinate = needModelWrapper.getLocationCoordinate(contentNode);
        if (coordinate != null) {
            framed.put(SOLR_IS_LOCATION_COORDINATES_FIELD, String.valueOf(coordinate.getLatitude()) + "," + String.valueOf(coordinate.getLongitude()));
        }
    }
    for (Resource contentNode : needModelWrapper.getContentNodes(NeedContentPropertyType.SEEKS)) {
        Coordinate coordinate = needModelWrapper.getLocationCoordinate(contentNode);
        if (coordinate != null) {
            framed.put(SOLR_SEEKS_LOCATION_COORDINATES_FIELD, String.valueOf(coordinate.getLatitude()) + "," + String.valueOf(coordinate.getLongitude()));
        }
    }
    for (Resource contentNode : needModelWrapper.getContentNodes(NeedContentPropertyType.SEEKS_SEEKS)) {
        Coordinate coordinate = needModelWrapper.getLocationCoordinate(contentNode);
        if (coordinate != null) {
            framed.put(SOLR_SEEKS_SEEKS_LOCATION_COORDINATES_FIELD, String.valueOf(coordinate.getLatitude()) + "," + String.valueOf(coordinate.getLongitude()));
        }
    }
    // write the final json string
    sw = new StringWriter();
    JsonUtils.writePrettyPrint(sw, framed);
    String needJson = sw.toString();
    // post the need to the solr index
    String indexUri = config.getSolrEndpointUri(useTestCore);
    indexUri += "update/json/docs";
    if (config.isCommitIndexedNeedImmediately()) {
        indexUri += "?commit=" + config.isCommitIndexedNeedImmediately();
    }
    log.debug("Post need to solr index. \n Solr URI: {} \n Need (JSON): {}", indexUri, needJson);
    httpService.postJsonRequest(indexUri, needJson);
}
Also used : DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) StringWriter(java.io.StringWriter) JsonLdOptions(com.github.jsonldjava.core.JsonLdOptions) Coordinate(won.protocol.model.Coordinate) Resource(org.apache.jena.rdf.model.Resource)

Example 9 with DefaultNeedModelWrapper

use of won.protocol.util.DefaultNeedModelWrapper in project webofneeds by researchstudio-sat.

the class CreateNeedFromMailAction method doRun.

protected void doRun(Event event, EventListener executingListener) throws Exception {
    EventListenerContext ctx = getEventListenerContext();
    if (event instanceof CreateNeedFromMailEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
        MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
        MimeMessage message = ((CreateNeedFromMailEvent) event).getMessage();
        try {
            NeedContentPropertyType type = mailContentExtractor.getNeedType(message);
            String title = mailContentExtractor.getTitle(message);
            String description = mailContentExtractor.getDescription(message);
            String[] tags = mailContentExtractor.getTags(message);
            boolean isUsedForTesting = mailContentExtractor.isUsedForTesting(message);
            boolean isDoNotMatch = mailContentExtractor.isDoNotMatch(message);
            WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
            final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
            final URI needURI = wonNodeInformationService.generateNeedURI(wonNodeUri);
            DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(needURI.toString());
            needModelWrapper.setTitle(type, title);
            needModelWrapper.setDescription(type, description);
            for (String tag : tags) {
                needModelWrapper.addTag(type, tag);
            }
            for (URI facet : facets) {
                needModelWrapper.addFacetUri(facet.toString());
            }
            Dataset dataset = needModelWrapper.copyDataset();
            logger.debug("creating need on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(dataset), 150));
            WonMessage createNeedMessage = createWonMessage(wonNodeInformationService, needURI, wonNodeUri, dataset, isUsedForTesting, isDoNotMatch);
            EventBotActionUtils.rememberInList(ctx, needURI, uriListName);
            botContextWrapper.addUriMimeMessageRelation(needURI, message);
            EventListener successCallback = new EventListener() {

                @Override
                public void onEvent(Event event) throws Exception {
                    logger.debug("need creation successful, new need URI is {}", needURI);
                    String sender = MailContentExtractor.getFromAddressString(botContextWrapper.getMimeMessageForURI(needURI));
                    botContextWrapper.addMailAddressWonURIRelation(sender, new WonURI(needURI, UriType.NEED));
                    logger.debug("created need was from sender: " + sender);
                }
            };
            EventListener failureCallback = new EventListener() {

                @Override
                public void onEvent(Event event) throws Exception {
                    String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
                    logger.debug("need creation failed for need URI {}, original message URI {}: {}", new Object[] { needURI, ((FailureResponseEvent) event).getOriginalMessageURI(), textMessage });
                    EventBotActionUtils.removeFromList(ctx, needURI, uriListName);
                    botContextWrapper.removeUriMimeMessageRelation(needURI);
                }
            };
            EventBotActionUtils.makeAndSubscribeResponseListener(createNeedMessage, successCallback, failureCallback, ctx);
            logger.debug("registered listeners for response to message URI {}", createNeedMessage.getMessageURI());
            ctx.getWonMessageSender().sendWonMessage(createNeedMessage);
            logger.debug("need creation message sent with message URI {}", createNeedMessage.getMessageURI());
        } catch (MessagingException me) {
            logger.error("messaging exception occurred: {}", me);
        }
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MessagingException(javax.mail.MessagingException) Dataset(org.apache.jena.query.Dataset) WonNodeInformationService(won.protocol.service.WonNodeInformationService) NeedContentPropertyType(won.protocol.model.NeedContentPropertyType) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) MimeMessage(javax.mail.internet.MimeMessage) WonMessage(won.protocol.message.WonMessage) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) EventListener(won.bot.framework.eventbot.listener.EventListener) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent)

Example 10 with DefaultNeedModelWrapper

use of won.protocol.util.DefaultNeedModelWrapper in project webofneeds by researchstudio-sat.

the class MailCommandAction method retrieveCorrespondingNeedUriFromMailByTitle.

/**
 * This Method tries to find a corresponding open need uri from a user(given by the from adress) and returns the
 * corresponding need uri if there was an open need with the same title
 * @param message used to extract sender adress and subject(title)
 * @return
 */
private URI retrieveCorrespondingNeedUriFromMailByTitle(MimeMessage message) {
    try {
        MailBotContextWrapper botContextWrapper = ((MailBotContextWrapper) getEventListenerContext().getBotContextWrapper());
        String sender = ((InternetAddress) message.getFrom()[0]).getAddress();
        URI needURI = null;
        String titleToClose = mailContentExtractor.getTitle(message).trim();
        if (sender != null) {
            List<WonURI> needUris = botContextWrapper.getWonURIsForMailAddress(sender);
            for (WonURI u : needUris) {
                Dataset needRDF = getEventListenerContext().getLinkedDataSource().getDataForResource(u.getUri());
                DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(needRDF);
                String needTitle = StringUtils.trim(needModelWrapper.getSomeTitleFromIsOrAll("en", "de"));
                if (titleToClose.equals(needTitle) && needModelWrapper.getNeedState().equals(NeedState.ACTIVE)) {
                    return u.getUri();
                }
            }
        }
        return needURI;
    } catch (MessagingException me) {
        logger.error("could not extract information from mimemessage");
        return null;
    }
}
Also used : DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) InternetAddress(javax.mail.internet.InternetAddress) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MessagingException(javax.mail.MessagingException) Dataset(org.apache.jena.query.Dataset) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI)

Aggregations

DefaultNeedModelWrapper (won.protocol.util.DefaultNeedModelWrapper)14 Dataset (org.apache.jena.query.Dataset)9 URI (java.net.URI)5 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)4 Event (won.bot.framework.eventbot.event.Event)4 FailureResponseEvent (won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent)4 EventListener (won.bot.framework.eventbot.listener.EventListener)4 WonMessage (won.protocol.message.WonMessage)4 WonNodeInformationService (won.protocol.service.WonNodeInformationService)4 MimeMessage (javax.mail.internet.MimeMessage)3 SendMessage (org.telegram.telegrambots.api.methods.send.SendMessage)3 WonURI (won.bot.framework.eventbot.action.impl.mail.model.WonURI)3 StringWriter (java.io.StringWriter)2 MessagingException (javax.mail.MessagingException)2 InternetAddress (javax.mail.internet.InternetAddress)2 MailBotContextWrapper (won.bot.framework.bot.context.MailBotContextWrapper)2 NeedCreationFailedEvent (won.bot.framework.eventbot.event.NeedCreationFailedEvent)2 NeedCreatedEventForMatcher (won.bot.framework.eventbot.event.impl.matcher.NeedCreatedEventForMatcher)2 NeedCreatedEvent (won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent)2 NeedContentPropertyType (won.protocol.model.NeedContentPropertyType)2