Search in sources :

Example 1 with PersistenceException

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

the class WorkspaceService method getWorkspaces.

@SuppressWarnings("unchecked")
@Listener("/service/workspaces")
public void getWorkspaces(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);
    String username = SubjectUtils.getName(subject);
    // No workspaces persisted for a guest user (whose username="")
    if (StringUtils.isNotBlank(username)) {
        if (data == null || data.isEmpty() || data.get("workspaces") == null) {
            List<Map<String, Object>> workspacesList = new ArrayList<Map<String, Object>>();
            try {
                workspacesList = persistentStore.get(PersistentStore.WORKSPACE_TYPE, "user = '" + username + "'");
                if (workspacesList.size() == 1) {
                    // Convert workspace's JSON representation back to nested maps of Map<String, Object>
                    Map<String, Object> workspaces = (Map<String, Object>) workspacesList.get(0);
                    JSONContext.Client jsonContext = new Jackson1JSONContextClient();
                    String json = (String) workspaces.get("workspaces_json_txt");
                    LOGGER.debug("workspaces extracted JSON text:\n {}", json);
                    Map<String, Object> workspacesMap;
                    try {
                        workspacesMap = jsonContext.getParser().parse(new StringReader(json), Map.class);
                        reply.putAll(workspacesMap);
                    } catch (ParseException e) {
                        LOGGER.info("ParseException while trying to convert persisted workspaces's for user {} from JSON", username, e);
                    }
                }
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to retrieve persisted workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        } else {
            LOGGER.debug("Persisting workspaces for username = {}", username);
            // Use JSON serializer so that only "data" component is serialized, not entire Message
            JSONContext.Server jsonContext = new Jackson1JSONContextServer();
            String json = jsonContext.getGenerator().generate(data);
            LOGGER.debug("workspaces JSON text:\n {}", json);
            PersistentItem item = new PersistentItem();
            item.addIdProperty(username);
            item.addProperty("user", username);
            item.addProperty("workspaces_json", json);
            try {
                persistentStore.add(PersistentStore.WORKSPACE_TYPE, item);
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to persist workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        }
    }
}
Also used : PersistentItem(org.codice.ddf.persistence.PersistentItem) ServerMessage(org.cometd.bayeux.server.ServerMessage) ArrayList(java.util.ArrayList) 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) Map(java.util.Map) Listener(org.cometd.annotation.Listener)

Example 2 with PersistenceException

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

the class NotificationController method deletePersistentNotification.

@Listener("/notification/action")
public void deletePersistentNotification(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[] notifications = (Object[]) dataAsMap.get("data");
        for (Object notificationObject : notifications) {
            Map notification = (Map) notificationObject;
            String id = (String) notification.get("id");
            String action = (String) notification.get("action");
            if (action != null) {
                if ("remove".equals(action)) {
                    //You can have a blank id for guest
                    if (id != null) {
                        try {
                            this.persistentStore.delete(PersistentStore.NOTIFICATION_TYPE, "id = '" + id + "'");
                        } catch (PersistenceException e) {
                            throw new IllegalArgumentException("Unable to delete notification with id = " + id);
                        }
                    } else {
                        throw new IllegalArgumentException("Message id is null");
                    }
                }
            } else {
                throw new IllegalArgumentException("Message action is null.");
            }
        }
    } else {
        throw new IllegalArgumentException("Server Message is null.");
    }
}
Also used : PersistenceException(org.codice.ddf.persistence.PersistenceException) 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)

Example 3 with PersistenceException

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

the class PersistentStoreImpl method get.

