Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves the Resource in the database with the specified id.
 * @param id/* ww w.  ja v  a 2  s  . c  o m*/
 * @return a Resource that may be empty
 */
public Resource retrieveResource(long id) {
    //TODO move this method elsewhere, it's here because extension of Resource Class are not queried if it were in controler-resource package
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Resource resource = (Resource) em.createQuery("from Resource where id = ?").setParameter(1, id)
                .getSingleResult();
        tx.commit();
        ////em.close();
        return resource;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveResource.retrieveResource] unable to retrieve Resource" + " id : " + id
                + " cause : " + e.getMessage());
        return new Resource();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves an annotationStatus/*from www  . jav a 2 s.  co  m*/
 * @param id
 * @return
 */
public AnnotationStatus retrieveAnnotationStatus(long id) {
    //   EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        AnnotationStatus _synchro = em.find(AnnotationStatus.class, id);
        tx.commit();
        if (_synchro != null)
            return _synchro;
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " id : " + id);
        return new AnnotationStatus();
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println(
                "[RetrieveAnnotationStatus.retrieveAnnotationStatus] unable to retrieve AnnotationStatus"
                        + " id : " + id + " cause : " + e.getMessage());
        return new AnnotationStatus();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Computes the number of annotations for associated to a specified Resource through its url
 * @param _url/*from  www  .jav  a2s  .c o m*/
 * @return
 */
public long computeNbAnnotations(String _url) {
    long nb = 0;
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.computeNbAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return nb;
        }
        Object nb_annotations = em.createQuery(
                " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?")
                .setParameter(1, _uri).getSingleResult();
        //System.out.println("[RetrieveAnnotation.computeNbAnnotations] nb_annotations : " + nb_annotations + " classe : " + nb_annotations.getClass().getSimpleName());
        tx.commit();
        if (nb_annotations instanceof Long) {
            nb = ((Long) nb_annotations).longValue();
        }
        return nb;
    } catch (Exception e) {
        tx.rollback();
        return nb;
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves all the annotations about a specified Resource, by ascendant or descendant chronological order
 * @param _url/*from   ww  w .  jav a2 s.c  o  m*/
 * @param asc
 * @return
 */
public List<Annotation> retrieveAnnotations(String _url, boolean asc) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " order by annotation.id desc";
        if (asc)
            order_by_clause = " order by annotation.id asc";
        List<Annotation> annotations = ((List<Annotation>) em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?"
                        + order_by_clause)
                .setParameter(1, _uri).getResultList());
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves all the annotations associated to a Resource specified by its URL, grouped by annotationStatus
 * @param _url/* www  .ja v a  2 s .  c o  m*/
 * @param asc
 * @return
 */
public List<Annotation> retrieveAnnotationsGroupByStatus(String _url, boolean asc) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " annotation.id desc";
        if (asc)
            order_by_clause = " annotation.id asc";
        List<Annotation> annotations = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.status,"
                        + order_by_clause)
                .setParameter(1, _uri).getResultList();
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves all the annotations associated to a specified Resource through its URL, ordered by FirstAuthor
 * @param _url/*ww  w. j  a  v a2  s.  c o  m*/
 * @param asc
 * @return
 */
public List<Annotation> retrieveAnnotationsGroupByFirstAuthor(String _url, boolean asc) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " annotation.id desc";
        if (asc)
            order_by_clause = " annotation.id asc";
        List<Annotation> annotations = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.creator,"
                        + order_by_clause)
                .setParameter(1, _uri).getResultList();
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

From source file:com.doculibre.constellio.wicket.panels.admin.indexing.AdminIndexingPanel.java

