Search in sources :

Example 11 with PersistenceException

use of org.codice.ddf.persistence.PersistenceException in project ddf by codice.

the class SubscriptionsPersistentStoreImpl method addEmails.

@SuppressWarnings("unchecked")
@Override
public void addEmails(String id, Set<String> emails) {
    notBlank(id, "id must be non-blank");
    notNull(emails, "emails must be non-null");
    emails.forEach(email -> notBlank(email, "emails in set must be non-blank"));
    LOCK.lock();
    try {
        List<Map<String, Object>> results = get(id);
        if (!results.isEmpty()) {
            PersistentItem item = convert(results.get(0));
            if (item.containsKey(EMAIL_PROPERTY + PersistentItem.TEXT_SUFFIX)) {
                Set<String> newValue = new HashSet<>(emails);
                Object value = item.get(EMAIL_PROPERTY + PersistentItem.TEXT_SUFFIX);
                if (value instanceof String) {
                    newValue.add((String) value);
                } else if (value instanceof Set) {
                    ((Set) value).stream().filter(String.class::isInstance).forEach(obj -> newValue.add((String) obj));
                }
                item.addProperty(EMAIL_PROPERTY, newValue);
            } else {
                item.addProperty(EMAIL_PROPERTY, emails);
            }
            persistentStore.add(SubscriptionsPersistentStore.SUBSCRIPTIONS_TYPE, item);
        } else {
            PersistentItem persistentItem = new PersistentItem();
            persistentItem.addIdProperty(id);
            persistentItem.addProperty(EMAIL_PROPERTY, emails);
            persistentStore.add(SubscriptionsPersistentStore.SUBSCRIPTIONS_TYPE, persistentItem);
        }
    } catch (PersistenceException e) {
        LOGGER.warn("unable to add emails to workspace: workspaceId={} emails={}", id, emails, e);
    } finally {
        LOCK.unlock();
    }
}
Also used : Logger(org.slf4j.Logger) ReentrantLock(java.util.concurrent.locks.ReentrantLock) PersistentItem(org.codice.ddf.persistence.PersistentItem) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Validate.notBlank(org.apache.commons.lang3.Validate.notBlank) Collectors(java.util.stream.Collectors) PersistenceException(org.codice.ddf.persistence.PersistenceException) HashSet(java.util.HashSet) List(java.util.List) Lock(java.util.concurrent.locks.Lock) Stream(java.util.stream.Stream) PersistentStore(org.codice.ddf.persistence.PersistentStore) Map(java.util.Map) SubscriptionsPersistentStore(org.codice.ddf.catalog.ui.query.monitor.api.SubscriptionsPersistentStore) Validate.notNull(org.apache.commons.lang3.Validate.notNull) Optional(java.util.Optional) Collections(java.util.Collections) Set(java.util.Set) HashSet(java.util.HashSet) PersistentItem(org.codice.ddf.persistence.PersistentItem) PersistenceException(org.codice.ddf.persistence.PersistenceException) Map(java.util.Map) HashSet(java.util.HashSet)

Example 12 with PersistenceException

use of org.codice.ddf.persistence.PersistenceException in project ddf by codice.

the class DeleteCommand method execute.

@Override
public Object execute() throws Exception {
    PrintStream console = System.out;
    // Get Notification service
    @SuppressWarnings("rawtypes") ServiceReference[] serviceReferences = bundleContext.getServiceReferences(SERVICE_PID, null);
    int numDeleted = 0;
    if (serviceReferences == null || serviceReferences.length != 1) {
        LOGGER.debug("Found no service references for {}", SERVICE_PID);
    } else {
        LOGGER.debug("Found " + serviceReferences.length + " service references for " + SERVICE_PID);
        PersistentStore persistentStore = (PersistentStore) bundleContext.getService(serviceReferences[0]);
        if (persistentStore != null) {
            if (StringUtils.isNotBlank(id)) {
                try {
                    numDeleted = persistentStore.delete(PersistentStore.NOTIFICATION_TYPE, Notification.NOTIFICATION_KEY_ID + " = '" + id + "'");
                } catch (PersistenceException e) {
                    LOGGER.info("PersistenceException during deletion of notifications for ID {}", id, e);
                }
            } else if (StringUtils.isNotBlank(userId)) {
                try {
                    numDeleted = persistentStore.delete(PersistentStore.NOTIFICATION_TYPE, Notification.NOTIFICATION_KEY_USER_ID + " = '" + userId + "'");
                } catch (PersistenceException e) {
                    LOGGER.info("PersistenceException during deletion of notifications for user {}", userId, e);
                }
            }
        } else {
            LOGGER.debug("Unable to lookup PersistentStore service");
        }
    }
    console.println(CYAN_CONSOLE_COLOR + "Deleted " + numDeleted + " notifications" + DEFAULT_CONSOLE_COLOR);
    return null;
}
Also used : PrintStream(java.io.PrintStream) PersistenceException(org.codice.ddf.persistence.PersistenceException) PersistentStore(org.codice.ddf.persistence.PersistentStore) ServiceReference(org.osgi.framework.ServiceReference)

