org.ektorp.CouchDbConnector - java examples

Here are the examples of the java api org.ektorp.CouchDbConnector taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

92 Examples 7

19 View Complete Implementation : TypedRepoConnectionManager.java
Copyright Apache License 2.0
Author : cfibmers
protected abstract void initRepo(CouchDbConnector couchdbconnector, boolean createIfNotExist);

19 View Complete Implementation : CouchDbRepositorySupportConstructionTest.java
Copyright Apache License 2.0
Author : helun
public clreplaced CouchDbRepositorySupportConstructionTest {

    CouchDbConnector db;

    @Before
    public void setUp() throws Exception {
        System.clearProperty(DesignDoreplacedent.UPDATE_ON_DIFF);
        System.clearProperty(DesignDoreplacedent.AUTO_UPDATE_VIEW_ON_CHANGE);
        db = mock(CouchDbConnector.clreplaced, new ThrowsException(new UnsupportedOperationException("This interaction was not expected on this mock")));
        doNothing().when(db).createDatabaseIfNotExists();
    }

    @After
    public void tearDown() {
        System.clearProperty(DesignDoreplacedent.UPDATE_ON_DIFF);
        System.clearProperty(DesignDoreplacedent.AUTO_UPDATE_VIEW_ON_CHANGE);
    }

    @Test
    public void given_design_doc_and_not_createIfExists_constructor_should_not_call_createDatabaseIfNotExists() {
        final String designDoc = "my_design_doc";
        new CouchDbRepositorySupport<CouchDbRepositorySupportTest.TestDoc>(CouchDbRepositorySupportTest.TestDoc.clreplaced, db, designDoc, false);
        verify(db, never()).createDatabaseIfNotExists();
    }

    @Test
    public void given_design_doc_andt_createIfExists_constructor_should_call_createDatabaseIfNotExists() {
        final String designDoc = "my_design_doc";
        new CouchDbRepositorySupport<CouchDbRepositorySupportTest.TestDoc>(CouchDbRepositorySupportTest.TestDoc.clreplaced, db, designDoc, true);
        verify(db, times(1)).createDatabaseIfNotExists();
    }
}

19 View Complete Implementation : CouchDbConnectionManager.java
Copyright Apache License 2.0
Author : cfibmers
public void setDb(CouchDbConnector db) {
    this.db = db;
}

19 View Complete Implementation : CouchProfileService.java
Copyright Apache License 2.0
Author : pac4j
public void setCouchDbConnector(final CouchDbConnector couchDbConnector) {
    this.couchDbConnector = couchDbConnector;
}

19 View Complete Implementation : CouchDbStore.java
Copyright Apache License 2.0
Author : apache
/**
 * Implements a CouchDb store. <br/>
 * <p>
 * Operates in At-most once recovery mode.
 * @displayName CouchDb Store
 * @category Output
 * @tags couchdb
 * @since 0.3.5
 */