public AdminIndexingPanel(String id) {
    super(id);/*ww  w .  j a  v  a 2 s.  co  m*/
    sizeDisk = 0;
    indexedRecords = 0;

    add(new AjaxSelfUpdatingTimerBehavior(Duration.ONE_SECOND));
    // add(new AbstractAjaxTimerBehavior(Duration.ONE_SECOND) {
    // @Override
    // protected void onTimer(AjaxRequestTarget target) {
    // // Do nothing, will prevent page from expiring
    // }
    // });

    connectorsModel = new LoadableDetachableModel() {
        @Override
        protected Object load() {
            List<ConnectorInstance> connectors;
            RecordCollection collection = getRecordCollection();
            if (collection.isFederationOwner()) {
                FederationServices federationServices = ConstellioSpringUtils.getFederationServices();
                connectors = federationServices.listConnectors(collection);
            } else {
                connectors = new ArrayList<ConnectorInstance>(collection.getConnectorInstances());
            }
            return connectors;
        }
    };

    manageConnectorsLink = new Link("manageConnectorsLink") {
        @Override
        public void onClick() {
            AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent(
                    AdminCollectionPanel.class);
            adminCollectionPanel.setSelectedTab(AdminCollectionPanel.CONNECTORS_MANAGEMENT_PANEL);
        }

        @Override
        public boolean isVisible() {
            boolean visible = super.isVisible();
            if (visible) {
                RecordCollection collection = getRecordCollection();
                visible = collection.getConnectorInstances().isEmpty();
            }
            return visible;
        }
    };

    synchronizeIndexFieldsLink = new Link("synchronizeIndexFieldsLink") {
        @Override
        public void onClick() {
            RecordCollection collection = getRecordCollection();

            RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
            SolrServices solrServices = ConstellioSpringUtils.getSolrServices();

            solrServices.updateSchemaFields(collection);
            solrServices.initCore(collection);

            EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
            if (!entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().begin();
            }
            collectionServices.markSynchronized(collection);
            entityManager.getTransaction().commit();

            IndexingManager indexingManager = IndexingManager.get(collection);
            if (!indexingManager.isActive()) {
                indexingManager.startIndexing();
            }
        }

        @Override
        public boolean isVisible() {
            boolean visible = super.isVisible();
            if (visible) {
                RecordCollection collection = getRecordCollection();
                visible = collection.isSynchronizationRequired();
            }
            return visible;
        }
    };

    manageIndexFieldsLink = new Link("manageIndexFieldsLink") {
        @Override
        public void onClick() {
            AdminCollectionPanel adminCollectionPanel = (AdminCollectionPanel) findParent(
                    AdminCollectionPanel.class);
            adminCollectionPanel.setSelectedTab(AdminCollectionPanel.INDEX_FIELDS_MANAGEMENT_PANEL);
        }
    };

    recordCountLabel = new Label("recordCount", new LoadableDetachableModel() {
        @Override
        protected Object load() {
            RecordCollection collection = getRecordCollection();
            return StatusManager.countTraversedRecords(collection);
        }
    });

    deleteAllLink = new Link("deleteAllLink") {
        @Override
        public void onClick() {
            RecordCollection collection = getRecordCollection();
            RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
            FederationServices federationServices = ConstellioSpringUtils.getFederationServices();

            ReadWriteLock collectionLock = recordServices.getLock(collection.getName());
            collectionLock.writeLock().lock();
            try {

                ConstellioPersistenceUtils.beginTransaction();
                recordServices.markRecordsForDeletion(collection);
                if (collection.isFederationOwner()) {
                    List<RecordCollection> includedCollections = federationServices
                            .listIncludedCollections(collection);
                    for (RecordCollection includedCollection : includedCollections) {
                        recordServices.markRecordsForDeletion(includedCollection);
                    }
                }
                SolrServer solrServer = SolrCoreContext.getSolrServer(collection);
                try {
                    solrServer.commit();
                    solrServer.optimize();
                } catch (Throwable t) {
                    try {
                        solrServer.rollback();
                    } catch (Exception e) {
                        throw new RuntimeException(t);
                    }
                }
            } finally {
                try {
                    ConstellioPersistenceUtils.finishTransaction(false);
                } finally {
                    collectionLock.writeLock().unlock();
                }
            }

            // RecordCollection collection = getRecordCollection();
            //
            // ConnectorManagerServices connectorManagerServices =
            // ConstellioSpringUtils.getConnectorManagerServices();
            // ConnectorManager connectorManager =
            // connectorManagerServices.getDefaultConnectorManager();
            // for (ConnectorInstance connectorInstance :
            // collection.getConnectorInstances()) {
            // String connectorName = connectorInstance.getName();
            // connectorManagerServices.disableConnector(connectorManager,
            // connectorName);
            // }
            //
            // IndexingManager indexingManager =
            // IndexingManager.get(collection);
            // indexingManager.deleteAll();
            // indexingManager.optimize();
            // while (indexingManager.isOptimizing()) {
            // try {
            // Thread.sleep(200);
            // } catch (InterruptedException e) {
            // e.printStackTrace();
            // }
            // }
        }

        @Override
        protected CharSequence getOnClickScript(CharSequence url) {
            String confirmMsg = getLocalizer().getString("confirmDeleteAll", AdminIndexingPanel.this)
                    .replace("'", "\\'");
            return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                    + "';} else { return false; }";
        }
    };

    indexedRecordCountLabel = new Label("indexedRecordCount", new LoadableDetachableModel() {
        @Override
        protected Object load() {
            RecordCollection collection = getRecordCollection();
            return StatusManager.countIndexedRecords(collection);
        }
    });

    controlIndexingButtons = new WebMarkupContainer("controlIndexingButtons");
    controlIndexingButtons.setOutputMarkupId(true);

    reindexAllLink = new Link("reindexAllLink") {
        @Override
        public void onClick() {
            RecordCollection collection = getRecordCollection();
            final String collectioName = collection.getName();
            final Long collectionId = collection.getId();

            new Thread() {
                @Override
                public void run() {
                    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
                    ReadWriteLock collectionLock = recordServices.getLock(collectioName);
                    collectionLock.writeLock().lock();
                    try {
                        EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
                        if (!entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().begin();
                        }

                        RecordCollectionServices collectionServices = ConstellioSpringUtils
                                .getRecordCollectionServices();
                        FederationServices federationServices = ConstellioSpringUtils.getFederationServices();
                        RecordCollection collection = collectionServices.get(collectionId);
                        try {
                            recordServices.markRecordsForUpdateIndex(collection);
                            if (collection.isFederationOwner()) {
                                List<RecordCollection> includedCollections = federationServices
                                        .listIncludedCollections(collection);
                                for (RecordCollection includedCollection : includedCollections) {
                                    recordServices.markRecordsForUpdateIndex(includedCollection);
                                }
                            }
                            SolrServer solrServer = SolrCoreContext.getSolrServer(collection);
                            try {
                                // solrServer.commit();
                                solrServer.optimize();
                            } catch (Throwable t) {
                                try {
                                    solrServer.rollback();
                                } catch (Exception e) {
                                    throw new RuntimeException(t);
                                }
                            }
                        } finally {
                            ConstellioPersistenceUtils.finishTransaction(false);
                        }
                    } finally {
                        collectionLock.writeLock().unlock();
                    }
                }

            }.start();
        }

        @Override
        protected CharSequence getOnClickScript(CharSequence url) {
            String confirmMsg = getLocalizer().getString("confirmReindexAll", AdminIndexingPanel.this)
                    .replace("'", "\\'");
            return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                    + "';} else { return false; }";
        }
    };

    resumeIndexingLink = new Link("resumeIndexingLink") {
        @Override
        public void onClick() {
            RecordCollection collection = getRecordCollection();
            IndexingManager indexingManager = IndexingManager.get(collection);
            if (!indexingManager.isActive()) {
                indexingManager.startIndexing(false);
            }
        }

        @Override
        public boolean isVisible() {
            // boolean visible = super.isVisible();
            // if (visible) {
            // RecordCollection collection = getRecordCollection();
            // IndexingManager indexingManager =
            // IndexingManager.get(collection);
            // visible = !collection.isSynchronizationRequired() &&
            // !indexingManager.isActive();
            // }
            // return visible;
            return false;
        }
    };

    optimizeLink = new Link("optimizeLink") {
        @Override
        public void onClick() {
            RecordCollection collection = getRecordCollection();
            final Long collectionId = collection.getId();
            new Thread() {
                @Override
                public void run() {
                    RecordCollectionServices collectionServices = ConstellioSpringUtils
                            .getRecordCollectionServices();
                    RecordCollection collection = collectionServices.get(collectionId);
                    SolrServer solrServer = SolrCoreContext.getSolrServer(collection);
                    try {
                        solrServer.optimize();
                    } catch (Throwable t) {
                        try {
                            solrServer.rollback();
                        } catch (Exception e) {
                            throw new RuntimeException(t);
                        }
                    }
                    // IndexingManager indexingManager =
                    // IndexingManager.get(collection);
                    // if (indexingManager.isActive() &&
                    // !indexingManager.isOptimizing()) {
                    // indexingManager.optimize();
                    // }
                }
            }.start();
        }

        @Override
        protected CharSequence getOnClickScript(CharSequence url) {
            String confirmMsg = getLocalizer().getString("confirmOptimize", AdminIndexingPanel.this)
                    .replace("'", "\\'");
            return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                    + "';} else { return false; }";
        }

        @Override
        public boolean isVisible() {
            // boolean visible = super.isVisible();
            // if (visible) {
            // RecordCollection collection = getRecordCollection();
            // IndexingManager indexingManager =
            // IndexingManager.get(collection);
            // visible = indexingManager.isActive();
            // }
            // return visible;
            return true;
        }

        @Override
        public boolean isEnabled() {
            // boolean enabled = super.isEnabled();
            // if (enabled) {
            // RecordCollection collection = getRecordCollection();
            // IndexingManager indexingManager =
            // IndexingManager.get(collection);
            // enabled = indexingManager.isActive() &&
            // !indexingManager.isOptimizing();
            // }
            // return enabled;
            return true;
        }
    };

    indexSizeOnDiskLabel = new Label("indexSizeOnDisk", new LoadableDetachableModel() {
        @Override
        protected Object load() {
            RecordCollection collection = getRecordCollection();
            return StatusManager.getSizeOnDisk(collection);
        }
    });

    connectorTraversalStatesListView = new ListView("connectorTraversalStates", connectorsModel) {
        @Override
        protected void populateItem(ListItem item) {
            ConnectorInstance connectorInstance = (ConnectorInstance) item.getModelObject();
            final ReloadableEntityModel<ConnectorInstance> connectorInstanceModel = new ReloadableEntityModel<ConnectorInstance>(
                    connectorInstance);
            Label displayNameLabel = new Label("displayName", connectorInstance.getDisplayName());
            Label lastTraversalDateLabel = new Label("latestTraversalDate", new LoadableDetachableModel() {
                @Override
                protected Object load() {
                    ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                    Date lastTraversalDate = StatusManager.getLastTraversalDate(connectorInstance);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    return lastTraversalDate != null ? sdf.format(lastTraversalDate) : "---";
                }

                @Override
                public void detach() {
                    connectorInstanceModel.detach();
                    super.detach();
                }
            });

            Link restartTraversalLink = new Link("restartTraversalLink") {
                @Override
                public void onClick() {
                    ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                    ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils
                            .getConnectorManagerServices();
                    ConnectorManager connectorManager = connectorManagerServices.getDefaultConnectorManager();
                    connectorManagerServices.restartTraversal(connectorManager, connectorInstance.getName());
                }

                @Override
                protected CharSequence getOnClickScript(CharSequence url) {
                    String confirmMsg = getLocalizer()
                            .getString("confirmRestartTraversal", AdminIndexingPanel.this).replace("'", "\\'");
                    return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                            + "';} else { return false; }";
                }

                @Override
                public boolean isVisible() {
                    ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                    RecordCollection connectorInstanceCollection = connectorInstance.getRecordCollection();
                    ConstellioUser user = ConstellioSession.get().getUser();
                    return super.isVisible() && user.hasAdminPermission(connectorInstanceCollection);
                }
            };

            Link disableConnectorLink = new Link("disableConnectorLink") {
                @Override
                public void onClick() {
                    ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                    String connectorName = connectorInstance.getName();
                    ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils
                            .getConnectorManagerServices();
                    ConnectorManager connectorManager = connectorManagerServices.getDefaultConnectorManager();
                    connectorManagerServices.disableConnector(connectorManager, connectorName);
                }

                @Override
                protected CharSequence getOnClickScript(CharSequence url) {
                    String confirmMsg = getLocalizer()
                            .getString("confirmDisableConnector", AdminIndexingPanel.this).replace("'", "\\'");
                    return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                            + "';} else { return false; }";
                }

                @Override
                public boolean isVisible() {
                    boolean visible = super.isVisible();
                    if (visible) {
                        ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                        String connectorName = connectorInstance.getName();
                        ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils
                                .getConnectorManagerServices();
                        ConnectorManager connectorManager = connectorManagerServices
                                .getDefaultConnectorManager();
                        visible = connectorManagerServices.isConnectorEnabled(connectorManager, connectorName);
                        if (visible) {
                            RecordCollection connectorInstanceCollection = connectorInstance
                                    .getRecordCollection();
                            ConstellioUser user = ConstellioSession.get().getUser();
                            visible = user.hasAdminPermission(connectorInstanceCollection);
                        }
                    }
                    return visible;
                }
            };

            Link enableConnectorLink = new Link("enableConnectorLink") {
                @Override
                public void onClick() {
                    ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                    String connectorName = connectorInstance.getName();
                    ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils
                            .getConnectorManagerServices();
                    ConnectorManager connectorManager = connectorManagerServices.getDefaultConnectorManager();
                    connectorManagerServices.enableConnector(connectorManager, connectorName);
                }

                @Override
                protected CharSequence getOnClickScript(CharSequence url) {
                    String confirmMsg = getLocalizer()
                            .getString("confirmEnableConnector", AdminIndexingPanel.this).replace("'", "\\'");
                    return "if (confirm('" + confirmMsg + "')) { window.location.href='" + url
                            + "';} else { return false; }";
                }

                @Override
                public boolean isVisible() {
                    boolean visible = super.isVisible();
                    if (visible) {
                        ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                        String connectorName = connectorInstance.getName();
                        ConnectorManagerServices connectorManagerServices = ConstellioSpringUtils
                                .getConnectorManagerServices();
                        ConnectorManager connectorManager = connectorManagerServices
                                .getDefaultConnectorManager();
                        visible = !connectorManagerServices.isConnectorEnabled(connectorManager, connectorName);
                        if (visible) {
                            RecordCollection connectorInstanceCollection = connectorInstance
                                    .getRecordCollection();
                            ConstellioUser user = ConstellioSession.get().getUser();
                            visible = user.hasAdminPermission(connectorInstanceCollection);
                        }
                    }
                    return visible;
                }
            };

            item.add(displayNameLabel);
            item.add(lastTraversalDateLabel);
            item.add(restartTraversalLink);
            item.add(disableConnectorLink);
            item.add(enableConnectorLink);
        }
    };

    latestIndexedRecordsTextArea = new LoggingTextArea("latestIndexedRecordsTextArea",
            new LoadableDetachableModel() {
                @Override
                protected Object load() {
                    RecordCollection collection = getRecordCollection();
                    return StatusManager.listLastIndexedRecords(collection);
                }
            }, refreshTimeMillis);

    connectorTraversalTextAreasListView = new ListView("connectorTraversalTextAreas", connectorsModel) {
        @Override
        protected void populateItem(ListItem item) {
            ConnectorInstance connectorInstance = (ConnectorInstance) item.getModelObject();
            final ReloadableEntityModel<ConnectorInstance> connectorInstanceModel = new ReloadableEntityModel<ConnectorInstance>(
                    connectorInstance);
            Label displayNameLabel = new Label("displayName", connectorInstance.getDisplayName());

            LoggingTextArea traversalTextArea = new LoggingTextArea("traversalTextArea",
                    new LoadableDetachableModel() {
                        @Override
                        protected Object load() {
                            ConnectorInstance connectorInstance = connectorInstanceModel.getObject();
                            return StatusManager.listLastTraversedRecords(connectorInstance);
                        }
                    }, refreshTimeMillis) {
                @Override
                public void detachModels() {
                    connectorInstanceModel.detach();
                    super.detachModels();
                }
            };

            item.add(displayNameLabel);
            item.add(traversalTextArea);
        }
    };
    // connectorTextAreasListView.setReuseItems(true);

    add(manageConnectorsLink);
    add(synchronizeIndexFieldsLink);
    add(manageIndexFieldsLink);
    add(recordCountLabel);
    add(deleteAllLink);
    add(indexedRecordCountLabel);
    add(controlIndexingButtons);
    controlIndexingButtons.add(reindexAllLink);
    controlIndexingButtons.add(resumeIndexingLink);
    controlIndexingButtons.add(optimizeLink);
    add(indexSizeOnDiskLabel);
    add(connectorTraversalStatesListView);
    add(latestIndexedRecordsTextArea);
    add(connectorTraversalTextAreasListView);

    /*
     * Quotas Part of the code :
     * antoine.timonnier@gmail.com
     */

    //Loading the size of the disk
    IModel model1 = new LoadableDetachableModel() {
        protected Object load() {
            return getsizeDisk();
        }
    };

    //Loading the number of documents indexed
    IModel model2 = new LoadableDetachableModel() {
        protected Object load() {
            return getindexedRecords();
        }
    };

    //Boolean that is true if both of the quotas are reached
    boolean bothQuotas = false;
    QuotasManagerImpl quotasManager = new QuotasManagerImpl();
    //TODO connect quotas manager with the quotas.properties
    /*double quotaSizeDisk = quotasManager.getQuotaSizeDisk();
    double quotaIndexedRecords = quotasManager.getQuotaIndexedRecords();
    double quotaPercentage = quotasManager.getQuotaPercentage();*/
    double quotaSizeDisk = 1;
    double quotaIndexedRecords = 1;
    double quotaPercentage = 70;
    double percentageSizeDisk = (sizeDisk * 100) / quotaSizeDisk;
    double percentageIndexedRecords = (indexedRecords * 100) / quotaIndexedRecords;

    //if the size of the disk is upper the quota percentage and doesn't reach the quota (lower than 100%)
    if (quotaPercentage < percentageSizeDisk && percentageSizeDisk < 100) {
        final String textPercentageSizeDisk = "Vous tes rendu  " + Double.toString(percentageSizeDisk)
                + "% de votre quota d'espace disque, veuillez contacter un administrateur !";
        configurePopUp(popUpPercentageSizeDisk, textPercentageSizeDisk, "Attention");
    }
    add(popUpPercentageSizeDisk);

    //if the number of doc indexed is upper the quota percentage and doesn't reach the quota (lower than 100%)
    if (quotaIndexedRecords < percentageIndexedRecords && percentageIndexedRecords < 100) {
        final String textPercentageIndexedRecords = "Vous tes rendu  " + Double.toString(percentageSizeDisk)
                + "% de votre quota de nombre de documents indexs, veuillez contacter un administrateur !";
        configurePopUp(popUpPercentageIndexedRecords, textPercentageIndexedRecords, "Attention");
    }
    add(popUpPercentageIndexedRecords);

    //Adding a pop up if both of the quotas are reached
    popUpBothQuotas = new ModalWindow("popUpBothQuotas");
    if (sizeDisk > quotaSizeDisk && indexedRecords > quotaIndexedRecords) {
        bothQuotas = true;
        // Sending the email
        // TODO sendEmail(String hostName, int smtpPort,
        // DefaultAuthenticator authenticator, String sender, String
        // subject, String message, String receiver);
        // TODO lock the indexing
        //Configuration of the popUp
        final String textBothQuotas = "Vous avez dpass votre quota d'espace disque et votre quotat de document indexs, veuillez contacter un administrateur";
        configurePopUp(popUpBothQuotas, textBothQuotas, "Attention");
    }
    add(popUpBothQuotas);

    //Adding a pop up if the size disk quota is reached
    popUpSizeDisk = new ModalWindow("popUpSizeDisk");
    boolean sizeDiskSuperior = sizeDisk > quotaSizeDisk;
    if (sizeDiskSuperior && bothQuotas == false) {
        /* Sending the email
        try {
           sendEmail("smtp.googlemail.com", 465, new DefaultAuthenticator("antoine.timonnier@gmail.com","quenellede300"), "antoine.timonnier@gmail.com", "constellio", "blabla", "antoine.timonnier@gmail.com");
        } catch (EmailException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        } */
        // TODO lock
        // Configuration of the popup
        final String textSizeDisk = "Attention, vous avez dpass votre quota d'espace disque, veuillez contacter un administrateur";
        configurePopUp(popUpSizeDisk, textSizeDisk, "Attention");
    }
    add(popUpSizeDisk);

    //Adding a pop up if the indexed records quota is reached
    popUpIndexedRecords = new ModalWindow("popUpIndexedRecords");
    if (indexedRecords > quotaIndexedRecords && bothQuotas == false) {
        // sending the email
        // TODO sendEmail(String hostName, int smtpPort,
        // DefaultAuthenticator authenticator, String sender, String
        // subject, String message, String receiver);
        // TODO lock
        // Configuration of the popup
        final String textIndexedRecords = "Attention, vous avez dpass votre quota de documents indexs, veuillez contacter un administrateur. boolean both = "
                + bothQuotas;
        configurePopUp(popUpIndexedRecords, textIndexedRecords, "Attention");
    }
    add(popUpIndexedRecords);

}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a specified quantity of Annotations associated to a Resource specified by its URL
 * @param _url//from   w  w w  .ja va 2  s. c  o  m
 * @param asc
 * @param first_indice
 * @param max_results
 * @return
 */
