Skip to content

DATAMONGO-479 - Add support for calling functions. #254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
4 changes: 2 additions & 2 deletions spring-data-mongodb-cross-store/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down Expand Up @@ -48,7 +48,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
</dependency>

<dependency>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-log4j/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.7.0.BUILD-SNAPSHOT</version>
<version>1.7.0.DATAMONGO-479-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;

import static java.util.UUID.*;
import static org.springframework.data.mongodb.core.query.Criteria.*;
import static org.springframework.data.mongodb.core.query.Query.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.bson.types.ObjectId;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.script.CallableMongoScript;
import org.springframework.data.mongodb.core.script.ServerSideJavaScript;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.mongodb.DB;
import com.mongodb.MongoException;

/**
* Default implementation of {@link ScriptOperations} capable of saving and executing {@link ServerSideJavaScript}.
*
* @author Christoph Strobl
* @since 1.7
*/
public class DefaultScriptOperations implements ScriptOperations {

private static final String SCRIPT_COLLECTION_NAME = "system.js";
private static final String SCRIPT_NAME_PREFIX = "func_";
private final MongoOperations mongoOperations;

/**
* Creates new {@link DefaultScriptOperations} using given {@link MongoOperations}.
*
* @param mongoOperations must not be {@literal null}.
*/
public DefaultScriptOperations(MongoOperations mongoOperations) {

Assert.notNull(mongoOperations, "MongoOperations must not be null!");

this.mongoOperations = mongoOperations;
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#save(org.springframework.data.mongodb.core.script.MongoScript)
*/
@Override
public CallableMongoScript register(ServerSideJavaScript script) {

Assert.notNull(script, "Script must not be null!");

CallableMongoScript callableScript = (script instanceof CallableMongoScript) ? (CallableMongoScript) script
: new CallableMongoScript(generateScriptName(), script);
mongoOperations.save(callableScript, SCRIPT_COLLECTION_NAME);
return callableScript;
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#execute(org.springframework.data.mongodb.core.script.MongoScript, java.lang.Object[])
*/
@Override
public Object execute(final ServerSideJavaScript script, final Object... args) {

Assert.notNull(script, "Script must not be null!");

if (script instanceof CallableMongoScript) {
return call(((CallableMongoScript) script).getName(), args);
}

return mongoOperations.execute(new DbCallback<Object>() {

@Override
public Object doInDB(DB db) throws MongoException, DataAccessException {

Assert.notNull(script.getCode(), "Script.code must not be null!");

return db.eval(script.getCode(), convertScriptArgs(args));
}
});
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#call(java.lang.String, java.lang.Object[])
*/
@Override
public Object call(final String scriptName, final Object... args) {

Assert.hasText(scriptName, "ScriptName must not be null or empty!");

return mongoOperations.execute(new DbCallback<Object>() {

@Override
public Object doInDB(DB db) throws MongoException, DataAccessException {

String evalString = scriptName + "(" + convertAndJoinScriptArgs(args) + ")";
return db.eval(evalString);
}
});
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#exists(java.lang.String)
*/
@Override
public Boolean exists(String scriptName) {

Assert.hasText(scriptName, "ScriptName must not be null or empty!");

return mongoOperations.exists(query(where("name").is(scriptName)), CallableMongoScript.class,
SCRIPT_COLLECTION_NAME);
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ScriptOperations#scriptNames()
*/
@Override
public Set<String> scriptNames() {

List<CallableMongoScript> scripts = (mongoOperations.findAll(CallableMongoScript.class, SCRIPT_COLLECTION_NAME));

if (CollectionUtils.isEmpty(scripts)) {
return Collections.emptySet();
}

Set<String> scriptNames = new HashSet<String>();
for (CallableMongoScript script : scripts) {
scriptNames.add(script.getName());
}
return scriptNames;
}

/**
* Generate a valid name for the {@literal JavaScript}. MongoDB requires an id of type String for scripts. Calling
* scripts having {@link ObjectId} as id fails. Therefore we create a random UUID without {@code -} (as this won't
* work) an prefix the result with {@link #SCRIPT_NAME_PREFIX}.
*
* @return
*/
private String generateScriptName() {
return SCRIPT_NAME_PREFIX + randomUUID().toString().replaceAll("-", "");
}

private Object[] convertScriptArgs(Object... args) {

if (ObjectUtils.isEmpty(args)) {
return args;
}

List<Object> convertedValues = new ArrayList<Object>(args.length);
for (Object arg : args) {
if (arg instanceof String) {
convertedValues.add("'" + arg + "'");
} else {
convertedValues.add(this.mongoOperations.getConverter().convertToMongoType(arg));
}
}
return convertedValues.toArray();
}

private String convertAndJoinScriptArgs(Object... args) {

if (ObjectUtils.isEmpty(args)) {
return "";
}

return StringUtils.arrayToCommaDelimitedString(convertScriptArgs(args));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,14 @@ public interface MongoOperations {
*/
IndexOperations indexOps(Class<?> entityClass);

/**
* Returns the {@link ScriptOperations} that can be performed on {@link com.mongodb.DB} level.
*
* @return
* @since 1.7
*/
ScriptOperations scriptOps();

/**
* Query for a list of objects of type T from the collection used by the entity class.
* <p/>
Expand Down Expand Up @@ -978,4 +986,5 @@ <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Cl
* @return
*/
MongoConverter getConverter();

}
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,15 @@ public IndexOperations indexOps(Class<?> entityClass) {
return new DefaultIndexOperations(this, determineCollectionName(entityClass));
}

/*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.MongoOperations#scriptOps()
*/
@Override
public ScriptOperations scriptOps() {
return new DefaultScriptOperations(this);
}

// Find methods that take a Query to express the query and that return a single object.

public <T> T findOne(Query query, Class<T> entityClass) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core;

import java.util.Set;

import org.springframework.data.mongodb.core.script.CallableMongoScript;
import org.springframework.data.mongodb.core.script.ServerSideJavaScript;

import com.mongodb.DB;

/**
* Script operations on {@link com.mongodb.DB} level. Allows interaction with server side {@literal JavaScript}
* functions.
*
* @author Christoph Strobl
* @since 1.7
*/
public interface ScriptOperations {

/**
* Store given {@literal script} to {@link com.mongodb.DB} so it can be called via its name.
*
* @param script must not be {@literal null}.
* @return {@link CallableMongoScript} with name under which the {@literal JavaScript} function can be called.
*/
CallableMongoScript register(ServerSideJavaScript script);

/**
* Executes the {@literal script} by either calling it via its {@literal name} or directly sending it.
*
* @param script must not be {@literal null}.
* @param args arguments to pass on for script execution.
* @return the script evaluation result.
* @throws org.springframework.dao.DataAccessException
*/
Object execute(ServerSideJavaScript script, Object... args);

/**
* Call the {@literal JavaScript} by its name.
*
* @param scriptName must not be {@literal null} or empty.
* @param args
* @return
*/
Object call(String scriptName, Object... args);

/**
* Checks {@link DB} for existence of {@link ServerSideJavaScript} with given name.
*
* @param scriptName must not be {@literal null} or empty.
* @return false if no {@link ServerSideJavaScript} with given name exists.
*/
Boolean exists(String scriptName);

/**
* Returns names of {@literal JavaScript} functions that can be called.
*
* @return empty {@link Set} if no scripts found.
*/
Set<String> scriptNames();

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.mongodb.core.convert.MongoConverters.BigDecimalToStringConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.BigIntegerToStringConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.CallableMongoScriptToDBObjectConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.DBObjectToCallableMongoScriptCoverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.DBObjectToStringConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.StringToBigDecimalConverter;
import org.springframework.data.mongodb.core.convert.MongoConverters.StringToBigIntegerConverter;
Expand Down Expand Up @@ -118,6 +120,8 @@ public CustomConversions(List<?> converters) {
toRegister.add(StringToURLConverter.INSTANCE);
toRegister.add(DBObjectToStringConverter.INSTANCE);
toRegister.add(TermToStringConverter.INSTANCE);
toRegister.add(CallableMongoScriptToDBObjectConverter.INSTANCE);
toRegister.add(DBObjectToCallableMongoScriptCoverter.INSTANCE);

toRegister.addAll(JodaTimeConverters.getConvertersToRegister());
toRegister.addAll(GeoConverters.getConvertersToRegister());
Expand Down
Loading