Example 13 with PersistenceException

use of org.codice.ddf.persistence.PersistenceException in project ddf by codice.

the class ListCommand method getNotifications.

@SuppressWarnings("unchecked")
private List<Map<String, Object>> getNotifications(String userId) throws InvalidSyntaxException {
    List<Map<String, Object>> notifications = new ArrayList<>();
    // Get Notification service
    @SuppressWarnings("rawtypes") ServiceReference[] serviceReferences = bundleContext.getServiceReferences(SERVICE_PID, null);
    if (serviceReferences == null || serviceReferences.length != 1) {
        LOGGER.debug("Found no service references for {}", SERVICE_PID);
    } else {
        LOGGER.debug("Found " + serviceReferences.length + " service references for " + SERVICE_PID);
        PersistentStore persistentStore = (PersistentStore) bundleContext.getService(serviceReferences[0]);
        if (persistentStore != null) {
            try {
                List<Map<String, Object>> results;
                if (StringUtils.isNotBlank(cql)) {
                    results = persistentStore.get(PersistentStore.NOTIFICATION_TYPE, cql);
                } else if (StringUtils.isNotBlank(userId)) {
                    results = persistentStore.get(PersistentStore.NOTIFICATION_TYPE, Notification.NOTIFICATION_KEY_USER_ID + " = '" + userId + "'");
                } else {
                    results = persistentStore.get(PersistentStore.NOTIFICATION_TYPE);
                }
                for (Map<String, Object> result : results) {
                    notifications.add(PersistentItem.stripSuffixes(result));
                }
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException during retrieval of notifications", e);
            }
        } else {
            LOGGER.debug("Unable to lookup PersistentStore service");
        }
    }
    return notifications;
}
Also used : ArrayList(java.util.ArrayList) PersistenceException(org.codice.ddf.persistence.PersistenceException) PersistentStore(org.codice.ddf.persistence.PersistentStore) Map(java.util.Map) ServiceReference(org.osgi.framework.ServiceReference)

Example 14 with PersistenceException

use of org.codice.ddf.persistence.PersistenceException in project ddf by codice.

the class UserService method getUser.

@Listener("/service/user")
public void getUser(final ServerSession remote, Message message) {
    ServerMessage.Mutable reply = new ServerMessageImpl();
    Map<String, Object> data = message.getDataAsMap();
    Subject subject = (Subject) bayeux.getContext().getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
    if (subject != null) {
        if (data == null || data.isEmpty()) {
            Map<String, Object> userMap = new HashMap<>();
            String username = SubjectUtils.getName(subject);
            userMap.put("username", username);
            userMap.put("isGuest", String.valueOf(subject.isGuest()));
            List<Map<String, Object>> preferencesList;
            try {
                preferencesList = persistentStore.get(PersistentStore.PREFERENCES_TYPE, "user = '" + username + "'");
                if (preferencesList.size() == 1) {
                    Map<String, Object> preferences = preferencesList.get(0);
                    JSONContext.Client jsonContext = new Jackson1JSONContextClient();
                    String json = (String) preferences.get("preferences_json_txt");
                    LOGGER.debug("preferences extracted JSON text:\n {}", json);
                    Map preferencesMap;
                    try {
                        preferencesMap = jsonContext.getParser().parse(new StringReader(json), Map.class);
                        userMap.put("preferences", preferencesMap);
                    } catch (ParseException e) {
                        LOGGER.info("ParseException while trying to convert persisted preferences for user {} from JSON", username, e);
                    }
                }
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to retrieve persisted preferences for user {}", username, e);
            }
            reply.put("user", userMap);
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/user", reply);
        } else {
            JSONContext.Server jsonContext = new Jackson1JSONContextServer();
            String json = jsonContext.getGenerator().generate(data);
            LOGGER.debug("preferences JSON text:\n {}", json);
            String username = SubjectUtils.getName(subject);
            PersistentItem item = new PersistentItem();
            item.addIdProperty(username);
            item.addProperty("user", username);
            item.addProperty("preferences_json", json);
            try {
                persistentStore.add(PersistentStore.PREFERENCES_TYPE, item);
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to persist preferences for user {}", username, e);
            }
        }
    } else {
        reply.put(Search.SUCCESSFUL, false);
        remote.deliver(serverSession, "/service/user", reply);
    }
}
Also used : PersistentItem(org.codice.ddf.persistence.PersistentItem) HashMap(java.util.HashMap) ServerMessage(org.cometd.bayeux.server.ServerMessage) Subject(ddf.security.Subject) JSONContext(org.cometd.common.JSONContext) ServerMessageImpl(org.cometd.server.ServerMessageImpl) StringReader(java.io.StringReader) PersistenceException(org.codice.ddf.persistence.PersistenceException) ParseException(java.text.ParseException) Jackson1JSONContextServer(org.cometd.server.Jackson1JSONContextServer) Jackson1JSONContextClient(org.cometd.common.Jackson1JSONContextClient) HashMap(java.util.HashMap) Map(java.util.Map) Listener(org.cometd.annotation.Listener)