public List<Annotation> retrieveAnnotations(String _url, boolean asc, int first_indice, int max_results) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " order by annotation.id desc";
        if (asc)
            order_by_clause = " order by annotation.id asc";
        Query _query = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=?"
                        + order_by_clause)
                .setParameter(1, _uri);
        _query.setFirstResult(first_indice);
        _query.setMaxResults(max_results);
        List<Annotation> annotations = _query.getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Tests if an agent has expressed a Spaming on a resource
 * @param _creator/*from w ww.j  a  v a2  s . c om*/
 * @param _url_to_test
 * @return
 */
public boolean spamExpressed(Agent _creator, String _url_to_test) {
    long nb = 0;
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url_to_test)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            System.out.println("[RetrieveAnnotation.spamExpressed] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url_to_test);
            return false;
        }
        AnnotationStatus status_spam = (AnnotationStatus) em
                .createQuery("from AnnotationStatus where label = ?").setParameter(1, "Spam").getSingleResult();
        if (status_spam != null) {
            Object nb_annotations_troll = em.createQuery(
                    " select count(distinct annotation.id) from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? and annotation.creator=? and annotation.status=?")
                    .setParameter(1, _uri).setParameter(2, _creator).setParameter(3, status_spam)
                    .getSingleResult();
            if (nb_annotations_troll instanceof Long) {
                nb = ((Long) nb_annotations_troll).longValue();
            }
        }
        tx.commit();
        if (nb > 0)
            return true;
        else
            return false;
    } catch (Exception e) {
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.spamExpressed] unable to retrieve Annotations" + " on url : "
                + _url_to_test + " cause : " + e.getMessage());
        return false; //to prevent to express its opinion if the system fails
    }
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Retrieves a specified quantity of annotations associated to a Resource specified by its URL and ordered by AnnotationStatus
 * @param _url//  w  w w .ja v  a 2 s . co  m
 * @param asc
 * @param first_indice
 * @param max_results
 * @return
 */