public clreplaced CouchDbStore implements Connectable {

    /**
     * default value: http://localhost:5984
     */
    private String dbUrl;

    private String userName;

    private String preplacedword;

    @NotNull
    private String dbName;

    private transient CouchDbConnector dbConnector;

    private transient StdCouchDbInstance couchInstance;

    /**
     * Sets the database URL.
     *
     * @param dbUrl database url.
     */
    public void setDbUrl(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    /**
     * Sets the database user.
     *
     * @param userName user name.
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * Sets the preplacedword of database user.
     *
     * @param preplacedword preplacedword of the database user.
     */
    public void setPreplacedword(String preplacedword) {
        this.preplacedword = preplacedword;
    }

    /**
     * Sets the database.
     *
     * @param dbName name of the database.
     */
    public void setDbName(@Nonnull String dbName) {
        this.dbName = dbName;
    }

    /**
     * Returns if a doreplacedent identified by the doreplacedent id is present in the database or not.
     *
     * @param docId doreplacedent id.
     * @return true if the doreplacedent is in the database; false otherwise.
     */
    public boolean containsDoreplacedent(String docId) {
        return dbConnector.contains(docId);
    }

    /**
     * Inserts a doreplacedent in the store.
     *
     * @param docId    doreplacedent id.
     * @param doreplacedent doreplacedent in the form of JsonNode.
     */
    public void insertDoreplacedent(String docId, @Nonnull Object doreplacedent) {
        dbConnector.create(docId, doreplacedent);
    }

    /**
     * Returns a doreplacedent identified by the docId from the database.
     *
     * @param docId doreplacedent id.
     * @return doreplacedent in the database in JsonNode format.
     */
    @Nullable
    public <T> T getDoreplacedent(String docId, Clreplaced<T> docType) {
        return dbConnector.get(docType, docId);
    }

    /**
     * Update or insert a doreplacedent identified by docId in the database.
     *
     * @param docId    doreplacedent id.
     * @param doreplacedent doreplacedent.
     */
    public void upsertDoreplacedent(String docId, @Nonnull Object doreplacedent) {
        if (docId != null && dbConnector.contains(docId)) {
            dbConnector.update(doreplacedent);
        } else {
            // create a doreplacedent & if docId is null then couch db will generate a random id.
            dbConnector.create(doreplacedent);
        }
    }

    /**
     * Returns the results of a view.
     *
     * @param viewQuery view query that represents a view in couch-db.
     * @return result of view.
     */
    public ViewResult queryStore(ViewQuery viewQuery) {
        return dbConnector.queryView(viewQuery);
    }

    @Override
    public void connect() throws IOException {
        StdHttpClient.Builder builder = new StdHttpClient.Builder();
        if (dbUrl != null) {
            try {
                builder.url(dbUrl);
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
        if (userName != null) {
            builder.username(userName);
        }
        if (preplacedword != null) {
            builder.preplacedword(preplacedword);
        }
        HttpClient httpClient = builder.build();
        couchInstance = new StdCouchDbInstance(httpClient);
        dbConnector = couchInstance.createConnector(dbName, false);
    }

    @Override
    public void disconnect() throws IOException {
        couchInstance.getConnection().shutdown();
        dbConnector = null;
    }

    @Override
    public boolean isConnected() {
        return dbConnector == null;
    }
}

19 View Complete Implementation : ServerDAOManager.java
Copyright Apache License 2.0
Author : cfibmers
protected void initRepo(CouchDbConnector db, boolean createIfNotExist) {
    triggerRecordDao = new TriggerRecordDAOImpl(db, createIfNotExist);
    boundAppDao = new BoundAppDAOImpl(db, createIfNotExist);
    serviceConfigDao = new ServiceConfigDAOImpl(db, createIfNotExist);
    metricDBSegmentDao = new MetricDBSegmentDAOImpl(db, createIfNotExist);
    autoScalerPolicyDao = new AutoScalerPolicyDAOImpl(db, createIfNotExist);
    applicationDao = new ApplicationDAOImpl(db, createIfNotExist);
    scalingHistoryDao = new ScalingHistoryDAOImpl(db, createIfNotExist);
    appAutoScalerStateDao = new AppAutoScaleStateDAOImpl(db, createIfNotExist);
}

19 View Complete Implementation : EktorpBeanSerializerModifier.java
Copyright Apache License 2.0
Author : helun
public clreplaced EktorpBeanSerializerModifier extends BeanSerializerModifier {

    private final CouchDbConnector db;

    public EktorpBeanSerializerModifier(CouchDbConnector db) {
        this.db = db;
    }

    @Override
    public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
        if (serializer instanceof BeanSerializer && hasAnnotatedField(beanDesc.getType().getRawClreplaced())) {
            return new DoreplacedentReferenceSerializer(db, (BeanSerializer) serializer);
        }
        return super.modifySerializer(config, beanDesc, serializer);
    }

    private boolean hasAnnotatedField(Clreplaced<?> clazz) {
        Collection<Field> f = ReflectionUtils.eachField(clazz, new Predicate<Field>() {

            @Override
            public boolean apply(Field input) {
                DoreplacedentReferences dr = input.getAnnotation(DoreplacedentReferences.clreplaced);
                if (dr == null) {
                    return false;
                }
                return CascadeType.intersects(dr.cascade(), CascadeType.PERSIST_TYPES);
            }
        });
        return !f.isEmpty();
    }
}

19 View Complete Implementation : CouchDBTestHelper.java
Copyright Apache License 2.0
Author : apache
/**
 * <br>A helper clreplaced that setups the couch db for testing
 *
 * @since 0.3.5
 */
public clreplaced CouchDBTestHelper {

    public static final String TEST_DB = "CouchDbTest";

    public static final String DESIGN_DOC_ID = "_design/CouchDbTest";

    public static final String TEST_VIEW = "testView";

    private static CouchDbConnector connector;

    private static final ObjectMapper mapper = new ObjectMapper();

    public static ViewQuery createAndFetchViewQuery() {
        if (!connector.contains(DESIGN_DOC_ID)) {
            // The design doreplacedent doesn't exist in the database so we create it.
            JsonNode rootNode = mapper.createObjectNode();
            ((ObjectNode) rootNode).put("language", "javascript");
            ((ObjectNode) rootNode).putObject("views").putObject(TEST_VIEW).put("map", "function(doc) {\n  emit(doc._id, doc);\n}");
            connector.create(DESIGN_DOC_ID, rootNode);
        }
        return new ViewQuery().designDocId(DESIGN_DOC_ID).viewName(TEST_VIEW);
    }

    public static void insertDoreplacedent(Map<String, String> dbTuple) {
        connector.create(dbTuple);
    }

    public static void insertDoreplacedent(Object dbTuple) {
        connector.create(dbTuple);
    }

    public static JsonNode fetchDoreplacedent(String docId) {
        return connector.get(JsonNode.clreplaced, docId);
    }

    public static int getTotalDoreplacedents() {
        return connector.queryView(createAndFetchViewQuery()).getTotalRows();
    }

    static void setup() {
        StdHttpClient.Builder builder = new StdHttpClient.Builder();
        HttpClient httpClient = builder.build();
        StdCouchDbInstance instance = new StdCouchDbInstance(httpClient);
        DbPath dbPath = new DbPath(TEST_DB);
        if (instance.checkIfDbExists((dbPath))) {
            instance.deleteDatabase(dbPath.getPath());
        }
        connector = instance.createConnector(TEST_DB, true);
    }

    static void teardown() {
        StdHttpClient.Builder builder = new StdHttpClient.Builder();
        HttpClient httpClient = builder.build();
        StdCouchDbInstance instance = new StdCouchDbInstance(httpClient);
        DbPath dbPath = new DbPath(TEST_DB);
        if (instance.checkIfDbExists((dbPath))) {
            instance.deleteDatabase(dbPath.getPath());
        }
    }
}

19 View Complete Implementation : CouchDBManager.java
Copyright MIT License
Author : AURIN
/**
 * @param db
 *          the db to set
 */
public void setDb(CouchDbConnector db) {
    this.db = db;
}

18 View Complete Implementation : StdDesignDocumentFactory.java
Copyright Apache License 2.0
Author : helun
/*
     * (non-Javadoc)
     * @see org.ektorp.support.DesignDoreplacedentFactory#getFromDatabase(org.ektorp.CouchDbConnector, java.lang.String)
     */
@Override
public DesignDoreplacedent getFromDatabase(CouchDbConnector db, String designDoreplacedentId) {
    return db.get(DesignDoreplacedent.clreplaced, designDoreplacedentId);
}

18 View Complete Implementation : EktorpJacksonModuleTest.java
Copyright Apache License 2.0
Author : helun
@SuppressWarnings("serial")
public clreplaced EktorpJacksonModuleTest {

    EktorpJacksonModule module;

    CouchDbConnector db = mock(CouchDbConnector.clreplaced);

    ObjectMapper mapper = new ObjectMapper();

    @Before
    public void setup() {
        module = new EktorpJacksonModule(db, mapper);
        mapper.registerModule(module);
    }

    @Test
    public void property_annotated_with_DocRef_should_not_be_serialized() throws Exception {
        ParentDoc p = new ParentDoc();
        p.setId("id");
        p.setRevision("rev");
        p.addChild(new ChildDoc("cid", "crev"));
        String json = mapper.writeValuereplacedtring(p);
        replacedertFalse("children field should be absent from json", json.matches(".*children.*"));
    }

    @Test
    public void cascading_property_should_be_saved_separately() throws Exception {
        ParentDocWithCascade p = new ParentDocWithCascade();
        p.setId("id");
        p.setRevision("rev");
        p.addChild(new ChildDoc("cid", "crev"));
        String json = mapper.writeValuereplacedtring(p);
        replacedertFalse("children field should be absent from json", json.matches(".*children.*"));
        verify(db).executeBulk(any(Collection.clreplaced));
    }

    public static clreplaced ParentDoc extends CouchDbDoreplacedent {

        @DoreplacedentReferences(backReference = "parentId")
        Set<ChildDoc> children;

        public Set<ChildDoc> getChildren() {
            return children;
        }

        public void setChildren(Set<ChildDoc> children) {
            this.children = children;
        }

        public void addChild(ChildDoc c) {
            if (children == null) {
                children = new LinkedHashSet<EktorpJacksonModuleTest.ChildDoc>();
            }
            children.add(c);
        }
    }

    public static clreplaced ParentDocWithCascade extends CouchDbDoreplacedent {

        @DoreplacedentReferences(backReference = "parentId", cascade = CascadeType.ALL)
        Set<ChildDoc> children;

        public Set<ChildDoc> getChildren() {
            return children;
        }

        public void setChildren(Set<ChildDoc> children) {
            this.children = children;
        }

        public void addChild(ChildDoc c) {
            if (children == null) {
                children = new LinkedHashSet<EktorpJacksonModuleTest.ChildDoc>();
            }
            children.add(c);
        }
    }

    public static clreplaced ChildDoc extends CouchDbDoreplacedent {

        private String parentId;

        @JsonCreator
        public ChildDoc(@JsonProperty("_id") String id, @JsonProperty("_rev") String rev) {
            setId(id);
            setRevision(rev);
        }

        public String getParentId() {
            return parentId;
        }

        public void setParentId(String parentId) {
            this.parentId = parentId;
        }
    }
}

18 View Complete Implementation : IndexUploaderTest.java
Copyright Apache License 2.0
Author : ldriscoll
/**
 * Created by IntelliJ IDEA.
 * User: ldriscoll
 * Date: 5/6/11
 * Time: 9:44 AM
 * To change this template use File | Settings | File Templates.
 */
public clreplaced IndexUploaderTest {

    private final IndexUploader uploader = new IndexUploader();

    private static String indexEverythingJS;

    private static String indexNothingJS;

    private CouchDbConnector connector;

    @Test
    public void testChangeWorks() {
        uploader.updateSearchFunctionIfNecessary(connector, Const.VIEW_NAME, Const.SEARCH_FUNCTION, indexNothingJS);
        // now make sure that when we load the index everything it has changed
        boolean updated;
        updated = uploader.updateSearchFunctionIfNecessary(connector, Const.VIEW_NAME, Const.SEARCH_FUNCTION, indexEverythingJS);
        replacedertTrue("View should update", updated);
        // now make sure that it doesn't change this time
        updated = uploader.updateSearchFunctionIfNecessary(connector, Const.VIEW_NAME, Const.SEARCH_FUNCTION, indexEverythingJS);
        replacedertFalse("View should not update", updated);
    }

    @BeforeClreplaced
    public static void setUpClreplaced() {
        indexEverythingJS = readJSFile(Const.INDEX_EVERYTHING_JS);
        replacedertNotNull(indexEverythingJS);
        indexNothingJS = readJSFile(Const.INDEX_NOTHING_JS);
        replacedertNotNull(indexNothingJS);
    }

    @Before
    public void setUp() throws IOException {
        HttpClient httpClient = new StdHttpClient.Builder().host("localhost").port(5984).socketTimeout(1000).username("testadmin").preplacedword("testpreplaced").build();
        CouchDbInstance instance = new StdCouchDbInstance(httpClient);
        // don't really need a lucene aware couchdb connector, but just testing it in case
        connector = new LuceneAwareCouchDbConnector(Const.TEST_DATABASE, instance);
        connector.createDatabaseIfNotExists();
    }

    @After
    public void tearDown() {
        connector = null;
    }

    /**
     * Reads in the given js file name form the clreplacedpath
     *
     * @param jsFileName
     * @return
     */
    protected static String readJSFile(String jsFileName) {
        // load the js out of the clreplacedpath
        InputStream is = IndexUploaderTest.clreplaced.getResourcereplacedtream("/" + jsFileName);
        try {
            String js = IOUtils.toString(is);
            return js;
        } catch (IOException e) {
            throw new RuntimeException("Problem loading the indexing js function from the package", e);
        }
    }
}

18 View Complete Implementation : EktorpTestConfiguration.java
Copyright Apache License 2.0
Author : rwitzel
@Bean
public EktorpCrudRepository<Exotic, ExoticId> exoticRepository(CouchDbConnector db) {
    return new EktorpCrudRepository<Exotic, ExoticId>(Exotic.clreplaced, db, new ExoticEnreplacedyInformation());
}

18 View Complete Implementation : ChangesFeedAsyncTask.java
Copyright Apache License 2.0
Author : helun
/**
 * This clreplaced allows you to pull DoreplacedentChanges off a CouchDB changes feed in the background
 * and process them on the main thread.
 */
public abstract clreplaced ChangesFeedAsyncTask extends AsyncTask<Void, DoreplacedentChange, Object> {

    protected CouchDbConnector couchDbConnector;

    protected ChangesCommand changesCommand;

    protected ChangesFeed changesFeed;

    /**
     * Create a ChangesFeedAsynTask with the provided CouchDbConnector and ChangesCommand
     *
     * @param couchDbConnector the couchDbConnector to use
     * @param changesCommand the changeCommand to execute
     */
    public ChangesFeedAsyncTask(CouchDbConnector couchDbConnector, ChangesCommand changesCommand) {
        this.couchDbConnector = couchDbConnector;
        this.changesCommand = changesCommand;
    }

    @Override
    protected Object doInBackground(Void... params) {
        Object result = null;
        changesFeed = couchDbConnector.changesFeed(changesCommand);
        while (!isCancelled() && changesFeed.isAlive()) {
            try {
                DoreplacedentChange change = changesFeed.next();
                publishProgress(change);
            } catch (DbAccessException dbAccesException) {
                result = dbAccesException;
            } catch (InterruptedException interruptedException) {
                cancel(false);
            }
        }
        return result;
    }

    @Override
    protected void onCancelled() {
        if (changesFeed != null) {
            changesFeed.cancel();
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        if (result == null) {
            onSuccess();
        } else if (result instanceof DbAccessException) {
            onDbAccessException((DbAccessException) result);
        }
    }

    /**
     * Called when the changes feed has returned all applicable changes without Exception
     */
    protected void onSuccess() {
    }

    /**
     * By default, we rethrow this exception
     * @param dbAccessException
     */
    protected void onDbAccessException(DbAccessException dbAccessException) {
        throw dbAccessException;
    }

    @Override
    protected void onProgressUpdate(DoreplacedentChange... values) {
        handleDoreplacedentChange(values[0]);
    }

    /**
     * Override this method to handle the DoreplacedentChange in your application
     * @param change the DoreplacedentChange
     */
    protected abstract void handleDoreplacedentChange(DoreplacedentChange change);
}

18 View Complete Implementation : EktorpTestConfiguration.java
Copyright Apache License 2.0
Author : rwitzel
@Bean
public EktorpCrudRepository<Manufacturer, String> manufacturerRepository(CouchDbConnector db) {
    return new EktorpCrudRepository<Manufacturer, String>(Manufacturer.clreplaced, db);
}

18 View Complete Implementation : JSONTraceDB.java
Copyright GNU General Public License v3.0
Author : coast-team
/**
 * @author romain
 */
// Clreplaced INCOMPLETE
public clreplaced JSONTraceDB implements Trace {

    private ArrayList<TraceOperation> ops;

    private CouchDbConnector db;

    private HashMap<String, Integer> numReplica;

    // permet de stocker la liste des doreplacedents qui permettent de stocker les lignes d'un fichier
    private HashMap<String, DoreplacedentJSON> listeDocs;

    public JSONTraceDB(String nomBDD) throws Exception, FileNotFoundException, IOException {
        // Connexion à la base de données
        HttpClient httpClient = new StdHttpClient.Builder().build();
        CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
        // if the second parameter is true, the database will be created if it doesn't exists
        db = dbInstance.createConnector(nomBDD, true);
        // recherche de la bd
        boolean trouve = false;
        trouve = dbInstance.checkIfDbExists(new DbPath(nomBDD));
        if (!trouve) {
            throw new Exception("Base de données " + nomBDD + " inexistante");
        }
        // Pour chaque nouvelle branche, on crée un nouveau vector clock
        VectorClockMapper vectorClockMapper = new VectorClockMapper();
        // initialistaion de la liste des traces operations
        this.ops = new ArrayList<TraceOperation>();
        // FileReader f = new FileReader("/home/damien/etherpad-lite/var/dirtyCS.db");
        // Récupération de tous les ids dans la base de données
        List<String> l = db.getAllDocIds();
        /*
         * Recherche de tous les commits n'ayant aucun fils
        */
        HashMap<String, Boolean> lb = new HashMap<String, Boolean>();
        for (String la : l) {
            // test au cas où un parent aurait été ajouter avant que l'on itère dessus
            if (!lb.containsKey(la)) {
                // insertion du commit dont on ne sait pas encore si c'est un parent ou non
                lb.put(la, true);
            }
            // mise en place d'un correctif d'erreur d'accès à la base de données
            boolean b = true;
            ArrayList<String> lpa = null;
            while (b) {
                try {
                    lpa = db.get(ObjetCommit.clreplaced, la).getDependances().getIdParents();
                    b = false;
                } catch (DbAccessException e) {
                    b = true;
                    System.out.println("Access DB Error");
                }
            }
            // Itération sur chaque commit parent du commit pour dire à chaque parent qu'il possède au moins un enfant
            for (String lp : lpa) {
                lb.put(lp, false);
            }
        }
        System.out.println("recherche commits sans fils terminée");
        // Creation d'une arraylist pour stocker les commits qui n'ont pas d'enfant
        ArrayList<String> ar = new ArrayList<String>();
        for (String s : lb.keySet()) {
            if (lb.get(s)) {
                ar.add(s);
            }
        }
        System.out.println("creation arraylist avec commits sans fils terminée, taille arraylist : " + ar.size());
        /*
         * Creation des numéros de réplica pour chaque commit
         */
        // Initialisation des numéros de réplica dans la Map qui contient les replacedociations entre les ids et les numéros de réplica
        numReplica = new HashMap<String, Integer>();
        for (String la : l) {
            numReplica.put(la, -2);
        }
        boolean verif = false;
        StringBuffer sa = new StringBuffer("");
        // Verification (normalement inutile) si chaque parent des ids présents dans la liste existe bien dans cette même liste
        for (String s : numReplica.keySet()) {
            // System.out.println("-"+s+"-");
            ObjetCommit ca = db.get(ObjetCommit.clreplaced, s);
            if (!ca.getDependances().getIdParents().isEmpty()) {
                for (String sc : ca.getDependances().getIdParents()) {
                    if (!numReplica.containsKey(sc)) {
                        verif = true;
                    // sa.append(s).append("\n");
                    }
                }
            }
        }
        System.out.println("verif : " + verif);
        // System.out.println(sa.toString());
        // Attribution à chaque id issu de la base de données d'un numéro de réplica
        // initialisation du premier numéro d'id
        int num = 0;
        // Iteration sur la liste des commits n'ayant aucun enfant
        for (String a : ar) {
            ObjetCommit c = db.get(ObjetCommit.clreplaced, a);
            System.out.println(c.getIdCommit());
            num = parcourir(c, num);
        }
        // affichage pour vérification que tout les commits possèdent un numéro de réplica
        System.out.println("\nListe numéro de réplica");
        for (String s : numReplica.keySet()) {
            System.out.println(s + " : " + numReplica.get(s));
        }
        System.out.println("Num replica size : " + numReplica.size());
        System.out.println("Liste all commits size : " + l.size());
        /*
         * Recherche des commits sans parents pour démarrer la création de vectorClock sur les plus anciens commits
         */
        ArrayList<String> as = new ArrayList<String>();
        for (String sp : l) {
            ObjetCommit cs = db.get(ObjetCommit.clreplaced, sp);
            if (cs.getDependances().getIdParents().isEmpty()) {
                as.add(cs.getIdCommit());
            }
        }
        System.out.println("nombre de commits sans parents : " + as.size());
        /*
         * Déclaration d'une map pour stocker des objets java DoreplacedentJSON qui permette de "rejouer" chaque modification sur chaque fichier 
         * afin de récupérer le nombre de caractères entre le début du doreplacedent jusqu'au début de la ligne qui nous intéresse afin de connaître la place de la ligne exprimée avec le nombre de caractères qui la précède et non plus le numéro de ligne
         */
        listeDocs = new HashMap<String, DoreplacedentJSON>();
        /*
         * Itération sur commits sans parents
         */
        for (int i = 0; i < as.size(); i++) {
            // Récupération du commit
            ObjetCommit sp = db.get(ObjetCommit.clreplaced, as.get(i));
            // Récupération du numéro de réplica
            int repli = this.numReplica.get(sp.getIdCommit());
            // itération sur les commits parents du commit pour vectorclocker chaque ligne de chaque opération
            for (CommitDiff cd : sp.getModifs().getCommitsDiff()) {
                // itération sur chaque opération
                for (FileOperations fo : cd.getFileOperations()) {
                    // itération sur chaque ligne du contenu modifié
                    for (ElementModif e : fo.getContenu()) {
                        // Récupération du doreplacedent replacedocié à la modification
                        DoreplacedentJSON d = listeDocs.get(fo.getPathObjet());
                        if (d == null) {
                            d = new DoreplacedentJSON(fo.getPathObjet());
                        }
                        // Modification du doreplacedent avec l'opération actuelle
                        if (e.getType() == TypeModif.addText) {
                            d.add(e);
                        } else {
                            d.del(e);
                        }
                        // ajout du doreplacedent dans la liste des doreplacedents
                        listeDocs.put(fo.getPathObjet(), d);
                        // Création d'une nouvelle SequenceOperation
                        TraceOperation sop = TraceGenerator.oneJSONDB2OP(repli, d, e, vectorClockMapper);
                    }
                // fin itération sur les lignes d'une opération
                }
            // fin itération sur fileOperation pour vectorclocker
            }
        // fin itération parent pour vectorclocker
        }
    // fin itération
    /*
         * itération sur le prochain élément qui se doit être un des enfants des commits précédemment (tâche non facilitée, on a que les parents d'un commit : necessite de parcours à chaque commit pour trouver les enfants ...)
         */
    }

    /*
     * Iterateur pour parcourir la liste des commits et créer une 
     */
    public Enumeration<TraceOperation> enumeration() {
        return new Enumeration<TraceOperation>() {

            private Iterator<TraceOperation> it = ops.iterator();

            @Override
            public boolean hasMoreElements() {
                return it.hasNext();
            }

            @Override
            public TraceOperation nextElement() {
                return it.next();
            }
        };
    }

    /*
    * Fonctions de parcourt des commits pour attribuer à chacun un numéro de réplica
    * Les numéros de réplica avec le SHA-1 du commit sont contenus dans la HashMap "numReplica"
    * 
    */
    private int parcourir(ObjetCommit n, int num) {
        if (numReplica.get(n.getIdCommit()) == -2) {
            numReplica.put(n.getIdCommit(), num);
        }
        // recherche du premier parent qui n'ait pas de numéro de réplica et descente sur celui ci
        for (String p : n.getDependances().getIdParents()) {
            ObjetCommit fat = db.get(ObjetCommit.clreplaced, p);
            if (numReplica.get(p) == -2) {
                descente(fat, num);
                num++;
            }
        }
        // Itération du parcours sur chaque parent du noeud
        for (String pp : n.getDependances().getIdParents()) {
            num = parcourir(db.get(ObjetCommit.clreplaced, pp), num);
        }
        return num;
    }

    private void descente(ObjetCommit s, int num) {
        // attribution au noeud s du numéro de réplica num
        numReplica.put(s.getIdCommit(), num);
        /*
         * recherche du premier parent de s tel que c.rep == -1
         */
        // on regarde si la liste des parents du noeud s n'est pas vide
        if (!s.getDependances().getIdParents().isEmpty()) {
            boolean bool = false;
            ObjetCommit c = null;
            for (String id : s.getDependances().getIdParents()) {
                if (!bool && (numReplica.get(id) == -2)) {
                    c = db.get(ObjetCommit.clreplaced, id);
                    bool = true;
                }
            }
            /*
          * Recherche des parents de c qui n'ont pas de numéros de réplicas
          */
            // regarde si c n'est pas null et a des parents
            if ((c != null) && (!c.getDependances().getIdParents().isEmpty())) {
                boolean b = false;
                // Vérification qu'il existe un parent qui n'a pas de numéro de réplica dans les parents de c
                for (String pr : c.getDependances().getIdParents()) {
                    if (numReplica.get(pr) == -2) {
                        b = true;
                    }
                }
                // verification qu'un parent ait été trouvé
                if (b) {
                    descente(c, num);
                }
            }
        // fin verif c a des parents
        }
    // fin verif s a des parents
    }

    public static void main(String[] args) throws Exception {
        JSONTraceDB db = new JSONTraceDB("gitmatthieu112");
    }
}

18 View Complete Implementation : CouchDBRecording.java
Copyright Apache License 2.0
Author : ryanramage
/**
 * @author ryan
 */
public clreplaced CouchDBRecording {

    private CouchDbConnector connector;

    private ChangesFeed feed;

    private String recordingDocIdPrefex = "com.eckoit.recording:";

    private String recorderUUID;

    private String userName;

    private ObjectNode currentRecordingDoc;

    private boolean running = true;

    private boolean streamAudio = true;

    public CouchDBRecording(final CouchDbConnector connector) {
        this.connector = connector;
        this.recorderUUID = UUID.randomUUID().toString();
        EventBus.subscribeStrongly(ExitApplicationMessage.clreplaced, new EventSubscriber<ExitApplicationMessage>() {

            @Override
            public void onEvent(ExitApplicationMessage t) {
                running = false;
                feed.cancel();
            }
        });
        EventBus.subscribeStrongly(RecordingStartedResponseEvent.clreplaced, new EventSubscriber<RecordingStartedResponseEvent>() {

            @Override
            public void onEvent(RecordingStartedResponseEvent t) {
                // get the current doc
                try {
                    currentRecordingDoc = connector.get(ObjectNode.clreplaced, t.getRecordingID());
                } catch (Exception e) {
                    // if we are here, then we have come from an internal request, we need to create the doc
                    ObjectMapper mapper = new ObjectMapper();
                    currentRecordingDoc = mapper.createObjectNode();
                    currentRecordingDoc.put("_id", t.getRecordingID());
                    ObjectNode recordingState = currentRecordingDoc.putObject("recordingState");
                    long dt = System.currentTimeMillis();
                    recordingState.put("recorderAsked", dt);
                    recordingState.put("recorderAvailable", getRecorderUUID());
                    recordingState.put("startAsked", dt);
                    if (StringUtils.isNotEmpty(userName)) {
                        ObjectNode userCtx = currentRecordingDoc.putObject("userCtx");
                        userCtx.put("name", userName);
                        userCtx.putArray("roles");
                    }
                }
                ObjectNode recordingState = getRecordingState(currentRecordingDoc);
                recordingState.put("startComplete", new Date().getTime());
                connector.update(currentRecordingDoc);
            }
        });
        EventBus.subscribeStrongly(RecordingStoppedResponseEvent.clreplaced, new EventSubscriber<RecordingStoppedResponseEvent>() {

            @Override
            public void onEvent(RecordingStoppedResponseEvent t) {
                ObjectNode recordingState = getRecordingState(currentRecordingDoc);
                recordingState.put("stopComplete", new Date().getTime());
                connector.update(currentRecordingDoc);
            }
        });
        EventBus.subscribeStrongly(PostProcessingStartedEvent.clreplaced, new EventSubscriber<PostProcessingStartedEvent>() {

            @Override
            public void onEvent(PostProcessingStartedEvent t) {
            // ObjectNode recordingState = getRecordingState(currentRecordingDoc);
            // recordingState.put("postProcessingStarted", new Date().getTime());
            // connector.update(currentRecordingDoc);
            }
        });
        EventBus.subscribeStrongly(RecordingCompleteEvent.clreplaced, new EventSubscriber<RecordingCompleteEvent>() {

            @Override
            public void onEvent(RecordingCompleteEvent t) {
                String id = currentRecordingDoc.get("_id").getTextValue();
                currentRecordingDoc = connector.get(ObjectNode.clreplaced, id);
                {
                    ObjectNode recordingState = getRecordingState(currentRecordingDoc);
                    recordingState.put("postProcessingStarted", new Date().getTime());
                    connector.update(currentRecordingDoc);
                }
                EventBus.publish(new UploadingStartedEvent());
                String revision = currentRecordingDoc.get("_rev").getTextValue();
                try {
                    // mp3
                    FileInputStream fis = new FileInputStream(t.getRecordings()[0]);
                    AttachmentInputStream ais = new AttachmentInputStream("complete.mp3", fis, "audio/mp3");
                    revision = connector.createAttachment(id, revision, ais);
                    ais.close();
                    fis.close();
                } catch (Exception e) {
                }
                try {
                    if (t.getRecordings().length == 2) {
                        // ogg
                        FileInputStream fis = new FileInputStream(t.getRecordings()[1]);
                        AttachmentInputStream ais = new AttachmentInputStream("complete.ogg", fis, "audio/ogg");
                        revision = connector.createAttachment(id, revision, ais);
                        ais.close();
                        fis.close();
                    }
                } catch (Exception e) {
                }
                EventBus.publish(new UploadingFinishedEvent());
                // lame extra get
                currentRecordingDoc = loadRecordingDoc(id);
                ObjectNode recordingState = getRecordingState(currentRecordingDoc);
                recordingState.put("recordingComplete", new Date().getTime());
                connector.update(currentRecordingDoc);
                currentRecordingDoc = null;
            }
        });
        EventBus.subscribeStrongly(StreamReadyEvent.clreplaced, new EventSubscriber<StreamReadyEvent>() {

            @Override
            public void onEvent(StreamReadyEvent t) {
                System.out.println("Streaming");
                if (streamAudio) {
                    try {
                        System.out.println("out");
                        // create a doc
                        ObjectMapper map = new ObjectMapper();
                        ObjectNode node = map.createObjectNode();
                        node.put("type", "com.eckoit.recordingSegment");
                        node.put("recording", currentRecordingDoc.get("_id").getTextValue());
                        node.put("startTime", t.getStartTime());
                        connector.create(node);
                        String id = node.get("_id").getTextValue();
                        String rev = node.get("_rev").getTextValue();
                        {
                            // attach stream
                            FileInputStream fis = new FileInputStream(t.getAvailableToStream());
                            String name = "fileSequence" + t.getSegmentCount() + ".ts";
                            AttachmentInputStream ais = new AttachmentInputStream(name, fis, t.getContentType());
                            rev = connector.createAttachment(id, rev, ais);
                            ais.close();
                            fis.close();
                        }
                        {
                            // attach mp3
                            FileInputStream fis = new FileInputStream(t.getFinishedFile());
                            String name = "fileSequence" + t.getSegmentCount() + ".mp3";
                            AttachmentInputStream ais = new AttachmentInputStream(name, fis, "audio/mp3");
                            rev = connector.createAttachment(id, rev, ais);
                            ais.close();
                            fis.close();
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        });
        EventBus.subscribeStrongly(RecorderJustStartedWithARecordingDocRequested.clreplaced, new EventSubscriber<RecorderJustStartedWithARecordingDocRequested>() {

            @Override
            public void onEvent(RecorderJustStartedWithARecordingDocRequested t) {
                ObjectNode testDoc = connector.get(ObjectNode.clreplaced, t.getRecordingDocId());
                RecordingState state = detectState(testDoc);
                System.out.println("The state of the requested doc: " + state.name());
                if (state == RecordingState.START_ASKED) {
                    processRecordingDoc(testDoc);
                } else if (state == RecordingState.RECORDER_AVAILABLE || state == RecordingState.RECORDER_ASKED) {
                    // ok we will update with our id,
                    ObjectNode recordingState = getRecordingState(testDoc);
                    recordingState.put("recorderAvailable", getRecorderUUID());
                    connector.update(testDoc);
                }
            // no idea how to handle the other states right now.
            }
        });
    }

    protected ObjectNode getRecordingState(ObjectNode recordingDoc) {
        return (ObjectNode) recordingDoc.get("recordingState");
    }

    public void watch() {
        ChangesCommand cmd = new ChangesCommand.Builder().filter("couchaudiorecorder/recordings").build();
        System.out.println("CouchDB recorder starting");
        while (running) {
            try {
                feed = connector.changesFeed(cmd);
                while (feed.isAlive() && running) {
                    DoreplacedentChange change = feed.next();
                    System.out.println("Got a change!");
                    String docId = change.getId();
                    System.out.println(docId);
                    ObjectNode doc = loadRecordingDoc(docId);
                    if (doc != null) {
                        System.out.println("has doc");
                        processRecordingDoc(doc);
                    }
                }
            } catch (Exception e) {
                try {
                    // this catches any interrupted exceptions
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(CouchDBRecording.clreplaced.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        System.out.println("CouchDB recorder finished");
    }

    public void stop() {
        System.out.println("Its over for you");
        running = false;
        feed.cancel();
    }

    protected boolean areWeTheRecorder(ObjectNode doc, String whoAmI) {
        // I guess we handle it all
        if (whoAmI == null)
            return true;
        JsonNode userCtx = doc.get("userCtx");
        if (userCtx != null) {
            String docUserName = userCtx.get("name").getTextValue();
            return (whoAmI.equals(docUserName));
        }
        return false;
    }

    protected void processRecordingDoc(ObjectNode doc) {
        final RecordingState state = detectState(doc);
        System.out.println("state: " + state.name());
        if (state == RecordingState.RECORDER_ASKED) {
            System.out.println("Recorder asked");
            if (currentRecordingDoc == null) {
                if (areWeTheRecorder(doc, userName)) {
                    System.out.println("we are programmed to receive");
                    // we are free...lets volenteer
                    ObjectNode recordingState = getRecordingState(doc);
                    recordingState.put("recorderAvailable", getRecorderUUID());
                    connector.update(doc);
                }
            }
            return;
        }
        if (state == RecordingState.RECORDER_AVAILABLE || state == RecordingState.UNKNOWN) {
            // skipp
            System.out.println("Skip");
            if (currentRecordingDoc == null) {
                System.out.println("Recording doc empty");
            } else {
                System.out.println("we are committed");
            }
        } else if (isOurRecorder(doc)) {
            if (state == RecordingState.RECORDING_COMPLETE) {
                // make us available
                currentRecordingDoc = null;
                return;
            }
            // keeps the rev up
            currentRecordingDoc = doc;
            if (state == RecordingState.START_ASKED) {
                RecordingStartClickedEvent rsce = new RecordingStartClickedEvent(doc.get("_id").getTextValue());
                SplitAudioRecorderConfiguration settings = loadConfig(doc);
                if (settings != null) {
                    rsce.setConfig(settings);
                }
                EventBus.publish(rsce);
            }
            if (state == RecordingState.STOP_ASKED) {
                EventBus.publish(new RecordingStopClickedEvent());
            }
        }
    }

    protected SplitAudioRecorderConfiguration loadConfig(ObjectNode doc) {
        JsonNode settings = doc.get("settings");
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(settings, SplitAudioRecorderConfiguration.clreplaced);
        } catch (Exception ex) {
            return null;
        }
    }

    protected boolean isOurRecorder(ObjectNode doc) {
        ObjectNode recordingState = getRecordingState(doc);
        if (recordingState != null) {
            JsonNode node = recordingState.get("recorderAvailable");
            if (node != null) {
                String uuid = node.getTextValue();
                if (getRecorderUUID().equals(uuid)) {
                    return true;
                }
            }
        }
        return false;
    }

    protected ObjectNode loadRecordingDoc(String docID) {
        if (docID.startsWith(recordingDocIdPrefex)) {
            ObjectNode doc = connector.get(ObjectNode.clreplaced, docID);
            System.out.println(doc);
            return doc;
        }
        return null;
    }

    protected RecordingState detectState(ObjectNode doc) {
        JsonNode recordingState = doc.get("recordingState");
        if (recordingState != null) {
            if (recordingState.get("recordingComplete") != null) {
                return RecordingState.RECORDING_COMPLETE;
            }
            if (recordingState.get("postProcessingStarted") != null) {
                return RecordingState.POST_PROCESSING_STARTED;
            }
            if (recordingState.get("stopComplete") != null) {
                return RecordingState.STOP_COMPLETE;
            }
            if (recordingState.get("stopAsked") != null) {
                return RecordingState.STOP_ASKED;
            }
            if (recordingState.get("startComplete") != null) {
                return RecordingState.START_COMPLETE;
            }
            if (recordingState.get("startAsked") != null) {
                return RecordingState.START_ASKED;
            }
            if (recordingState.get("recorderAvailable") != null) {
                return RecordingState.RECORDER_AVAILABLE;
            }
            if (recordingState.get("recorderAsked") != null) {
                return RecordingState.RECORDER_ASKED;
            }
        }
        return RecordingState.UNKNOWN;
    }

    /**
     * @return the recordingDocIdPrefex
     */
    public String getRecordingDocIdPrefex() {
        return recordingDocIdPrefex;
    }

    /**
     * @param recordingDocIdPrefex the recordingDocIdPrefex to set
     */
    public void setRecordingDocIdPrefex(String recordingDocIdPrefex) {
        this.recordingDocIdPrefex = recordingDocIdPrefex;
    }

    /**
     * @return the recorderUUID
     */
    public String getRecorderUUID() {
        return recorderUUID;
    }

    /**
     * @param recorderUUID the recorderUUID to set
     */
    public void setRecorderUUID(String recorderUUID) {
        this.recorderUUID = recorderUUID;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public enum RecordingState {

        UNKNOWN,
        RECORDER_ASKED,
        RECORDER_AVAILABLE,
        START_ASKED,
        START_COMPLETE,
        STOP_ASKED,
        STOP_COMPLETE,
        POST_PROCESSING_STARTED,
        RECORDING_COMPLETE
    }
}

18 View Complete Implementation : CouchProfileService.java
Copyright Apache License 2.0
Author : pac4j
/**
 * The CouchDB profile service.
 *
 * @author Elie Roux
 * @since 2.0.0
 */
public clreplaced CouchProfileService extends AbstractProfileService<CouchProfile> {

    private CouchDbConnector couchDbConnector;

    private ObjectMapper objectMapper;

    private static final TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
    };

    public static final String COUCH_ID = "_id";

    public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes, final PreplacedwordEncoder preplacedwordEncoder) {
        setIdAttribute(COUCH_ID);
        objectMapper = new ObjectMapper();
        this.couchDbConnector = couchDbConnector;
        setAttributes(attributes);
        setPreplacedwordEncoder(preplacedwordEncoder);
    }

    public CouchProfileService() {
        this(null, null, null);
    }

    public CouchProfileService(final CouchDbConnector couchDbConnector) {
        this(couchDbConnector, null, null);
    }

    public CouchProfileService(final CouchDbConnector couchDbConnector, final String attributes) {
        this(couchDbConnector, attributes, null);
    }

    public CouchProfileService(final CouchDbConnector couchDbConnector, final PreplacedwordEncoder preplacedwordEncoder) {
        this(couchDbConnector, null, preplacedwordEncoder);
    }

    @Override
    protected void internalInit() {
        CommonHelper.replacedertNotNull("preplacedwordEncoder", getPreplacedwordEncoder());
        CommonHelper.replacedertNotNull("couchDbConnector", this.couchDbConnector);
        defaultProfileDefinition(new CommonProfileDefinition<>(x -> new CouchProfile()));
        super.internalInit();
    }

    @Override
    protected void insert(final Map<String, Object> attributes) {
        logger.debug("Insert doc: {}", attributes);
        couchDbConnector.create(attributes);
    }

    @Override
    protected void update(final Map<String, Object> attributes) {
        final String id = (String) attributes.get(COUCH_ID);
        try {
            final InputStream oldDocStream = couchDbConnector.getreplacedtream(id);
            final Map<String, Object> res = objectMapper.readValue(oldDocStream, typeRef);
            res.putAll(attributes);
            couchDbConnector.update(res);
            logger.debug("Updating id: {} with attributes: {}", id, attributes);
        } catch (DoreplacedentNotFoundException e) {
            logger.debug("Insert doc (not found by update(): {}", attributes);
            couchDbConnector.create(attributes);
        } catch (IOException e) {
            logger.error("Unexpected IO CouchDB Exception", e);
        }
    }

    @Override
    protected void deleteById(final String id) {
        logger.debug("Delete id: {}", id);
        try {
            final InputStream oldDocStream = couchDbConnector.getreplacedtream(id);
            final JsonNode oldDoc = objectMapper.readTree(oldDocStream);
            final String rev = oldDoc.get("_rev").asText();
            couchDbConnector.delete(id, rev);
        } catch (DoreplacedentNotFoundException e) {
            logger.debug("id {} is not in the database", id);
        } catch (IOException e) {
            logger.error("Unexpected IO CouchDB Exception", e);
        }
    }

    private Map<String, Object> populateAttributes(final Map<String, Object> rowAttributes, final List<String> names) {
        final Map<String, Object> newAttributes = new HashMap<>();
        for (final Map.Entry<String, Object> entry : rowAttributes.entrySet()) {
            final String name = entry.getKey();
            if (names == null || names.contains(name)) {
                newAttributes.put(name, entry.getValue());
            }
        }
        return newAttributes;
    }

    @Override
    protected List<Map<String, Object>> read(final List<String> names, final String key, final String value) {
        logger.debug("Reading key / value: {} / {}", key, value);
        final List<Map<String, Object>> listAttributes = new ArrayList<>();
        if (key.equals(COUCH_ID)) {
            try {
                final InputStream oldDocStream = couchDbConnector.getreplacedtream(value);
                final Map<String, Object> res = objectMapper.readValue(oldDocStream, typeRef);
                listAttributes.add(populateAttributes(res, names));
            } catch (DoreplacedentNotFoundException e) {
                logger.debug("Doreplacedent id {} not found", value);
            } catch (IOException e) {
                logger.error("Unexpected IO CouchDB Exception", e);
            }
        } else {
            // supposes a by_$key view in the design doreplacedent, see doreplacedentation
            final ViewQuery query = new ViewQuery().designDocId("_design/pac4j").viewName("by_" + key).key(value);
            final ViewResult result = couchDbConnector.queryView(query);
            for (ViewResult.Row row : result.getRows()) {
                final String stringValue = row.getValue();
                Map<String, Object> res = null;
                try {
                    res = objectMapper.readValue(stringValue, typeRef);
                    listAttributes.add(populateAttributes(res, names));
                } catch (IOException e) {
                    logger.error("Unexpected IO CouchDB Exception", e);
                }
            }
        }
        logger.debug("Found: {}", listAttributes);
        return listAttributes;
    }

    public CouchDbConnector getCouchDbConnector() {
        return couchDbConnector;
    }

    public void setCouchDbConnector(final CouchDbConnector couchDbConnector) {
        this.couchDbConnector = couchDbConnector;
    }

    public ObjectMapper getObjectMapper() {
        return this.objectMapper;
    }

    public void setObjectMapper(final ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String toString() {
        return CommonHelper.toNiceString(this.getClreplaced(), "couchDbConnector", couchDbConnector, "preplacedwordEncoder", getPreplacedwordEncoder(), "attributes", getAttributes(), "profileDefinition", getProfileDefinition(), "idAttribute", getIdAttribute(), "usernameAttribute", getUsernameAttribute(), "preplacedwordAttribute", getPreplacedwordAttribute());
    }
}

18 View Complete Implementation : CouchDBObjectMapperFactory.java
Copyright Apache License 2.0
Author : apache
/**
 * Create a object mapper object via couchdb connector
 *
 * @param connector
 * @return
 */
public synchronized ObjectMapper createObjectMapper(CouchDbConnector connector) {
    this.createObjectMapper();
    instance.registerModule(new EktorpJacksonModule(connector, instance));
    return instance;
}

18 View Complete Implementation : CachingObjectMapperFactory.java
Copyright Apache License 2.0
Author : helun
@Override
public ObjectMapper createObjectMapper(CouchDbConnector connector) {
    throw new UnsupportedOperationException();
}

18 View Complete Implementation : FFMpegSetterUpper.java
Copyright Apache License 2.0
Author : ryanramage
/**
 * This will do everything in its power to get a ffmpeg name back.
 *
 * @param workingDir The working dir that will hold a cached copy of ffmpeg
 * @param connector A couchdb that holds binary copies of ffmpeg
 * @param designDocName the design doc that holds the binary copies
 * @return
 * @throws NotImplementedException ffmpeg cant be found anywhere!
 */
public String ffmpegLocation(File workingDir, CouchDbConnector connector, String designDocName) throws NotImplementedException {
    String localFile = findLocalFFMpeg(workingDir);
    if (localFile != null)
        return localFile;
    // test system wide
    String system = findFFmepg();
    if (system != null)
        return system;
    return installFFMpegAndReturnLocation(workingDir, connector, designDocName);
}

18 View Complete Implementation : App.java
Copyright Apache License 2.0
Author : ryanramage
protected void startPlugins(List<Clreplaced> plugins, CouchDbConnector connector, CouchDbInstance couchDBInstance) {
    for (Clreplaced plugin : plugins) {
        startPlugin(plugin, connector, couchDBInstance);
    }
}

18 View Complete Implementation : AppTest.java
Copyright Apache License 2.0
Author : ryanramage
/**
 * @author ryan.ramage
 */
public clreplaced AppTest {

    App app;

    LocalCouch mock;

    CouchDbInstance couchMock;

    CouchDbConnector connectorMock;

    public AppTest() {
    }

    @Test
    public void createLocalDatabaseNameTest() {
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 80, null);
        String localDbName = app2.createLocalDbName();
        replacedertEquals("choose-choose_iriscouch_com", localDbName);
    }

    @Test
    public void createLocalDatabaseNameTestPort() {
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 5984, null);
        String localDbName = app2.createLocalDbName();
        replacedertEquals("choose-choose_iriscouch_com-5984", localDbName);
    }

    @Test
    public void createLocalDatabaseNameLowerCase() {
        App app2 = new App("App Name", "choose.irisCouch.com", "choose", 5984, null);
        String localDbName = app2.createLocalDbName();
        replacedertEquals("choose-choose_iriscouch_com-5984", localDbName);
    }

    @Test
    public void testGetSrcReplicationUrl() {
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        String result = app2.getSrcReplicationUrl(false);
        replacedertEquals("http://choose.iriscouch.com:81/choose", result);
    }

    @Test
    public void testFindPluginNames() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode design = mapper.readTree("{  \"advanced\" : {  \"plugins\" : [ \"com.test.Alpha\" ]          }   }");
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        List<String> results = app2.findPluginNamess(design);
        replacedertEquals(1, results.size());
        replacedertEquals("com.test.Alpha", results.get(0));
    }

    @Test
    public void testFindPluginNamesEmpty() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode design = mapper.readTree("{  \"advanced\" : {  \"plugins\" : [  ]          }   }");
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        List<String> results = app2.findPluginNamess(design);
        replacedertEquals(0, results.size());
    }

    @Test
    public void testFindPluginNamesNothing() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode design = mapper.readTree("{  \"advanced\" : {          }   }");
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        List<String> results = app2.findPluginNamess(design);
        replacedertEquals(0, results.size());
    }

    @Test
    public void testFindPluginNamesNoAdvanced() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode design = mapper.readTree("{  \"pizza\" : {          }   }");
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        List<String> results = app2.findPluginNamess(design);
        replacedertEquals(0, results.size());
    }

    @Test
    public void testConvertNamesToClreplacedes() throws IOException {
        App app2 = new App("App Name", "choose.iriscouch.com", "choose", 81, null);
        List<String> plugins = Arrays.asList("com.github.couchapptakeout.App");
        List<Clreplaced> results = app2.convertPluginNamesToClreplacedes(plugins);
        replacedertEquals(1, results.size());
        replacedertEquals(App.clreplaced, results.get(0));
    }

    // Needs to be an integration test
    public void testStartSync() {
        App app2 = new App("App Name", "localhost", "choose", 5984, null);
        HttpClient httpClient = new StdHttpClient.Builder().host("localhost").port(5984).build();
        CouchDbInstance couch = new StdCouchDbInstance(httpClient);
        CouchDbConnector connector = couch.createConnector("test-choose", true);
        app2.setupReplication(couch, connector);
    }

    public void testCopyDesignDocs() {
        App app2 = new App("App Name", "localhost", "ecko-it", 5984, null);
        HttpClient httpClient1 = new StdHttpClient.Builder().host("localhost").port(5984).build();
        CouchDbInstance couch1 = new StdCouchDbInstance(httpClient1);
        CouchDbConnector connector1 = couch1.createConnector("ecko-it", false);
        HttpClient httpClient2 = new StdHttpClient.Builder().host("localhost").port(5984).build();
        CouchDbInstance couch2 = new StdCouchDbInstance(httpClient2);
        try {
            couch2.deleteDatabase("eckoit-clone");
        } catch (Exception ignore) {
        }
        CouchDbConnector connector2 = couch2.createConnector("eckoit-clone", true);
        app2.copyDesignDocs(connector1, connector2);
        app2.setupReplication(couch2, connector2);
    }

    /**
     * Test of loadNeeded method, of clreplaced App.
     */
    public void testLoadNeededNoPreplacedword() throws Exception {
        App app = new App("App Name", "choose.irisCouch.com", "choose", 5984, null);
        setupMocksFor(app);
        replay(mock);
        replay(couchMock);
        replay(connectorMock);
        app.loadNeeded(false);
    }

    protected void setupMocksFor(App app) throws CouchDBNotFoundException {
        mock = createMock(LocalCouch.clreplaced);
        couchMock = createMock(CouchDbInstance.clreplaced);
        connectorMock = createNiceMock(CouchDbConnector.clreplaced);
        expect(mock.getCouchInstance()).andReturn(couchMock);
        expect(mock.getCouchConnector(app.createLocalDbName(), couchMock)).andReturn(connectorMock);
        app.setLocalCouchManager(mock);
    }
    // Some scenarios to consider
    // one app, one user
    // many apps, one user
    // many users, many apps
}

18 View Complete Implementation : DocumentReferenceSerializer.java
Copyright Apache License 2.0
Author : helun
/**
 * @author ragnar rova
 * @author henrik lundgren
 *
 * @param <T>
 */
public clreplaced DoreplacedentReferenceSerializer extends JsonSerializer<Object> {

    private final CouchDbConnector couchDbConnector;

    private final JsonSerializer<Object> delegate;

    public DoreplacedentReferenceSerializer(CouchDbConnector db, JsonSerializer<Object> delegate) {
        this.couchDbConnector = db;
        this.delegate = delegate;
    }

    @Override
    public void serialize(final Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        try {
            final Set<Object> docsToSave = new HashSet<Object>();
            ReflectionUtils.eachField(value.getClreplaced(), new Predicate<Field>() {

                @Override
                public boolean apply(Field input) {
                    DoreplacedentReferences referenceMetaData = input.getAnnotation(DoreplacedentReferences.clreplaced);
                    if (referenceMetaData != null) {
                        if (Set.clreplaced.isreplacedignableFrom(input.getType())) {
                            try {
                                input.setAccessible(true);
                                Collection<?> d = findDoreplacedentsToSave((Set<?>) input.get(value));
                                docsToSave.addAll(d);
                            } catch (IllegalAccessException e) {
                                throw Exceptions.propagate(e);
                            }
                        } else {
                            throw new DbAccessException("@DoreplacedentReferences can only be used on java.util.Set");
                        }
                    }
                    return false;
                }
            });
            if (!docsToSave.isEmpty()) {
                List<DoreplacedentOperationResult> res = couchDbConnector.executeBulk(docsToSave);
                if (res.size() > 0) {
                    throwBulkUpdateError(res);
                }
            }
            delegate.serialize(value, jgen, provider);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    private void throwBulkUpdateError(List<DoreplacedentOperationResult> res) {
        StringBuilder sb = new StringBuilder();
        int maxErrors = 10;
        for (DoreplacedentOperationResult docResult : res) {
            if (maxErrors == 0) {
                sb.append(".. " + res.size() + " more ");
                break;
            }
            sb.append(docResult.getId());
            sb.append(" ");
            sb.append(docResult.getError());
            sb.append(" ");
            sb.append(docResult.getReason());
            sb.append(" ");
            maxErrors--;
        }
        throw new DbAccessException(sb.toString());
    }

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "BC_VACUOUS_INSTANCEOF")
    private Set<?> findDoreplacedentsToSave(Set<?> o) {
        if (o == null) {
            return Collections.emptySet();
        }
        Set<Object> docsToSave = new LinkedHashSet<Object>();
        if (Proxy.isProxyClreplaced(o.getClreplaced()) && Proxy.getInvocationHandler(o) instanceof ViewBasedCollection) {
            ViewBasedCollection c = (ViewBasedCollection) Proxy.getInvocationHandler(o);
            if (c.initialized()) {
                docsToSave.addAll((Collection<?>) o);
                docsToSave.addAll(c.getPendingRemoval());
            }
        } else if (o instanceof Collection && ((Collection<?>) o).size() > 0) {
            docsToSave.addAll((Collection<?>) o);
        }
        return docsToSave;
    }
}

18 View Complete Implementation : ICureDAOImpl.java
Copyright GNU General Public License v2.0
Author : taktik
@Autowired
public void setCouchdbConfig(CouchDbConnector couchdbConfig) {
    this.couchdbConfig = couchdbConfig;
}

18 View Complete Implementation : EktorpBeanDeserializerModifier.java
Copyright Apache License 2.0
Author : helun
public clreplaced EktorpBeanDeserializerModifier extends BeanDeserializerModifier {

    private final CouchDbConnector db;

    private final ObjectMapper objectMapper;

    public EktorpBeanDeserializerModifier(CouchDbConnector db, ObjectMapper objectMapper) {
        this.db = db;
        this.objectMapper = objectMapper;
    }

    @Override
    public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
        if (deserializer instanceof BeanDeserializer) {
            List<ConstructibleAnnotatedCollection> fields = collectFields(config, beanDesc);
            if (!fields.isEmpty()) {
                return new BackReferencedBeanDeserializer((BeanDeserializer) deserializer, fields, db, beanDesc.getType().getRawClreplaced());
            }
        }
        return super.modifyDeserializer(config, beanDesc, deserializer);
    }

    private List<ConstructibleAnnotatedCollection> collectFields(final DeserializationConfig config, final BeanDescription desc) {
        final List<ConstructibleAnnotatedCollection> fields = new ArrayList<ConstructibleAnnotatedCollection>();
        final Map<String, AnnotatedMethod> setters = new LinkedHashMap<String, AnnotatedMethod>();
        List<BeanPropertyDefinition> properties = desc.findProperties();
        for (BeanPropertyDefinition beanPropertyDefinition : properties) {
            setters.put(beanPropertyDefinition.getInternalName(), beanPropertyDefinition.getSetter());
        }
        ReflectionUtils.eachField(desc.getType().getRawClreplaced(), new Predicate<Field>() {

            @Override
            public boolean apply(Field input) {
                if (ReflectionUtils.hasAnnotation(input, DoreplacedentReferences.clreplaced)) {
                    ConstructibleAnnotatedCollection c = collectBackrefField(config, desc, setters, input);
                    if (c != null) {
                        fields.add(c);
                    }
                }
                return false;
            }
        });
        return fields;
    }

    private ConstructibleAnnotatedCollection collectBackrefField(DeserializationConfig config, BeanDescription beanDesc, Map<String, AnnotatedMethod> setters, Field field) {
        JavaType type = objectMapper.getTypeFactory().constructType(field.getGenericType());
        if (!(type instanceof CollectionType)) {
            return null;
        }
        CollectionType collectionType = (CollectionType) type;
        return new ConstructibleAnnotatedCollection(field, findCtor(config, collectionType, field.getType()), constructSettableProperty(config, beanDesc, field.getName(), setters.get(field.getName()), collectionType), collectionType);
    }

    /**
     * Method copied from org.codehaus.jackson.map.deser.BeanDeserializerFactory
     */
    protected SettableBeanProperty constructSettableProperty(DeserializationConfig config, BeanDescription beanDesc, String name, AnnotatedMethod setter, JavaType type) {
        // need to ensure method is callable (for non-public)
        if (config.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {
            Method member = setter.getAnnotated();
            if (!Modifier.isPublic(member.getModifiers()) || !Modifier.isPublic(member.getDeclaringClreplaced().getModifiers())) {
                member.setAccessible(true);
            }
        }
        /*
		 * First: does the Method specify the deserializer to use? If so, let's
		 * use it.
		 */
        TypeDeserializer typeDeser = type.getTypeHandler();
        SettableBeanProperty prop = new MethodProperty(SimpleBeanPropertyDefinition.construct(config, setter), type, typeDeser, beanDesc.getClreplacedAnnotations(), setter);
        // [JACKSON-235]: need to retain name of managed forward references:
        AnnotationIntrospector.ReferenceProperty ref = config.getAnnotationIntrospector().findReferenceType(setter);
        if (ref != null && ref.isManagedReference()) {
            prop.setManagedReferenceName(ref.getName());
        }
        return prop;
    }

    private Constructor<Collection<Object>> findCtor(DeserializationConfig config, CollectionType type, Clreplaced<?> clazz) {
        Clreplaced<?> collectionClreplaced = clazz;
        if (type.isInterface() || type.isAbstract()) {
            @SuppressWarnings("rawtypes")
            Clreplaced<? extends Collection> fallback = _collectionFallbacks.get(collectionClreplaced.getName());
            if (fallback == null) {
                throw new IllegalArgumentException("Can not find a deserializer for non-concrete Collection type " + type);
            }
            collectionClreplaced = fallback;
        }
        boolean fixAccess = config.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
        @SuppressWarnings("unchecked")
        Constructor<Collection<Object>> ctor = ClreplacedUtil.findConstructor((Clreplaced<Collection<Object>>) collectionClreplaced, fixAccess);
        return ctor;
    }

    @SuppressWarnings("rawtypes")
    final static Map<String, Clreplaced<? extends Collection>> _collectionFallbacks = new HashMap<String, Clreplaced<? extends Collection>>();

    static {
        _collectionFallbacks.put(Collection.clreplaced.getName(), ArrayList.clreplaced);
        _collectionFallbacks.put(List.clreplaced.getName(), ArrayList.clreplaced);
        _collectionFallbacks.put(Set.clreplaced.getName(), LinkedHashSet.clreplaced);
        _collectionFallbacks.put(SortedSet.clreplaced.getName(), TreeSet.clreplaced);
        _collectionFallbacks.put(Queue.clreplaced.getName(), LinkedList.clreplaced);
        _collectionFallbacks.put("java.util.Deque", LinkedList.clreplaced);
        _collectionFallbacks.put("java.util.NavigableSet", TreeSet.clreplaced);
    }

    @Override
    public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDesc, BeanDeserializerBuilder builder) {
        return super.updateBuilder(config, beanDesc, builder);
    }
}

18 View Complete Implementation : CouchDbRepositorySupport.java
Copyright Apache License 2.0
Author : helun
/**
 * Provides "out of the box" CRUD functionality for sub clreplacedes.
 *
 * Note that this clreplaced will try to access the standard design doreplacedent named according
 * to this convention:
 *
 * _design/[repository type simple name]
 *
 *  e.g. _design/Sofa if this repository's handled type is foo.bar.Sofa
 *
 *  It is preferable that this design doreplacedent must define a view named "all".
 *  The "all"-view should only return doreplacedent id's that refer to doreplacedents that can be loaded as this repository's handled type.
 *
 * @author henrik lundgren
 * @param <T>
 */
public clreplaced CouchDbRepositorySupport<T> implements GenericRepository<T> {

    /**
     * System property key: org.ektorp.support.AutoUpdateViewOnChange
     */
    public static final String AUTO_UPDATE_VIEW_ON_CHANGE = "org.ektorp.support.AutoUpdateViewOnChange";

    protected static final Logger log = LoggerFactory.getLogger(CouchDbRepositorySupport.clreplaced);

    protected final CouchDbConnector db;

    protected final Clreplaced<T> type;

    protected final String stdDesignDoreplacedentId;

    private DesignDoreplacedentFactory designDoreplacedentFactory;

    protected CouchDbRepositorySupport(Clreplaced<T> type, CouchDbConnector db) {
        this(type, db, true);
    }

    protected CouchDbRepositorySupport(Clreplaced<T> type, CouchDbConnector db, boolean createIfNotExists) {
        replacedert.notNull(db, "CouchDbConnector may not be null");
        replacedert.notNull(type);
        this.db = db;
        this.type = type;
        if (createIfNotExists) {
            db.createDatabaseIfNotExists();
        }
        stdDesignDoreplacedentId = NameConventions.designDocName(type);
    }

    /**
     * Alternative constructor allowing a custom design doreplacedent name (not linked to the type clreplaced name).
     *
     * @param type
     * @param db
     * @param designDocName
     */
    protected CouchDbRepositorySupport(Clreplaced<T> type, CouchDbConnector db, String designDocName) {
        this(type, db, designDocName, true);
    }

    /**
     * Alternative constructor allowing a custom design doreplacedent name (not linked to the type clreplaced name)
     * @param type repository type
     * @param db database connector
     * @param designDocName design doreplacedent Id
     * @param createIfNotExists true if db should be created if it doesnt' exist
     */
    protected CouchDbRepositorySupport(Clreplaced<T> type, CouchDbConnector db, String designDocName, boolean createIfNotExists) {
        replacedert.notNull(db, "CouchDbConnector may not be null");
        replacedert.notNull(type);
        this.db = db;
        this.type = type;
        if (createIfNotExists) {
            db.createDatabaseIfNotExists();
        }
        stdDesignDoreplacedentId = NameConventions.designDocName(designDocName);
    }

    /**
     * @throws UpdateConflictException if there was an update conflict.
     */
    public void add(T enreplacedy) {
        replacedertEnreplacedyNotNull(enreplacedy);
        replacedert.isTrue(Doreplacedents.isNew(enreplacedy), "enreplacedy must be new");
        db.create(enreplacedy);
    }

    /**
     * If the repository's design doreplacedent has a view named "all" it will be used
     * to fetch all doreplacedents of this repository's handled type.
     *
     * "all" must return doreplacedent ids that refers doreplacedents that are readable by this repository.
     *
     * If the "all"-view is not defined, all doreplacedents in the database (except design doreplacedents)
     * will be fetched. In this case the database must only contain doreplacedents that are readable by
     * this repository.
     *
     * @return all objects of this repository's handled type in the db.
     */
    public List<T> getAll() {
        if (designDocContainsAllView()) {
            return queryView("all");
        }
        return loadAllByAllDocIds();
    }

    private boolean designDocContainsAllView() {
        if (db.contains(stdDesignDoreplacedentId)) {
            DesignDoreplacedent dd = db.get(DesignDoreplacedent.clreplaced, stdDesignDoreplacedentId);
            return dd.containsView("all");
        }
        return false;
    }

    private List<T> loadAllByAllDocIds() {
        List<String> ids = db.getAllDocIds();
        List<T> all = new ArrayList<T>(ids.size());
        for (String id : ids) {
            if (!id.startsWith("_design")) {
                all.add(get(id));
            }
        }
        return all;
    }

    /**
     * @param id
     * @return
     * @throws DoreplacedentNotFoundException if the doreplacedent was not found.
     */
    public T get(String id) {
        return db.get(type, id);
    }

    /**
     * @param id
     * @param options
     * @return
     * @throws DoreplacedentNotFoundException if the doreplacedent was not found.
     */
    public T get(String id, Options options) {
        return db.get(type, id, options);
    }

    /**
     * @param id
     * @param rev
     * @return
     * @throws DoreplacedentNotFoundException if the doreplacedent was not found.
     * @deprecated use get(String id, Options options)
     */
    public T get(String id, String rev) {
        return db.get(type, id, rev);
    }

    public void remove(T enreplacedy) {
        replacedertEnreplacedyNotNull(enreplacedy);
        db.delete(Doreplacedents.getId(enreplacedy), Doreplacedents.getRevision(enreplacedy));
    }

    /**
     * @throws UpdateConflictException if there was an update conflict.
     */
    public void update(T enreplacedy) {
        replacedertEnreplacedyNotNull(enreplacedy);
        db.update(enreplacedy);
    }

    private void replacedertEnreplacedyNotNull(T enreplacedy) {
        replacedert.notNull(enreplacedy, "enreplacedy may not be null");
    }

    /**
     * Creates a ViewQuery pre-configured with correct dbPath, design doreplacedent id and view name.
     * @param viewName
     * @return
     */
    protected ViewQuery createQuery(String viewName) {
        return new ViewQuery().dbPath(db.path()).designDocId(stdDesignDoreplacedentId).viewName(viewName);
    }

    /**
     * Allows subclreplacedes to query views with simple String value keys
     * and load the result as the repository's handled type.
     *
     * The viewName must be defined in this repository's design doreplacedent.
     *
     * @param viewName
     * @param key
     * @return
     */
    protected List<T> queryView(String viewName, String key) {
        return db.queryView(createQuery(viewName).includeDocs(true).key(key), type);
    }

    /**
     * Allows subclreplacedes to query views with simple String value keys
     * and load the result as the repository's handled type.
     *
     * The viewName must be defined in this repository's design doreplacedent.
     *
     * @param viewName
     * @param keyValue
     * @return
     */
    protected List<T> queryView(String viewName, int key) {
        return db.queryView(createQuery(viewName).includeDocs(true).key(key), type);
    }

    /**
     * Allows subclreplacedes to query views with simple String value keys
     * and load the result as the repository's handled type.
     *
     * The viewName must be defined in this repository's design doreplacedent.
     *
     * @param viewName
     * @param key
     * @return
     */
    protected List<T> queryView(String viewName, ComplexKey key) {
        return db.queryView(createQuery(viewName).includeDocs(true).key(key), type);
    }

    /**
     * Allows subclreplacedes to query a view and load the result as the repository's handled type.
     *
     * The viewName must be defined in this repository's design doreplacedent.
     *
     * @param viewName
     * @return
     */
    protected List<T> queryView(String viewName) {
        return db.queryView(createQuery(viewName).includeDocs(true), type);
    }

    /**
     * <p>
     * Will create the standard design doreplacedent if it does not exists in the database.
     * </p>
     * <p>
     * Will also generate view definitions for finder methods defined in this clreplaced and annotated by the @GenerateView
     * annotation. The method name must adhere to the name convention of findBy[Property].
     * </p>
     * <p>
     * The method:
     * </p>
     * <code>
     * <pre>
     * @GenerateView
     * public List<Sofa> findByColor(String s) {
     * 	return queryView("by_color", s);
     * }
     * </pre>
     * </code>
     * <p>
     * Will result in a generated view named "by_color" in the doreplacedent _design/Sofa
     * </p>
     * <p>
     * Any existing view with the same name will be kept unchanged.
     *
     * TIP: The generated DesignDoreplacedent will be written to the log if debug log level is enabled.
     * </p>
     */
    public void initStandardDesignDoreplacedent() {
        initDesignDocInternal(0);
    }

    private void initDesignDocInternal(int invocations) {
        DesignDoreplacedent designDoc;
        if (db.contains(stdDesignDoreplacedentId)) {
            designDoc = getDesignDoreplacedentFactory().getFromDatabase(db, stdDesignDoreplacedentId);
        } else {
            designDoc = getDesignDoreplacedentFactory().newDesignDoreplacedentInstance();
            designDoc.setId(stdDesignDoreplacedentId);
        }
        log.debug("Generating DesignDoreplacedent for {}", getHandledType());
        DesignDoreplacedent generated = getDesignDoreplacedentFactory().generateFrom(this);
        boolean changed = designDoc.mergeWith(generated);
        if (log.isDebugEnabled()) {
            debugDesignDoc(designDoc);
        }
        if (changed) {
            log.debug("DesignDoreplacedent changed or new. Updating database");
            try {
                db.update(designDoc);
            } catch (UpdateConflictException e) {
                log.warn("Update conflict occurred when trying to update design doreplacedent: {}", designDoc.getId());
                if (invocations == 0) {
                    backOff();
                    log.info("retrying initStandardDesignDoreplacedent for design doreplacedent: {}", designDoc.getId());
                    initDesignDocInternal(1);
                }
            }
        } else {
            log.debug("DesignDoreplacedent was unchanged. Database was not updated.");
        }
    }

    /**
     * Wait a short while in order to prevent racing initializations from other repositories.
     */
    private void backOff() {
        try {
            Thread.sleep(new Random().nextInt(400));
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }

    protected void debugDesignDoc(DesignDoreplacedent generated) {
        ObjectMapper om = new ObjectMapper();
        om.configure(SerializationFeature.INDENT_OUTPUT, true);
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            String json = om.writeValuereplacedtring(generated);
            log.debug("DesignDoreplacedent source:\n" + json);
        } catch (Exception e) {
            log.error("Could not write generated design doreplacedent as json", e);
        }
    }

    public boolean contains(String docId) {
        return db.contains(docId);
    }

    public void setDesignDoreplacedentFactory(DesignDoreplacedentFactory df) {
        this.designDoreplacedentFactory = df;
    }

    protected DesignDoreplacedentFactory getDesignDoreplacedentFactory() {
        if (designDoreplacedentFactory == null) {
            designDoreplacedentFactory = new StdDesignDoreplacedentFactory();
        }
        return designDoreplacedentFactory;
    }

    Clreplaced<?> getHandledType() {
        return type;
    }
}

17 View Complete Implementation : StdObjectMapperFactory.java
Copyright Apache License 2.0
Author : helun
public ObjectMapper createObjectMapper(CouchDbConnector connector) {
    ObjectMapper objectMapper = new ObjectMapper();
    applyDefaultConfiguration(objectMapper);
    objectMapper.registerModule(new EktorpJacksonModule(connector, objectMapper));
    return objectMapper;
}

17 View Complete Implementation : App.java
Copyright Apache License 2.0
Author : IBM-Cloud
@Bean
public CouchDbConnector couchDbConnector(CouchDbInstance couchDbInstance) {
    CouchDbConnector connector = new StdCouchDbConnector("status", couchDbInstance);
    connector.createDatabaseIfNotExists();
    return connector;
}

17 View Complete Implementation : EktorpLuceneObjectMapperFactory.java
Copyright Apache License 2.0
Author : ldriscoll
@Override
public ObjectMapper createObjectMapper(CouchDbConnector connector) {
    ObjectMapper om = super.createObjectMapper(connector);
    applyDefaultConfiguration(om);
    return om;
}

17 View Complete Implementation : CouchProfileServiceTests.java
Copyright Apache License 2.0
Author : pac4j
/**
 * Tests the {@link CouchProfileService}.
 *
 * @author Elie Roux
 * @since 2.0.0
 */
public final clreplaced CouchProfileServiceTests implements TestsConstants {

    private static final String COUCH_ID_FIELD = CouchProfileService.COUCH_ID;

    private static final String COUCH_ID = "couchId";

    private static final String COUCH_LINKED_ID = "couchLinkedId";

    private static final String COUCH_USER = "couchUser";

    private static final String COUCH_USER2 = "couchUser2";

    private static final String COUCH_Preplaced = "couchPreplaced";

    private static final String COUCH_Preplaced2 = "couchPreplaced2";

    private static final String IDPERSON1 = "idperson1";

    private static final String IDPERSON2 = "idperson2";

    private static final String IDPERSON3 = "idperson3";

    public final static PreplacedwordEncoder PreplacedWORD_ENCODER = new ShiroPreplacedwordEncoder(new DefaultPreplacedwordService());

    private static final CouchServer couchServer = new CouchServer();

    private static final CouchDbConnector couchDbConnector = couchServer.start();

    @BeforeClreplaced
    public static void setUp() {
        final String preplacedword = PreplacedWORD_ENCODER.encode(PreplacedWORD);
        final CouchProfileService couchProfileService = new CouchProfileService(couchDbConnector);
        couchProfileService.setPreplacedwordEncoder(PreplacedWORD_ENCODER);
        // insert sample data
        final Map<String, Object> properties1 = new HashMap<>();
        properties1.put(USERNAME, GOOD_USERNAME);
        properties1.put(FIRSTNAME, FIRSTNAME_VALUE);
        CouchProfile couchProfile = new CouchProfile();
        couchProfile.build(IDPERSON1, properties1);
        couchProfileService.create(couchProfile, PreplacedWORD);
        // second person,
        final Map<String, Object> properties2 = new HashMap<>();
        properties2.put(USERNAME, MULTIPLE_USERNAME);
        couchProfile = new CouchProfile();
        couchProfile.build(IDPERSON2, properties2);
        couchProfileService.create(couchProfile, PreplacedWORD);
        final Map<String, Object> properties3 = new HashMap<>();
        properties3.put(USERNAME, MULTIPLE_USERNAME);
        properties3.put(PreplacedWORD, preplacedword);
        couchProfile = new CouchProfile();
        couchProfile.build(IDPERSON3, properties3);
        couchProfileService.create(couchProfile, PreplacedWORD);
    }

    @AfterClreplaced
    public static void tearDown() {
    // couchServer.stop();
    }

    @Test
    public void testNullConnector() {
        final CouchProfileService couchProfileService = new CouchProfileService(null);
        couchProfileService.setPreplacedwordEncoder(PreplacedWORD_ENCODER);
        TestsHelper.expectException(() -> couchProfileService.init(), TechnicalException.clreplaced, "couchDbConnector cannot be null");
    }

    @Test(expected = AccountNotFoundException.clreplaced)
    public void authentFailed() {
        final CouchProfileService couchProfileService = new CouchProfileService(couchDbConnector);
        couchProfileService.setPreplacedwordEncoder(PreplacedWORD_ENCODER);
        final UsernamePreplacedwordCredentials credentials = new UsernamePreplacedwordCredentials(BAD_USERNAME, PreplacedWORD);
        couchProfileService.validate(credentials, null);
    }

    @Test
    public void authentSuccessSingleAttribute() {
        final CouchProfileService couchProfileService = new CouchProfileService(couchDbConnector);
        couchProfileService.setPreplacedwordEncoder(PreplacedWORD_ENCODER);
        final UsernamePreplacedwordCredentials credentials = new UsernamePreplacedwordCredentials(GOOD_USERNAME, PreplacedWORD);
        couchProfileService.validate(credentials, null);
        final CommonProfile profile = credentials.getUserProfile();
        replacedertNotNull(profile);
        replacedertTrue(profile instanceof CouchProfile);
        final CouchProfile couchProfile = (CouchProfile) profile;
        replacedertEquals(GOOD_USERNAME, couchProfile.getUsername());
        replacedertEquals(2, couchProfile.getAttributes().size());
        replacedertEquals(FIRSTNAME_VALUE, couchProfile.getAttribute(FIRSTNAME));
    }

    @Test
    public void testCreateUpdateFindDelete() {
        final CouchProfile profile = new CouchProfile();
        profile.setId(COUCH_ID);
        profile.setLinkedId(COUCH_LINKED_ID);
        profile.addAttribute(USERNAME, COUCH_USER);
        final CouchProfileService couchProfileService = new CouchProfileService(couchDbConnector);
        couchProfileService.setPreplacedwordEncoder(PreplacedWORD_ENCODER);
        // create
        couchProfileService.create(profile, COUCH_Preplaced);
        // check credentials
        final UsernamePreplacedwordCredentials credentials = new UsernamePreplacedwordCredentials(COUCH_USER, COUCH_Preplaced);
        couchProfileService.validate(credentials, null);
        final CommonProfile profile1 = credentials.getUserProfile();
        replacedertNotNull(profile1);
        // check data
        final List<Map<String, Object>> results = getData(couchProfileService, COUCH_ID);
        replacedertEquals(1, results.size());
        final Map<String, Object> result = results.get(0);
        replacedertEquals(5, result.size());
        replacedertEquals(COUCH_ID, result.get(COUCH_ID_FIELD));
        replacedertEquals(COUCH_LINKED_ID, result.get(AbstractProfileService.LINKEDID));
        replacedertNotNull(result.get(AbstractProfileService.SERIALIZED_PROFILE));
        replacedertEquals(COUCH_USER, result.get(USERNAME));
        // findById
        final CouchProfile profile2 = couchProfileService.findById(COUCH_ID);
        replacedertEquals(COUCH_ID, profile2.getId());
        replacedertEquals(COUCH_LINKED_ID, profile2.getLinkedId());
        replacedertEquals(COUCH_USER, profile2.getUsername());
        replacedertEquals(1, profile2.getAttributes().size());
        // update with preplacedword
        profile.addAttribute(USERNAME, COUCH_USER2);
        couchProfileService.update(profile, COUCH_Preplaced2);
        List<Map<String, Object>> results2 = getData(couchProfileService, COUCH_ID);
        replacedertEquals(1, results2.size());
        Map<String, Object> result2 = results2.get(0);
        replacedertEquals(5, result2.size());
        replacedertEquals(COUCH_ID, result2.get(COUCH_ID_FIELD));
        replacedertEquals(COUCH_LINKED_ID, result2.get(AbstractProfileService.LINKEDID));
        replacedertNotNull(result2.get(AbstractProfileService.SERIALIZED_PROFILE));
        replacedertEquals(COUCH_USER2, result2.get(USERNAME));
        // check credentials
        final UsernamePreplacedwordCredentials credentials2 = new UsernamePreplacedwordCredentials(COUCH_USER2, COUCH_Preplaced2);
        couchProfileService.validate(credentials2, null);
        CommonProfile profile3 = credentials.getUserProfile();
        replacedertNotNull(profile3);
        // update with no preplacedword update
        couchProfileService.update(profile, null);
        results2 = getData(couchProfileService, COUCH_ID);
        replacedertEquals(1, results2.size());
        result2 = results2.get(0);
        replacedertEquals(5, result2.size());
        replacedertEquals(COUCH_USER2, result2.get(USERNAME));
        // check credentials
        couchProfileService.validate(credentials2, null);
        profile3 = credentials.getUserProfile();
        replacedertNotNull(profile3);
        // remove
        couchProfileService.remove(profile);
        final List<Map<String, Object>> results3 = getData(couchProfileService, COUCH_ID);
        replacedertEquals(0, results3.size());
    }

    private List<Map<String, Object>> getData(final CouchProfileService couchProfileService, final String id) {
        return couchProfileService.read(Arrays.asList(COUCH_ID_FIELD, "username", "linkedid", "preplacedword", "serializedprofile"), COUCH_ID_FIELD, id);
    }
}

17 View Complete Implementation : FFMpegSetterUpper.java
Copyright Apache License 2.0
Author : ryanramage
protected String installFFMpegAndReturnLocation(File workingDir, CouchDbConnector connector, String designDocName) throws NotImplementedException {
    try {
        installLocalffmpg(workingDir, connector, designDocName);
        String localFile = findLocalFFMpeg(workingDir);
        if (localFile != null)
            return localFile;
        // if we are here, we cant find ffmpeg
        throw new NotImplementedException("FFMpeg can't be found.");
    } catch (IOException ex) {
        Logger.getLogger(FFMpegSetterUpper.clreplaced.getName()).log(Level.SEVERE, null, ex);
        throw new NotImplementedException("FFMpeg can't be found.");
    }
}

17 View Complete Implementation : FFMpegSetterUpper.java
Copyright Apache License 2.0
Author : ryanramage
protected void installLocalffmpg(File storDir, CouchDbConnector connector, String designDoc) throws IOException {
    String attachmentName = null;
    if (SystemUtils.IS_OS_WINDOWS) {
        attachmentName = windowsAttachmentName;
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        attachmentName = macAttachmentName;
    } else {
        return;
    }
    File zip = downloadLocalZip(storDir, connector, designDoc, attachmentName);
    unzip(zip, storDir);
    zip.delete();
}

17 View Complete Implementation : App.java
Copyright Apache License 2.0
Author : ryanramage
public CouchDbConnector getSrcConnector() {
    int couchPort = src_port;
    if (couchPort <= 0)
        couchPort = 5984;
    StdHttpClient.Builder builder = new StdHttpClient.Builder().host(src_host).port(couchPort);
    if (src_username != null && src_username != "") {
        builder.username(src_username);
        builder.preplacedword(src_preplacedword);
    }
    HttpClient httpClient = builder.build();
    CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    CouchDbConnector db = new StdCouchDbConnector(src_db, dbInstance);
    return db;
}

17 View Complete Implementation : App.java
Copyright Apache License 2.0
Author : ryanramage
public void start() throws Exception {
    try {
        showSplashDialog();
        couchDbInstance = localCouchManager.getCouchInstance();
        CouchDbConnector db = localCouchManager.getCouchConnector(localDbName, couchDbInstance);
        DbInfo info = db.getDbInfo();
        ready(db);
    } catch (CouchDBNotFoundException nfe) {
        ready(loadNeeded(true));
    } catch (Exception noInfo) {
        ready(loadNeeded(false));
    }
}

17 View Complete Implementation : ICureDAOImpl.java
Copyright GNU General Public License v2.0
Author : taktik
@Repository("iCureDAO")
public clreplaced ICureDAOImpl implements ICureDAO {

    CouchDbConnector couchdbConfig;

    CouchDbInstance couchdbInstance;

    private Gson gson = new GsonBuilder().create();

    @Override
    public Map<String, Number> getIndexingStatus() {
        HttpResponse active_tasks = couchdbConfig.getConnection().getUncached("/_active_tasks");
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(active_tasks.getContent(), "UTF8");
            List<Map<String, Object>> json = gson.fromJson(inputStreamReader, List.clreplaced);
            Map<String, List<Number>> statusesMap = new HashMap<>();
            for (Map<String, Object> status : json) {
                String designDoc = (String) status.get("design_doreplacedent");
                Number progress = (Number) status.get("progress");
                if (designDoc != null && progress != null) {
                    List<Number> statuses = statusesMap.get(designDoc);
                    if (statuses == null) {
                        statusesMap.put(designDoc, statuses = new LinkedList<>());
                    }
                    statuses.add(progress);
                }
            }
            Map<String, Number> results = new HashMap<>();
            for (Map.Entry<String, List<Number>> e : statusesMap.entrySet()) {
                results.put(e.getKey(), e.getValue().stream().collect(Collectors.averagingInt(Number::intValue)));
            }
            return results;
        } catch (UnsupportedEncodingException e) {
        // 
        }
        return null;
    }

    @Autowired
    public void setCouchdbConfig(CouchDbConnector couchdbConfig) {
        this.couchdbConfig = couchdbConfig;
    }

    @Autowired
    public void setCouchdbInstance(CouchDbInstance couchdbInstance) {
        this.couchdbInstance = couchdbInstance;
    }
}

17 View Complete Implementation : CouchDbDataContextTest.java
Copyright Apache License 2.0
Author : apache
public clreplaced CouchDbDataContextTest extends CouchDbTestSupport {

    private HttpClient httpClient;

    private StdCouchDbInstance couchDbInstance;

    private CouchDbConnector connector;

    private SimpleTableDef predefinedTableDef;

    @Before
    public void before() throws Exception {
        loadConfiguration();
        if (isConfigured()) {
            // 8 seconds should be more than
            final int timeout = 8 * 1000;
            // enough
            httpClient = new StdHttpClient.Builder().socketTimeout(timeout).host(getHostname()).build();
            // set up a simple database
            couchDbInstance = new StdCouchDbInstance(httpClient);
            final String databaseName = getDatabaseName();
            if (couchDbInstance.getAllDatabases().contains(databaseName)) {
                throw new IllegalStateException("Couch DB instance already has a database called " + databaseName);
            }
            connector = couchDbInstance.createConnector(databaseName, true);
            final String[] columnNames = new String[] { "name", "gender", "age" };
            final ColumnType[] columnTypes = new ColumnType[] { ColumnType.STRING, ColumnType.CHAR, ColumnType.INTEGER };
            predefinedTableDef = new SimpleTableDef(databaseName, columnNames, columnTypes);
        }
    }

    @After
    public void after() {
        connector = null;
        if (isConfigured()) {
            couchDbInstance.deleteDatabase(getDatabaseName());
            httpClient.shutdown();
        }
    }

    @Test
    public void testWorkingWithMapsAndLists() throws Exception {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        connector = couchDbInstance.createConnector("test_table_map_and_list", true);
        final CouchDbDataContext dc = new CouchDbDataContext(couchDbInstance, new SimpleTableDef("test_table_map_and_list", new String[] { "id", "foo", "bar" }, new ColumnType[] { ColumnType.INTEGER, ColumnType.MAP, ColumnType.LIST }));
        Table table = null;
        try {
            table = dc.getTableByQualifiedLabel("test_table_map_and_list");
            Map<String, Object> exampleMap = new LinkedHashMap<String, Object>();
            exampleMap.put("hello", Arrays.asList("world", "welt", "verden"));
            exampleMap.put("foo", "bar");
            List<Map<String, Object>> exampleList = new ArrayList<Map<String, Object>>();
            exampleList.add(new LinkedHashMap<String, Object>());
            Map<String, Object> exampleMap2 = new LinkedHashMap<String, Object>();
            exampleMap2.put("meta", "model");
            exampleMap2.put("couch", "db");
            exampleList.add(exampleMap2);
            dc.executeUpdate(new InsertInto(table).value("id", 1).value("foo", exampleMap).value("bar", exampleList));
            DataSet ds = dc.query().from(table).select("id", "foo", "bar").execute();
            replacedertTrue(ds.next());
            Row row = ds.getRow();
            replacedertFalse(ds.next());
            ds.close();
            replacedertEquals("Row[values=[1, {hello=[world, welt, verden], foo=bar}, [{}, {meta=model, couch=db}]]]", row.toString());
            replacedertTrue(row.getValue(0) instanceof Integer);
            replacedertTrue(row.getValue(1) instanceof Map);
            replacedertTrue(row.getValue(2) instanceof List);
            CouchDbDataContext dc2 = new CouchDbDataContext(couchDbInstance, new SimpleTableDef("test_table_map_and_list", new String[] { "foo.hello[0]", "bar[1].couch" }));
            ds = dc2.query().from("test_table_map_and_list").select("foo.hello[0]", "bar[1].couch").execute();
            replacedertTrue(ds.next());
            replacedertEquals("Row[values=[world, db]]", ds.getRow().toString());
            replacedertFalse(ds.next());
            ds.close();
        } finally {
            dc.executeUpdate(new DropTable(table));
        }
    }

    @Test
    public void testCreateUpdateDeleteScenario() throws Exception {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        final String databaseName = getDatabaseName();
        {
            // insert a doreplacedent to provide data to do inferential schema
            // detection
            final CouchDbConnector connector = couchDbInstance.createConnector(databaseName, false);
            final Map<String, Object> map = new HashMap<String, Object>();
            map.put("foo", "bar");
            map.put("bar", "baz");
            map.put("baz", 1234);
            connector.addToBulkBuffer(map);
            connector.flushBulkBuffer();
        }
        final CouchDbDataContext dc = new CouchDbDataContext(couchDbInstance);
        Table table = dc.getDefaultSchema().getTableByName(databaseName);
        replacedertNotNull(table);
        replacedertEquals("[Column[name=_id,columnNumber=0,type=STRING,nullable=false,nativeType=null,columnSize=null], " + "Column[name=_rev,columnNumber=1,type=STRING,nullable=false,nativeType=null,columnSize=null], " + "Column[name=bar,columnNumber=2,type=STRING,nullable=null,nativeType=null,columnSize=null], " + "Column[name=baz,columnNumber=3,type=INTEGER,nullable=null,nativeType=null,columnSize=null], " + "Column[name=foo,columnNumber=4,type=STRING,nullable=null,nativeType=null,columnSize=null]]", Arrays.toString(table.getColumns().toArray()));
        // first delete the manually created database!
        dc.executeUpdate(new UpdateScript() {

            @Override
            public void run(UpdateCallback callback) {
                callback.dropTable(databaseName).execute();
            }
        });
        table = dc.getDefaultSchema().getTableByName(databaseName);
        replacedertNull(table);
        dc.executeUpdate(new UpdateScript() {

            @Override
            public void run(UpdateCallback callback) {
                Table table = callback.createTable(dc.getDefaultSchema(), databaseName).withColumn("foo").ofType(ColumnType.STRING).withColumn("greeting").ofType(ColumnType.STRING).execute();
                replacedertEquals("[_id, _rev, foo, greeting]", Arrays.toString(table.getColumnNames().toArray()));
            }
        });
        dc.executeUpdate(new UpdateScript() {

            @Override
            public void run(UpdateCallback callback) {
                callback.insertInto(databaseName).value("foo", "bar").value("greeting", "hello").execute();
                callback.insertInto(databaseName).value("foo", "baz").value("greeting", "hi").execute();
            }
        });
        DataSet ds = dc.query().from(databaseName).select("_id", "foo", "greeting").execute();
        replacedertTrue(ds.next());
        replacedertNotNull(ds.getRow().getValue(0));
        replacedertEquals("bar", ds.getRow().getValue(1));
        replacedertEquals("hello", ds.getRow().getValue(2));
        replacedertTrue(ds.next());
        replacedertNotNull(ds.getRow().getValue(0));
        replacedertEquals("baz", ds.getRow().getValue(1));
        replacedertEquals("hi", ds.getRow().getValue(2));
        replacedertFalse(ds.next());
        ds.close();
        dc.executeUpdate(new UpdateScript() {

            @Override
            public void run(UpdateCallback callback) {
                callback.update(databaseName).value("greeting", "howdy").where("foo").isEquals("baz").execute();
                callback.update(databaseName).value("foo", "foo").where("foo").isEquals("bar").execute();
            }
        });
        ds = dc.query().from(databaseName).select("_id", "foo", "greeting").execute();
        replacedertTrue(ds.next());
        replacedertNotNull(ds.getRow().getValue(0));
        replacedertEquals("foo", ds.getRow().getValue(1));
        replacedertEquals("hello", ds.getRow().getValue(2));
        replacedertTrue(ds.next());
        replacedertNotNull(ds.getRow().getValue(0));
        replacedertEquals("baz", ds.getRow().getValue(1));
        replacedertEquals("howdy", ds.getRow().getValue(2));
        replacedertFalse(ds.next());
        ds.close();
    }

    @Test
    public void testBasicQuery() throws Exception {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        // insert a few records
        {
            HashMap<String, Object> map;
            map = new HashMap<String, Object>();
            map.put("name", "John Doe");
            map.put("age", 30);
            connector.create(map);
            map = new HashMap<String, Object>();
            map.put("name", "Jane Doe");
            map.put("gender", 'F');
            connector.create(map);
        }
        // create datacontext using detected schema
        CouchDbDataContext dc = new CouchDbDataContext(couchDbInstance, getDatabaseName());
        // verify schema and execute query
        Schema schema = dc.getMainSchema();
        replacedertEquals("[" + getDatabaseName() + "]", Arrays.toString(schema.getTableNames().toArray()));
        replacedertEquals("[_id, _rev, age, gender, name]", Arrays.toString(schema.getTableByName(getDatabaseName()).getColumnNames().toArray()));
        Column idColumn = schema.getTableByName(getDatabaseName()).getColumnByName("_id");
        replacedertEquals("Column[name=_id,columnNumber=0,type=STRING,nullable=false,nativeType=null,columnSize=null]", idColumn.toString());
        replacedertTrue(idColumn.isPrimaryKey());
        replacedertEquals("Column[name=_rev,columnNumber=1,type=STRING,nullable=false,nativeType=null,columnSize=null]", schema.getTableByName(getDatabaseName()).getColumnByName("_rev").toString());
        DataSet ds;
        ds = dc.query().from(getDatabaseName()).select("name").and("age").execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[John Doe, 30]]", ds.getRow().toString());
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[Jane Doe, null]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name").and("gender").where("age").isNull().execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[Jane Doe, F]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("_id").where("name").eq("Jane Doe").execute();
        replacedertTrue(ds.next());
        Object pkValue = ds.getRow().getValue(0);
        replacedertFalse(ds.next());
        ds.close();
        // Test greater than or equals
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").greaterThanOrEquals(29).execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[John Doe, 30]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").greaterThanOrEquals(30).execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[John Doe, 30]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").greaterThanOrEquals(31).execute();
        replacedertFalse(ds.next());
        ds.close();
        // Test less than or equals
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").lessThanOrEquals(31).execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[John Doe, 30]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").lessThanOrEquals(30).execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[John Doe, 30]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name").and("age").where("age").lessThanOrEquals(29).execute();
        replacedertFalse(ds.next());
        ds.close();
        // test primary key lookup query
        ds = dc.query().from(getDatabaseName()).select("name").and("gender").where("_id").eq(pkValue).execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[Jane Doe, F]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
        // test primary key null
        ds = dc.query().from(getDatabaseName()).select("name").and("gender").where("_id").isNull().execute();
        replacedertFalse(ds.next());
        ds.close();
        // test primary key not found
        ds = dc.query().from(getDatabaseName()).select("name").and("gender").where("_id").eq("this id does not exist").execute();
        replacedertFalse(ds.next());
        ds.close();
    }

    @Test
    public void testFirstRowAndLastRow() throws Exception {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        // insert a few records
        {
            HashMap<String, Object> map;
            map = new HashMap<String, Object>();
            map.put("name", "John Doe");
            map.put("age", 30);
            connector.create(map);
            map = new HashMap<String, Object>();
            map.put("name", "Jane Doe");
            map.put("gender", 'F');
            connector.create(map);
        }
        // create datacontext using detected schema
        final String databaseName = getDatabaseName();
        final CouchDbDataContext dc = new CouchDbDataContext(couchDbInstance, databaseName);
        final DataSet ds1 = dc.query().from(databaseName).select("name").and("age").firstRow(2).execute();
        final DataSet ds2 = dc.query().from(databaseName).select("name").and("age").maxRows(1).execute();
        replacedertTrue("Clreplaced: " + ds1.getClreplaced().getName(), ds1 instanceof CouchDbDataSet);
        replacedertTrue("Clreplaced: " + ds2.getClreplaced().getName(), ds2 instanceof CouchDbDataSet);
        replacedertTrue(ds1.next());
        replacedertTrue(ds2.next());
        final Row row1 = ds1.getRow();
        final Row row2 = ds2.getRow();
        replacedertFalse(ds1.next());
        replacedertFalse(ds2.next());
        replacedertEquals("Row[values=[Jane Doe, null]]", row1.toString());
        replacedertEquals("Row[values=[John Doe, 30]]", row2.toString());
        ds1.close();
        ds2.close();
    }

    @Test
    public void testInsert() throws Exception {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        // create datacontext using predefined table def
        CouchDbDataContext dc = new CouchDbDataContext(httpClient, predefinedTableDef);
        Table table = dc.getTableByQualifiedLabel(getDatabaseName());
        replacedertNotNull(table);
        replacedertEquals("[_id, _rev, name, gender, age]", Arrays.toString(table.getColumnNames().toArray()));
        DataSet ds;
        // replacedert not rows in DB
        ds = dc.query().from(getDatabaseName()).selectCount().execute();
        replacedertTrue(ds.next());
        replacedertEquals(0, ((Number) ds.getRow().getValue(0)).intValue());
        replacedertFalse(ds.next());
        ds.close();
        dc.executeUpdate(new UpdateScript() {

            @Override
            public void run(UpdateCallback callback) {
                callback.insertInto(getDatabaseName()).value("name", "foo").value("gender", 'M').execute();
                callback.insertInto(getDatabaseName()).value("name", "bar").value("age", 32).execute();
            }
        });
        // now count should be 2
        ds = dc.query().from(getDatabaseName()).selectCount().execute();
        replacedertTrue(ds.next());
        replacedertEquals(2, ((Number) ds.getRow().getValue(0)).intValue());
        replacedertFalse(ds.next());
        ds.close();
        ds = dc.query().from(getDatabaseName()).select("name", "gender", "age").execute();
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[foo, M, null]]", ds.getRow().toString());
        replacedertTrue(ds.next());
        replacedertEquals("Row[values=[bar, null, 32]]", ds.getRow().toString());
        replacedertFalse(ds.next());
        ds.close();
    }

    @Test
    public void testSelectNestedObject() {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        try (DataSet ds = executeNestedObjectQuery("SELECT name.given FROM " + getDatabaseName() + " WHERE id = 42")) {
            replacedertTrue(ds.next());
            replacedertEquals("John", (String) ds.getRow().getValue(0));
            replacedertFalse(ds.next());
        }
    }

    @Test
    public void testWhereNestedObject() {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        try (DataSet ds = executeNestedObjectQuery("SELECT id FROM " + getDatabaseName() + " WHERE name.given = 'Jane'")) {
            replacedertTrue(ds.next());
            replacedertEquals(43, ((Number) ds.getRow().getValue(0)).intValue());
            replacedertFalse(ds.next());
        }
    }

    @Test
    public void testSelectAndWhereNestedObject() {
        if (!isConfigured()) {
            System.err.println(getInvalidConfigurationMessage());
            return;
        }
        try (DataSet ds = executeNestedObjectQuery("SELECT name.family FROM " + getDatabaseName() + " WHERE name.given = 'Jane'")) {
            replacedertTrue(ds.next());
            replacedertEquals("Johnson", (String) ds.getRow().getValue(0));
            replacedertFalse(ds.next());
        }
    }

    // reusable method for a couple of test cases above
    private DataSet executeNestedObjectQuery(String sql) {
        // insert a few records
        {
            HashMap<String, String> name = new HashMap<>();
            name.put("given", "John");
            name.put("family", "Doe");
            HashMap<String, Object> map;
            map = new HashMap<>();
            map.put("id", 42);
            map.put("name", name);
            connector.create(map);
            name.put("given", "Jane");
            name.put("family", "Johnson");
            map = new HashMap<>();
            map.put("id", 43);
            map.put("name", name);
            connector.create(map);
        }
        final CouchDbDataContext dataContext = new CouchDbDataContext(httpClient);
        replacedertTrue(dataContext.getDefaultSchema().getTableNames().contains(getDatabaseName()));
        final Table table = dataContext.getDefaultSchema().getTableByName(getDatabaseName());
        replacedertEquals("[_id, _rev, id, name]", table.getColumnNames().toString());
        return dataContext.executeQuery(sql);
    }
}