Example 15 with PersistenceException

use of org.codice.ddf.persistence.PersistenceException in project ddf by codice.

the class ActivityController method deletePersistentActivity.

@Listener("/service/action")
public void deletePersistentActivity(ServerSession serverSession, ServerMessage serverMessage) {
    LOGGER.debug("\nServerSession: {}\nServerMessage: {}", serverSession, serverMessage);
    if (null == serverSession) {
        throw new IllegalArgumentException("ServerSession is null");
    }
    if (null == serverMessage) {
        throw new IllegalArgumentException("ServerMessage is null");
    }
    Subject subject = null;
    try {
        subject = SecurityUtils.getSubject();
    } catch (Exception e) {
        LOGGER.debug("Couldn't grab user subject from Shiro.", e);
    }
    String userId = getUserId(serverSession, subject);
    Map<String, Object> dataAsMap = serverMessage.getDataAsMap();
    if (dataAsMap != null) {
        Object activitiesPreCast = dataAsMap.get("data");
        Object[] activities = activitiesPreCast instanceof List ? ((List) activitiesPreCast).toArray() : (Object[]) activitiesPreCast;
        for (Object activityObject : activities) {
            Map activity = (Map) activityObject;
            String id = (String) activity.get("id");
            String action = (String) activity.get("action");
            if (action != null) {
                if (REMOVE_ACTION.equals(action)) {
                    //You can have a blank id for guest
                    if (id != null) {
                        try {
                            this.persistentStore.delete(PersistentStore.ACTIVITY_TYPE, "id = '" + id + "'");
                        } catch (PersistenceException e) {
                            throw new IllegalArgumentException("Unable to delete activity with id = " + id);
                        }
                    } else {
                        throw new IllegalArgumentException("Message id is null");
                    }
                } else if (CANCEL_ACTION.equals(action)) {
                    if (null == userId) {
                        throw new IllegalArgumentException("User ID is null");
                    }
                    if (null == id) {
                        throw new IllegalArgumentException("Metadata ID is null");
                    }
                    Map<String, Object> jsonPropMap = new HashMap<>();
                    jsonPropMap.put(ActivityEvent.DOWNLOAD_ID_KEY, id);
                    Event event = new Event(ActivityEvent.EVENT_TOPIC_DOWNLOAD_CANCEL, jsonPropMap);
                    eventAdmin.postEvent(event);
                }
            } else {
                throw new IllegalArgumentException("Message action is null.");
            }
        }
    } else {
        throw new IllegalArgumentException("Server Message is null.");
    }
}
Also used : PersistenceException(org.codice.ddf.persistence.PersistenceException) ActivityEvent(org.codice.ddf.activities.ActivityEvent) Event(org.osgi.service.event.Event) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Subject(org.apache.shiro.subject.Subject) PersistenceException(org.codice.ddf.persistence.PersistenceException) Listener(org.cometd.annotation.Listener)

Aggregations

PersistenceException (org.codice.ddf.persistence.PersistenceException)28 Map (java.util.Map)16 PersistentItem (org.codice.ddf.persistence.PersistentItem)10 ArrayList (java.util.ArrayList)9 IOException (java.io.IOException)7 Test (org.junit.Test)7 HashMap (java.util.HashMap)6 SolrServerException (org.apache.solr.client.solrj.SolrServerException)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 List (java.util.List)4 Listener (org.cometd.annotation.Listener)4 Date (java.util.Date)3 SolrClient (org.apache.solr.client.solrj.SolrClient)3 UpdateResponse (org.apache.solr.client.solrj.response.UpdateResponse)3 PersistentStore (org.codice.ddf.persistence.PersistentStore)3 Subject (ddf.security.Subject)2 StringReader (java.io.StringReader)2 ParseException (java.text.ParseException)2 Collection (java.util.Collection)2 Collectors (java.util.stream.Collectors)2