public List<Annotation> retrieveAnnotationsGroupByStatus(String _url, boolean asc, int first_indice,
        int max_results) {
    //EntityManagerFactory emf = this.setEMF();
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        URI _uri = (URI) em.createQuery("from URI where effectiveURI = ?").setParameter(1, _url)
                .getSingleResult();
        if (_uri == null) {
            tx.commit();
            //   //em.close();
            System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                    + " cause : there is no uri " + _url);
            return new ArrayList<Annotation>();
        }
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotated as annotated inner join annotated.representsResource as uri where uri=?").setParameter(1, _uri).getResultList();
        String order_by_clause = " annotation.id desc";
        if (asc)
            order_by_clause = " annotation.id asc";
        Query _query = em.createQuery(
                "select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? order by annotation.status,"
                        + order_by_clause)
                .setParameter(1, _uri);
        _query.setFirstResult(first_indice);
        _query.setMaxResults(max_results);
        List<Annotation> annotations = _query.getResultList();
        //List annotations = em.createQuery("select distinct annotation from Annotation as annotation inner join annotation.annotatedURIs as uri where uri=? group by annotation.status" ).setParameter(1, _uri).getResultList();
        tx.commit();
        //em.close();
        return annotations;
    } catch (Exception e) {
        //tx.commit();
        tx.rollback();
        //em.close();
        System.out.println("[RetrieveAnnotation.retrieveAnnotations] unable to retrieve Annotations"
                + " cause : " + e.getMessage());
        return new ArrayList<Annotation>();
    }
}