17 View Complete Implementation : CouchDbConnectionManager.java
Copyright Apache License 2.0
Author : cfibmers
public clreplaced CouchDbConnectionManager {

    private static final Logger logger = Logger.getLogger(CouchDbConnectionManager.clreplaced);

    private CouchDbConnector db;

    private CouchDbInstance dbInstance;

    public CouchDbConnectionManager(String dbName, String userName, String preplacedword, String host, int port, boolean enableSSL, int timeout) {
        db = null;
        try {
            db = initConnection(dbName, userName, preplacedword, host, port, enableSSL, timeout);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public CouchDbConnector getDb() {
        return db;
    }

    public void setDb(CouchDbConnector db) {
        this.db = db;
    }

    private CouchDbConnector initConnection(String dbName, String userName, String preplacedword, String host, int port, boolean enableSSL, int timeout) {
        Builder builder = new StdHttpClient.Builder().host(host).port(port).connectionTimeout(timeout).socketTimeout(timeout).enableSSL(enableSSL);
        if (userName != null && !userName.isEmpty() && preplacedword != null && !preplacedword.isEmpty())
            builder.username(userName).preplacedword(preplacedword);
        dbInstance = new StdCouchDbInstance(builder.build());
        if (!dbInstance.checkIfDbExists(dbName))
            dbInstance.createDatabase(dbName);
        CouchDbConnector couchDB = dbInstance.createConnector(dbName, true);
        return couchDB;
    }

    public boolean deleteDB(String dbName) {
        if (dbInstance != null && dbInstance.checkIfDbExists(dbName)) {
            dbInstance.deleteDatabase(dbName);
            return true;
        } else
            return false;
    }
}

17 View Complete Implementation : BackReferencedBeanSerializer.java
Copyright Apache License 2.0
Author : helun
public clreplaced BackReferencedBeanSerializer<T> extends JsonSerializer<T> {

    private final JsonSerializer<T> delegate;

    private final List<BeanPropertyWriter> doreplacedentReferenceFields;

    private final CouchDbConnector couchDbConnector;

    public BackReferencedBeanSerializer(JsonSerializer<T> delegate, List<BeanPropertyWriter> list, CouchDbConnector couchDbConnector) {
        this.delegate = delegate;
        this.doreplacedentReferenceFields = list;
        this.couchDbConnector = couchDbConnector;
    }

    @Override
    public void serialize(T value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        Set<Object> docsToSave = new LinkedHashSet<Object>();
        try {
            for (BeanPropertyWriter writer : doreplacedentReferenceFields) {
                if (!cascadeUpdates(writer.getName(), value)) {
                    continue;
                }
                Object o = writer.get(value);
                findDoreplacedentsToSave(docsToSave, o);
            }
            if (docsToSave.size() > 0) {
                List<DoreplacedentOperationResult> res = couchDbConnector.executeBulk(docsToSave);
                if (res.size() > 0) {
                    throwBulkUpdateError(res);
                }
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
        delegate.serialize(value, jgen, provider);
    }

    private boolean cascadeUpdates(final String propertyName, Object value) {
        DoreplacedentReferences referenceMetaData = ReflectionUtils.findAnnotation(value.getClreplaced(), DoreplacedentReferences.clreplaced, new Predicate<Field>() {

            public boolean apply(Field input) {
                return propertyName.equals(input.getName());
            }
        });
        for (CascadeType t : referenceMetaData.cascade()) {
            if (CascadeType.PERSIST_TYPES.contains(t)) {
                return true;
            }
        }
        return false;
    }

    private void throwBulkUpdateError(List<DoreplacedentOperationResult> res) {
        StringBuilder sb = new StringBuilder();
        int maxErrors = 10;
        for (DoreplacedentOperationResult docResult : res) {
            if (maxErrors == 0) {
                sb.append(".. " + res.size() + " more ");
                break;
            }
            sb.append(docResult.getId());
            sb.append(" ");
            sb.append(docResult.getError());
            sb.append(" ");
            sb.append(docResult.getReason());
            sb.append(" ");
            maxErrors--;
        }
        throw new DbAccessException(sb.toString());
    }

    private void findDoreplacedentsToSave(Set<Object> docsToSave, Object o) {
        if (o == null) {
            return;
        }
        if (Proxy.isProxyClreplaced(o.getClreplaced()) && Proxy.getInvocationHandler(o) instanceof ViewBasedCollection) {
            ViewBasedCollection c = (ViewBasedCollection) Proxy.getInvocationHandler(o);
            if (c.initialized()) {
                docsToSave.addAll((Collection<?>) o);
                docsToSave.addAll(c.getPendingRemoval());
            }
        } else if (o instanceof Collection && ((Collection<?>) o).size() > 0) {
            docsToSave.addAll((Collection<?>) o);
        }
    }
}

17 View Complete Implementation : EktorpJacksonModule.java
Copyright Apache License 2.0
Author : helun
public clreplaced EktorpJacksonModule extends Module {

    private final static Version VERSION = new Version(1, 2, 0, null);

    private final CouchDbConnector db;

    private final ObjectMapper objectMapper;

    public EktorpJacksonModule(CouchDbConnector db, ObjectMapper objectMapper) {
        replacedert.notNull(db, "CouchDbConnector may not be null");
        replacedert.notNull(objectMapper, "ObjectMapper may not be null");
        this.db = db;
        this.objectMapper = objectMapper;
    }

    @Override
    public String getModuleName() {
        return "EktorpDocRefModule";
    }

    @Override
    public Version version() {
        return VERSION;
    }

    @Override
    public void setupModule(SetupContext context) {
        context.insertAnnotationIntrospector(new EktorpAnnotationIntrospector());
        context.addBeanDeserializerModifier(new EktorpBeanDeserializerModifier(db, objectMapper));
        context.addBeanSerializerModifier(new EktorpBeanSerializerModifier(db));
    }
}

16 View Complete Implementation : CouchDBStore.java
Copyright Apache License 2.0
Author : apache
/**
 * Implementation of a CouchDB data store to be used by gora.
 *
 * @param <K> clreplaced to be used for the key
 * @param <T> clreplaced to be persisted within the store
 */
public clreplaced CouchDBStore<K, T extends PersistentBase> extends DataStoreBase<K, T> {

    /**
     * Logging implementation
     */
    protected static final Logger LOG = LoggerFactory.getLogger(CouchDBStore.clreplaced);

    /**
     * The default file name value to be used for obtaining the CouchDB object field mapping's
     */
    public static final String DEFAULT_MAPPING_FILE = "gora-couchdb-mapping.xml";

    /**
     * for bulk doreplacedent operations
     */
    private final List<Object> bulkDocs = new ArrayList<>();

    /**
     * Mapping definition for CouchDB
     */
    private CouchDBMapping mapping;

    /**
     * The standard implementation of the CouchDbInstance interface. This interface provides methods for
     * managing databases on the connected CouchDb instance.
     * StdCouchDbInstance is thread-safe.
     */
    private CouchDbInstance dbInstance;

    /**
     * The standard implementation of the CouchDbConnector interface. This interface provides methods for
     * manipulating doreplacedents within a specific database.
     * StdCouchDbConnector is thread-safe.
     */
    private CouchDbConnector db;

    /**
     * Initialize the data store by reading the credentials, setting the client's properties up and
     * reading the mapping file. Initialize is called when then the call to
     * {@link org.apache.gora.store.DataStoreFactory#createDataStore} is made.
     *
     * @param keyClreplaced
     * @param persistentClreplaced
     * @param properties
     * @throws GoraException
     */
    @Override
    public void initialize(Clreplaced<K> keyClreplaced, Clreplaced<T> persistentClreplaced, Properties properties) throws GoraException {
        LOG.debug("Initializing CouchDB store");
        super.initialize(keyClreplaced, persistentClreplaced, properties);
        final CouchDBParameters params = CouchDBParameters.load(properties);
        try {
            final String mappingFile = DataStoreFactory.getMappingFile(properties, this, DEFAULT_MAPPING_FILE);
            final HttpClient httpClient = new StdHttpClient.Builder().url("http://" + params.getServer() + ":" + params.getPort()).build();
            dbInstance = new StdCouchDbInstance(httpClient);
            final CouchDBMappingBuilder<K, T> builder = new CouchDBMappingBuilder<>(this);
            LOG.debug("Initializing CouchDB store with mapping {}.", new Object[] { mappingFile });
            builder.readMapping(mappingFile);
            mapping = builder.build();
            final ObjectMapperFactory myObjectMapperFactory = new CouchDBObjectMapperFactory();
            myObjectMapperFactory.createObjectMapper().addMixInAnnotations(persistentClreplaced, CouchDbDoreplacedent.clreplaced);
            db = new StdCouchDbConnector(mapping.getDatabaseName(), dbInstance, myObjectMapperFactory);
            db.createDatabaseIfNotExists();
        } catch (Exception e) {
            throw new GoraException("Error while initializing CouchDB store", e);
        }
    }

    /**
     * In CouchDB, Schemas are referred to as database name.
     *
     * @return databasename
     */
    @Override
    public String getSchemaName() {
        return mapping.getDatabaseName();
    }

    /**
     * In CouchDB, Schemas are referred to as database name.
     *
     * @param mappingSchemaName the name of the schema as read from the mapping file
     * @param persistentClreplaced   persistent clreplaced
     * @return database name
     */
    @Override
    public String getSchemaName(final String mappingSchemaName, final Clreplaced<?> persistentClreplaced) {
        return super.getSchemaName(mappingSchemaName, persistentClreplaced);
    }

    /**
     * Create a new database in CouchDB if necessary.
     */
    @Override
    public void createSchema() throws GoraException {
        try {
            if (schemaExists()) {
                return;
            }
            dbInstance.createDatabase(mapping.getDatabaseName());
        } catch (GoraException e) {
            throw e;
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    /**
     * Drop the database.
     */
    @Override
    public void deleteSchema() throws GoraException {
        try {
            if (schemaExists()) {
                dbInstance.deleteDatabase(mapping.getDatabaseName());
            }
        } catch (GoraException e) {
            throw e;
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    /**
     * Check if the database already exists or should be created.
     */
    @Override
    public boolean schemaExists() throws GoraException {
        try {
            return dbInstance.checkIfDbExists(mapping.getDatabaseName());
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    /**
     * Retrieve an entry from the store with only selected fields.
     *
     * @param key    identifier of the doreplacedent in the database
     * @param fields list of fields to be loaded from the database
     */
    @Override
    public T get(final K key, final String[] fields) throws GoraException {
        final Map<String, Object> result;
        try {
            result = db.get(Map.clreplaced, key.toString());
            return newInstance(result, getFieldsToQuery(fields));
        } catch (DoreplacedentNotFoundException e) {
            return null;
        } catch (GoraException e) {
            throw e;
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    @Override
    public boolean exists(final K key) throws GoraException {
        try {
            return db.contains(key.toString());
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    /**
     * Persist an object into the store.
     *
     * @param key identifier of the object in the store
     * @param obj the object to be inserted
     */
    @Override
    public void put(K key, T obj) throws GoraException {
        final Map<String, Object> buffer = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
        buffer.put("_id", key);
        Schema schema = obj.getSchema();
        List<Field> fields = schema.getFields();
        for (int i = 0; i < fields.size(); i++) {
            if (!obj.isDirty(i)) {
                continue;
            }
            Field field = fields.get(i);
            Object fieldValue = obj.get(field.pos());
            Schema fieldSchema = field.schema();
            // check if field has a nested structure (array, map, record or union)
            fieldValue = toDBObject(fieldSchema, fieldValue);
            buffer.put(field.name(), fieldValue);
        }
        bulkDocs.add(buffer);
    }

    private Map<String, Object> mapToCouchDB(final Object fieldValue) {
        final Map<String, Object> newMap = new LinkedHashMap<>();
        final Map<?, ?> fieldMap = (Map<?, ?>) fieldValue;
        if (fieldValue == null) {
            return null;
        }
        for (Object key : fieldMap.keySet()) {
            newMap.put(key.toString(), fieldMap.get(key).toString());
        }
        return newMap;
    }

    private List<Object> listToCouchDB(final Schema fieldSchema, final Object fieldValue) {
        final List<Object> list = new LinkedList<>();
        for (Object obj : (List<Object>) fieldValue) {
            list.add(toDBObject(fieldSchema.getElementType(), obj));
        }
        return list;
    }

    private Map<String, Object> recordToCouchDB(final Schema fieldSchema, final Object fieldValue) {
        final PersistentBase persistent = (PersistentBase) fieldValue;
        final Map<String, Object> newMap = new LinkedHashMap<>();
        if (persistent != null) {
            for (Field member : fieldSchema.getFields()) {
                Schema memberSchema = member.schema();
                Object memberValue = persistent.get(member.pos());
                newMap.put(member.name(), toDBObject(memberSchema, memberValue));
            }
            return newMap;
        }
        return null;
    }

    private String bytesToCouchDB(final Object fieldValue) {
        return new String(((ByteBuffer) fieldValue).array(), StandardCharsets.UTF_8);
    }

    private Object unionToCouchDB(final Schema fieldSchema, final Object fieldValue) {
        Schema.Type type0 = fieldSchema.getTypes().get(0).getType();
        Schema.Type type1 = fieldSchema.getTypes().get(1).getType();
        // Check if types are different and there's a "null", like ["null","type"]
        // or ["type","null"]
        if (!type0.equals(type1) && (type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL))) {
            Schema innerSchema = fieldSchema.getTypes().get(1);
            LOG.debug("Transform value to DBObject (UNION), schemaType:{}, type1:{}", new Object[] { innerSchema.getType(), type1 });
            // Deserialize as if schema was ["type"]
            return toDBObject(innerSchema, fieldValue);
        } else {
            throw new IllegalStateException("CouchDBStore doesn't support 3 types union field yet. Please update your mapping");
        }
    }

    private Object toDBObject(final Schema fieldSchema, final Object fieldValue) {
        final Object result;
        switch(fieldSchema.getType()) {
            case MAP:
                result = mapToCouchDB(fieldValue);
                break;
            case ARRAY:
                result = listToCouchDB(fieldSchema, fieldValue);
                break;
            case RECORD:
                result = recordToCouchDB(fieldSchema, fieldValue);
                break;
            case BYTES:
                result = bytesToCouchDB(fieldValue);
                break;
            case ENUM:
            case STRING:
                result = fieldValue.toString();
                break;
            case UNION:
                result = unionToCouchDB(fieldSchema, fieldValue);
                break;
            default:
                result = fieldValue;
                break;
        }
        return result;
    }

    /**
     * Deletes the object with the given key
     *
     * @param key the key of the object
     * @return whether the object was successfully deleted
     */
    @Override
    public boolean delete(K key) throws GoraException {
        if (key == null) {
            deleteSchema();
            createSchema();
            return true;
        }
        try {
            final String keyString = key.toString();
            final Map<String, Object> referenceData = db.get(Map.clreplaced, keyString);
            return StringUtils.isNotEmpty(db.delete(keyString, referenceData.get("_rev").toString()));
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    /**
     * Deletes all the objects matching the query.
     * See also the note on <a href="#visibility">visibility</a>.
     *
     * @param query matching records to this query will be deleted
     * @return number of deleted records
     */
    @Override
    public long deleteByQuery(Query<K, T> query) throws GoraException {
        final K key = query.getKey();
        final K startKey = query.getStartKey();
        final K endKey = query.getEndKey();
        if (key == null && startKey == null && endKey == null) {
            deleteSchema();
            createSchema();
            return -1;
        } else {
            try {
                final ViewQuery viewQuery = new ViewQuery().allDocs().includeDocs(true).key(key).startKey(startKey).endKey(endKey);
                final List<Map> result = db.queryView(viewQuery, Map.clreplaced);
                final Map<String, List<String>> revisionsToPurge = new HashMap<>();
                for (Map map : result) {
                    final List<String> revisions = new ArrayList<>();
                    String keyString = map.get("_id").toString();
                    String rev = map.get("_rev").toString();
                    revisions.add(rev);
                    revisionsToPurge.put(keyString, revisions);
                }
                return db.purge(revisionsToPurge).getPurged().size();
            } catch (Exception e) {
                throw new GoraException(e);
            }
        }
    }

    /**
     * Create a new {@link Query} to query the datastore.
     */
    @Override
    public Query<K, T> newQuery() {
        CouchDBQuery<K, T> query = new CouchDBQuery<>(this);
        query.setFields(getFieldsToQuery(null));
        return query;
    }

    /**
     * Execute the query and return the result.
     */
    @Override
    public Result<K, T> execute(Query<K, T> query) throws GoraException {
        try {
            query.setFields(getFieldsToQuery(query.getFields()));
            final ViewQuery viewQuery = new ViewQuery().allDocs().includeDocs(true).startKey(query.getStartKey()).endKey(query.getEndKey()).limit(// FIXME GORA have long value but ektorp client use integer
            Ints.checkedCast(query.getLimit()));
            CouchDBResult<K, T> couchDBResult = new CouchDBResult<>(this, query, db.queryView(viewQuery, Map.clreplaced));
            return couchDBResult;
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    @Override
    public List<ParreplacedionQuery<K, T>> getParreplacedions(Query<K, T> query) throws IOException {
        final List<ParreplacedionQuery<K, T>> list = new ArrayList<>();
        final ParreplacedionQueryImpl<K, T> pqi = new ParreplacedionQueryImpl<>(query);
        pqi.setConf(getConf());
        list.add(pqi);
        return list;
    }

    /**
     * Creates a new Persistent instance with the values in 'result' for the fields listed.
     *
     * @param result result from the query to the database
     * @param fields the list of fields to be mapped to the persistence clreplaced instance
     * @return a persistence clreplaced instance which content was deserialized
     * @throws GoraException
     */
    public T newInstance(Map<String, Object> result, String[] fields) throws GoraException {
        if (result == null)
            return null;
        T persistent = newPersistent();
        // Populate each field
        for (String fieldName : fields) {
            if (result.get(fieldName) == null) {
                continue;
            }
            final Field field = fieldMap.get(fieldName);
            final Schema fieldSchema = field.schema();
            LOG.debug("Load from DBObject (MAIN), field:{}, schemaType:{}, docField:{}", new Object[] { field.name(), fieldSchema.getType(), fieldName });
            final Object resultObj = fromDBObject(fieldSchema, field, fieldName, result);
            persistent.put(field.pos(), resultObj);
            persistent.setDirty(field.pos());
        }
        persistent.clearDirty();
        return persistent;
    }

    private Object fromCouchDBRecord(final Schema fieldSchema, final String docf, final Object value) throws GoraException {
        final Object innerValue = ((Map) value).get(docf);
        if (innerValue == null) {
            return null;
        }
        Clreplaced<?> clazz = null;
        try {
            clazz = ClreplacedLoadingUtils.loadClreplaced(fieldSchema.getFullName());
        } catch (ClreplacedNotFoundException e) {
            throw new GoraException(e);
        }
        final PersistentBase record = (PersistentBase) new BeanFactoryImpl(keyClreplaced, clazz).newPersistent();
        for (Field recField : fieldSchema.getFields()) {
            Schema innerSchema = recField.schema();
            record.put(recField.pos(), fromDBObject(innerSchema, recField, recField.name(), innerValue));
        }
        return record;
    }

    private Object fromCouchDBMap(final Schema fieldSchema, final Field field, final String docf, final Object value) throws GoraException {
        final Map<String, Object> map = (Map<String, Object>) ((Map<String, Object>) value).get(docf);
        final Map<Utf8, Object> rmap = new HashMap<>();
        if (map == null) {
            return new DirtyMapWrapper(rmap);
        }
        for (Map.Entry<String, Object> e : map.entrySet()) {
            Schema innerSchema = fieldSchema.getValueType();
            ;
            Object o = fromDBObject(innerSchema, field, e.getKey(), e.getValue());
            rmap.put(new Utf8(e.getKey()), o);
        }
        return new DirtyMapWrapper<>(rmap);
    }

    private Object fromCouchDBUnion(final Schema fieldSchema, final Field field, final String docf, final Object value) throws GoraException {
        // schema [type0, type1]
        Object result;
        Schema.Type type0 = fieldSchema.getTypes().get(0).getType();
        Schema.Type type1 = fieldSchema.getTypes().get(1).getType();
        // Check if types are different and there's a "null", like ["null","type"]
        // or ["type","null"]
        if (!type0.equals(type1) && (type0.equals(Schema.Type.NULL) || type1.equals(Schema.Type.NULL))) {
            Schema innerSchema = fieldSchema.getTypes().get(1);
            LOG.debug("Load from DBObject (UNION), schemaType:{}, docField:{}, storeType:{}", new Object[] { innerSchema.getType(), docf });
            // Deserialize as if schema was ["type"]
            result = fromDBObject(innerSchema, field, docf, value);
        } else {
            throw new GoraException("CouchDBStore doesn't support 3 types union field yet. Please update your mapping");
        }
        return result;
    }

    private Object fromCouchDBList(final Schema fieldSchema, final Field field, final String docf, final Object value) throws GoraException {
        final List<Object> list = (List<Object>) ((Map<String, Object>) value).get(docf);
        final List<Object> rlist = new ArrayList<>();
        if (list == null) {
            return new DirtyListWrapper(rlist);
        }
        for (Object item : list) {
            Object o = fromDBObject(fieldSchema.getElementType(), field, "item", item);
            rlist.add(o);
        }
        return new DirtyListWrapper<>(rlist);
    }

    private Object fromCouchDBEnum(final Schema fieldSchema, final String docf, final Object value) {
        final Object result;
        if (value instanceof Map) {
            result = AvroUtils.getEnumValue(fieldSchema, (String) ((Map) value).get(docf));
        } else {
            result = AvroUtils.getEnumValue(fieldSchema, (String) value);
        }
        return result;
    }

    private Object fromCouchDBBytes(final String docf, final Object value) {
        final byte[] array;
        if (value instanceof Map) {
            array = ((String) ((Map) value).get(docf)).getBytes(StandardCharsets.UTF_8);
        } else {
            array = ((String) value).getBytes(StandardCharsets.UTF_8);
        }
        return ByteBuffer.wrap(array);
    }

    private Object fromCouchDBString(final String docf, final Object value) {
        final Object result;
        if (value instanceof Map) {
            result = new Utf8((String) ((Map) value).get(docf));
        } else {
            result = new Utf8((String) value);
        }
        return result;
    }

    private Object fromDBObject(final Schema fieldSchema, final Field field, final String docf, final Object value) throws GoraException {
        if (value == null) {
            return null;
        }
        final Object result;
        switch(fieldSchema.getType()) {
            case MAP:
                result = fromCouchDBMap(fieldSchema, field, docf, value);
                break;
            case ARRAY:
                result = fromCouchDBList(fieldSchema, field, docf, value);
                break;
            case RECORD:
                result = fromCouchDBRecord(fieldSchema, docf, value);
                break;
            case UNION:
                result = fromCouchDBUnion(fieldSchema, field, docf, value);
                break;
            case ENUM:
                result = fromCouchDBEnum(fieldSchema, docf, value);
                break;
            case BYTES:
                result = fromCouchDBBytes(docf, value);
                break;
            case STRING:
                result = fromCouchDBString(docf, value);
                break;
            case LONG:
            case DOUBLE:
            case INT:
                result = ((Map) value).get(docf);
                break;
            default:
                result = value;
        }
        return result;
    }

    @Override
    public void flush() throws GoraException {
        try {
            db.executeBulk(bulkDocs);
            bulkDocs.clear();
            db.flushBulkBuffer();
        } catch (Exception e) {
            throw new GoraException(e);
        }
    }

    @Override
    public void close() {
        try {
            flush();
        } catch (GoraException e) {
            // Log and ignore. We are closing... so is doest not matter if it just died
            LOG.warn("Error flushing when closing", e);
        }
    }
}

16 View Complete Implementation : CouchDbUpdateCallback.java
Copyright Apache License 2.0
Author : apache
public CouchDbConnector getConnector(String name) {
    CouchDbConnector connector = _connectors.get(name);
    if (connector == null) {
        CouchDbInstance instance = getDataContext().getCouchDbInstance();
        connector = instance.createConnector(name, false);
        _connectors.put(name, connector);
    }
    return connector;
}

16 View Complete Implementation : CouchDbConnectionManager.java
Copyright Apache License 2.0
Author : cfibmers
private CouchDbConnector initConnection(String dbName, String userName, String preplacedword, String host, int port, boolean enableSSL, int timeout) {
    Builder builder = new StdHttpClient.Builder().host(host).port(port).connectionTimeout(timeout).socketTimeout(timeout).enableSSL(enableSSL);
    if (userName != null && !userName.isEmpty() && preplacedword != null && !preplacedword.isEmpty())
        builder.username(userName).preplacedword(preplacedword);
    dbInstance = new StdCouchDbInstance(builder.build());
    if (!dbInstance.checkIfDbExists(dbName))
        dbInstance.createDatabase(dbName);
    CouchDbConnector couchDB = dbInstance.createConnector(dbName, true);
    return couchDB;
}

16 View Complete Implementation : GitTrace.java
Copyright GNU General Public License v3.0
Author : coast-team
public static GitTrace create(String gitdir, CouchConnector cc, String path, boolean cleanDB, boolean detectMaU, int ut, int mt) throws IOException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repo = builder.setGitDir(new File(gitdir + "/.git")).readEnvironment().findGitDir().build();
    CouchDbInstance dbInstance = cc.getDbInstance();
    String prefix = clearName(gitdir, path), co = prefix + "_commit", pa = prefix + "_patch";
    CouchDbConnector dbcc = new StdCouchDbConnector(co, dbInstance);
    CouchDbConnector dbcp = new StdCouchDbConnector(pa, dbInstance);
    CommitCRUD commitCRUD;
    PatchCRUD patchCRUD;
    if (cleanDB || !dbInstance.checkIfDbExists(new DbPath(co)) || !dbInstance.checkIfDbExists(new DbPath(pa))) {
        clearDB(dbInstance, co);
        clearDB(dbInstance, pa);
        commitCRUD = new CommitCRUD(dbcc);
        patchCRUD = new PatchCRUD(dbcp);
        GitExtraction ge = new GitExtraction(repo, commitCRUD, patchCRUD, GitExtraction.defaultDiffAlgorithm, path, detectMaU, ut, mt);
        ge.parseRepository();
        UpdBefore = ge.nbUpdBlockBefore;
        MoveBefore = ge.nbMoveBefore;
        MergeBefore = ge.nbrMergeBefore;
        returnStat = ge.returnLastStat;
        commitRevert = ge.commitReverted;
    } else {
        commitCRUD = new CommitCRUD(dbcc);
        patchCRUD = new PatchCRUD(dbcp);
    }
    return new GitTrace(commitCRUD, patchCRUD, detectMaU, ut, mt);
}

16 View Complete Implementation : BackReferencedBeanDeserializer.java
Copyright Apache License 2.0
Author : helun
/**
 * @author ragnar rova
 */
public clreplaced BackReferencedBeanDeserializer extends StdDeserializer<Object> implements ResolvableDeserializer {

    private final CouchDbConnector couchDbConnector;

    private final BeanDeserializer delegate;

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SE_BAD_FIELD")
    private final List<ConstructibleAnnotatedCollection> backReferencedFields;

    private final Clreplaced<?> clazz;

    public BackReferencedBeanDeserializer(BeanDeserializer deserializer, List<ConstructibleAnnotatedCollection> fields, CouchDbConnector couchDbConnector, Clreplaced<?> clazz) {
        super(clazz);
        this.clazz = clazz;
        this.delegate = deserializer;
        this.couchDbConnector = couchDbConnector;
        this.backReferencedFields = fields;
    }

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        Object deserializedObject = delegate.deserialize(jp, ctxt);
        addbackReferencedFields(deserializedObject, ctxt);
        return deserializedObject;
    }

    private void addbackReferencedFields(Object deserializedObject, DeserializationContext ctxt) throws IOException {
        String id = Doreplacedents.getId(deserializedObject);
        for (ConstructibleAnnotatedCollection constructibleField : this.backReferencedFields) {
            DoreplacedentReferences ann = constructibleField.getField().getAnnotation(DoreplacedentReferences.clreplaced);
            try {
                ViewBasedCollection handler;
                if (ann.fetch().equals(FetchType.EAGER)) {
                    handler = new ViewBasedCollection(id, couchDbConnector, clazz, ann, constructibleField);
                    handler.initialize();
                } else {
                    handler = new LazyLoadingViewBasedCollection(id, couchDbConnector, clazz, ann, constructibleField);
                }
                Object o = Proxy.newProxyInstance(constructibleField.getCollectionType().getRawClreplaced().getClreplacedLoader(), new Clreplaced[] { constructibleField.getCollectionType().getRawClreplaced() }, handler);
                constructibleField.getSetter().set(deserializedObject, o);
            } catch (Exception e) {
                throw new IOException("Failed creating reflection proxy for collection " + constructibleField, e);
            }
        }
    }

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object intoValue) throws IOException, JsonProcessingException {
        Object deserializedObject = super.deserialize(jp, ctxt, intoValue);
        addbackReferencedFields(deserializedObject, ctxt);
        return deserializedObject;
    }

    @Override
    public void resolve(DeserializationContext ctxt) throws JsonMappingException {
        delegate.resolve(ctxt);
    }
}

16 View Complete Implementation : SimpleViewGeneratorTest.java
Copyright Apache License 2.0
Author : helun
@Test
public void given_a_discriminator_is_declared_then_all_view_should_be_generated() {
    CouchDbConnector db = mock(CouchDbConnector.clreplaced);
    DiscriminatingRepo repo = new DiscriminatingRepo(db);
    Map<String, DesignDoreplacedent.View> result = gen.generateViews(repo);
    replacedertEquals(expectedAutoGeneratedAllView, result.get("all").getMap());
}

16 View Complete Implementation : SimpleViewGeneratorTest.java
Copyright Apache License 2.0
Author : helun
@Test
public void given_a_custom_discriminator_is_declared_then_it_should_be_used() {
    CouchDbConnector db = mock(CouchDbConnector.clreplaced);
    CustomDiscriminatingRepo repo = new CustomDiscriminatingRepo(db);
    Map<String, DesignDoreplacedent.View> result = gen.generateViews(repo);
    replacedertEquals(expectedAllViewWithCustomDiscriminator, result.get("all").getMap());
}

16 View Complete Implementation : SimpleViewGeneratorTest.java
Copyright Apache License 2.0
Author : helun
@Test
public void given_a_discriminator_is_declared_on_iterable_field_then_views_should_filter_for_specified_property() {
    CouchDbConnector db = mock(CouchDbConnector.clreplaced);
    DiscriminatingRepo repo = new DiscriminatingRepo(db);
    Map<String, DesignDoreplacedent.View> result = gen.generateViews(repo);
    replacedertEquals(expectedArrayFunctionWithDiscriminator, result.get("by_domainName").getMap());
}

16 View Complete Implementation : SimpleViewGeneratorTest.java
Copyright Apache License 2.0
Author : helun
@Test
public void given_a_discriminator_is_declared_on_child_type_then_docrefs_view_should_use_it() {
    CouchDbConnector db = mock(CouchDbConnector.clreplaced);
    DiscriminatingRepo repo = new DiscriminatingRepo(db);
    Map<String, DesignDoreplacedent.View> result = gen.generateViews(repo);
    replacedertEquals(expectedDocrefsFunctionWhereChildHasDiscriminator, result.get("ektorp_docrefs_children").getMap());
}

16 View Complete Implementation : SimpleViewGeneratorTest.java
Copyright Apache License 2.0
Author : helun
@Test
public void given_a_discriminator_is_declared_on_getter_then_all_view_should_be_generated() {
    CouchDbConnector db = mock(CouchDbConnector.clreplaced);
    GenericRepository<DiscriminatorOnMethodType> repo = new CouchDbRepositorySupport<DiscriminatorOnMethodType>(DiscriminatorOnMethodType.clreplaced, db) {

        @GenerateView
        @Override
        public List<DiscriminatorOnMethodType> getAll() {
            return super.getAll();
        }
    };
    Map<String, DesignDoreplacedent.View> result = gen.generateViews(repo);
    replacedertEquals(expectedAutoGeneratedAllView, result.get("all").getMap());
}