@Override
public // Returned Map will have suffixes in the key names - client is responsible for handling them
List<Map<String, Object>> get(String type, String cql) throws PersistenceException {
    if (StringUtils.isBlank(type)) {
        throw new PersistenceException("The type of object(s) to retrieve must be non-null and not blank, e.g., notification, metacard, etc.");
    }
    List<Map<String, Object>> results = new ArrayList<>();
    // Set Solr Core name to type and create/connect to Solr Core
    SolrClient solrClient = getSolrClient(type);
    if (solrClient == null) {
        throw new PersistenceException("Unable to create Solr client.");
    }
    SolrQueryFilterVisitor visitor = new SolrQueryFilterVisitor(solrClient, type);
    try {
        SolrQuery solrQuery;
        // If not cql specified, then return all items
        if (StringUtils.isBlank(cql)) {
            solrQuery = new SolrQuery("*:*");
        } else {
            Filter filter = CQL.toFilter(cql);
            solrQuery = (SolrQuery) filter.accept(visitor, null);
        }
        QueryResponse solrResponse = solrClient.query(solrQuery, METHOD.POST);
        long numResults = solrResponse.getResults().getNumFound();
        LOGGER.debug("numResults = {}", numResults);
        SolrDocumentList docs = solrResponse.getResults();
        for (SolrDocument doc : docs) {
            PersistentItem result = new PersistentItem();
            Collection<String> fieldNames = doc.getFieldNames();
            for (String name : fieldNames) {
                LOGGER.debug("field name = {} has value = {}", name, doc.getFieldValue(name));
                if (name.endsWith(PersistentItem.TEXT_SUFFIX) && doc.getFieldValues(name).size() > 1) {
                    result.addProperty(name, doc.getFieldValues(name).stream().filter(s -> s instanceof String).map(s -> (String) s).collect(Collectors.toSet()));
                } else if (name.endsWith(PersistentItem.XML_SUFFIX)) {
                    result.addXmlProperty(name, (String) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.TEXT_SUFFIX)) {
                    result.addProperty(name, (String) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.LONG_SUFFIX)) {
                    result.addProperty(name, (Long) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.INT_SUFFIX)) {
                    result.addProperty(name, (Integer) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.DATE_SUFFIX)) {
                    result.addProperty(name, (Date) doc.getFirstValue(name));
                } else if (name.endsWith(PersistentItem.BINARY_SUFFIX)) {
                    result.addProperty(name, (byte[]) doc.getFirstValue(name));
                } else {
                    LOGGER.debug("Not adding field {} because it has invalid suffix", name);
                }
            }
            results.add(result);
        }
    } catch (CQLException e) {
        throw new PersistenceException("CQLException while getting Solr data with cql statement " + cql, e);
    } catch (SolrServerException | IOException e) {
        throw new PersistenceException("SolrServerException while getting Solr data with cql statement " + cql, e);
    }
    return results;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Date(java.util.Date) SolrDocumentList(org.apache.solr.common.SolrDocumentList) SolrClientFactory(org.codice.solr.factory.SolrClientFactory) SolrClientFactoryImpl(org.codice.solr.factory.impl.SolrClientFactoryImpl) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) ArrayList(java.util.ArrayList) PersistenceException(org.codice.ddf.persistence.PersistenceException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) Future(java.util.concurrent.Future) METHOD(org.apache.solr.client.solrj.SolrRequest.METHOD) CQL(org.geotools.filter.text.cql2.CQL) SolrQueryFilterVisitor(org.codice.solr.query.SolrQueryFilterVisitor) Map(java.util.Map) CQLException(org.geotools.filter.text.cql2.CQLException) Logger(org.slf4j.Logger) PersistentItem(org.codice.ddf.persistence.PersistentItem) Collection(java.util.Collection) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) SolrClient(org.apache.solr.client.solrj.SolrClient) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) SolrDocument(org.apache.solr.common.SolrDocument) List(java.util.List) PersistentStore(org.codice.ddf.persistence.PersistentStore) SolrQuery(org.apache.solr.client.solrj.SolrQuery) Filter(org.opengis.filter.Filter) UpdateResponse(org.apache.solr.client.solrj.response.UpdateResponse) SolrInputDocument(org.apache.solr.common.SolrInputDocument) PersistentItem(org.codice.ddf.persistence.PersistentItem) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ArrayList(java.util.ArrayList) SolrQueryFilterVisitor(org.codice.solr.query.SolrQueryFilterVisitor) SolrDocumentList(org.apache.solr.common.SolrDocumentList) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) Date(java.util.Date) SolrDocument(org.apache.solr.common.SolrDocument) SolrClient(org.apache.solr.client.solrj.SolrClient) Filter(org.opengis.filter.Filter) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) PersistenceException(org.codice.ddf.persistence.PersistenceException) CQLException(org.geotools.filter.text.cql2.CQLException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 4 with PersistenceException

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

the class TestDataUsage method testGetPersistentCronTimeDefaultWithException.

@Test
public void testGetPersistentCronTimeDefaultWithException() throws PersistenceException {
    List<Map<String, Object>> mapList = new ArrayList<>();
    Map<String, Object> stringObjectMap = new HashMap<>();
    mapList.add(stringObjectMap);
    when(persistentStore.get(anyString())).thenThrow(new PersistenceException());
    dataUsage.init();
    assertThat(dataUsage.cronTime(), is(DEFAULT_TIME));
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PersistenceException(org.codice.ddf.persistence.PersistenceException) Matchers.anyString(org.mockito.Matchers.anyString) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 5 with PersistenceException

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

the class AdminAlertImpl method getAlerts.

@Override
public List<Map<String, Object>> getAlerts() {
    List<Map<String, Object>> alerts = new ArrayList<>();
    try {
        List<Map<String, Object>> results = persistentStore.get("alerts", activeAlertQuery);
        if (!results.isEmpty()) {
            for (Map<String, Object> item : results) {
                item = PersistentItem.stripSuffixes(item);
                // strings/sets of strings. Single value sets will come back as strings.
                if (item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY) instanceof String) {
                    item.put(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY, Collections.singleton(item.get(SystemNotice.SYSTEM_NOTICE_DETAILS_KEY)));
                }
                escapeStrings(item);
                alerts.add(item);
            }
        }
    } catch (PersistenceException pe) {
        LOGGER.debug("Error retrieving system alert.", pe);
        return Collections.singletonList(new Alert("unable_to_retrieve_alerts", NoticePriority.CRITICAL, "Persistent Storage Not Responding. Could Not Retrieve Alerts.", Collections.singleton("Critical alerts may be present, but not displayed because the persistent storage is not responding.")).getProperties());
    }
    alerts.sort((map1, map2) -> new Alert(map1).getPriority().value() >= new Alert(map2).getPriority().value() ? -1 : 1);
    return alerts;
}
Also used : ArrayList(java.util.ArrayList) PersistenceException(org.codice.ddf.persistence.PersistenceException) Alert(org.codice.ddf.system.alerts.Alert) HashMap(java.util.HashMap) Map(java.util.Map)

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