Unable to stub partial_search for chefspec - search

I'm writing a cookbook that runs a partial search to find an attribute on other nodes. My chefspec test is failing with error ERROR: Connection refused connecting to localhost:443. The search is instantiated as below:
describe 'my_recipe::default' do
let(:test1_node) do
stub_node('test1.com', platform: 'redhat', version: '6.3') do |node|
node.set['my_recipe']['id'] = 101
node.set['chef_environment'] = 'production'
end
end
let(:test2_node) do
stub_node('test2.com', platform: 'redhat', version: '6.3') do |node|
node.set['my_recipe']['id'] = 102
node.set['chef_environment'] = 'production'
end
end
before do
stub_search("node", "my_recipe:* AND chef_environment:production").and_return([])
end
let(:chef_run) do
ChefSpec::Runner.new do |node|
env = Chef::Environment.new
env.name 'production'
node.stub(:chef_environment).and_return(env.name)
Chef::Environment.stub(:load).and_return(env)
end.converge(described_recipe)
end
it 'updates the file' do
stub_search("node", "my_recipe:* AND chef_environment:production").and_return([test1_node,test2_node])
expect(chef_run).to create_template(/conf/my_recipe.cfg")
end
end
Am I stubbing this incorrectly?

stub_search is for stubbing Chef Search. Partial search is supported by a cookbook and therefore not part of Chef core. Partial search uses a different API endpoint and uses POST instead of GET for the protocol.
You'll need to stub Chef's API calls to partial search. stub_search will not work.

Related

How to add janus graph imports to gremlin groovy script engine?

I use GremlinGroovyScriptEngine, which is part of gremlin-server to evaluate string gremlin queries - like this:
final ScriptEngine engine = new GremlinGroovyScriptEngine();
engine.eval("g.V().count().next();");
... everything was good until I have started to use janus-graph specific elements in queries - like that (last string):
final ScriptEngine engine = new GremlinGroovyScriptEngine();
//== Set binding with traversal/graph/transaction to script engine ===
JanusGraphManagement mgmt = jg.openManagement();
SimpleBindings trBinding = new SimpleBindings();
trBinding.putAll(this.bindings);
trBinding.put("mgmt", mgmt);
engine.setBindings(trBinding, ScriptContext.ENGINE_SCOPE);
result = engine.eval("mgmt.makePropertyKey('zzzzzz').dataType(String.class).cardinality(Cardinality.SINGLE).make();");
... in that case I got:
MissingPropertyException: No such property: SINGLE for class: org.apache.tinkerpop.gremlin.structure.VertexProperty$Cardinality
As workaround I define whole class name org.janusgraph.core.Cardinality.SINGLE in query.
As I understand it is possible to set up all specific import to script engine during its creation.
Janus specific imports is defined in JanusGraphGremlinPlugin class which I use during gremlin-script-engine initialization in this way:
JanusGraphGremlinPlugin graphGremlinPlugin = JanusGraphGremlinPlugin.instance();
GremlinScriptEngineManager engineManager = new CachedGremlinScriptEngineManager();
/* Create gremlin script engine */
GremlinGroovyScriptEngine engine = GremlinGroovyScriptEngine.class
.cast(engineManager.getEngineByName("gremlin-groovy"));
... but it does not work. It seems that engineManager not set any plugins because after creation of engine engine.getPlugins().size() gives 0.
Also there is direct method of engine for loading plugin:
...
engine.loadPlugins(Collections.singletonList(graphGremlinPlugin))
...
... but it receive List of instances of org.apache.tinkerpop.gremlin.groovy.plugin.GremlinPlugin class which is deprecated (replaced by org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin).
Moreover JanusGraphGremlinPlugin class is descendant of org.apache.tinkerpop.gremlin.jsr223.AbstractGremlinPlugin so that it cannot be used in .loadPlugins() method.
Do you know how it is possible to use JanusGraphGremlinPlugin class to add janus-specific imports to gremlin-groovy-engine?
You need to add the plugin to the GremlinScriptEngineManager instance:
GremlinScriptEngineManager engineManager = new CachedGremlinScriptEngineManager();
engineManager.addPlugin(JanusGraphGremlinPlugin.instance())
engine = engineManager.getEngineByName("gremlin-groovy")
As long as the plugin is added before you instantiate the engine, it should work.

Call Scala Functions from Excel/VBA

I know that with C++ one can create DLL files that contain certain functions, which can then be imported into Excel (e.g. via VBA). Let us take the following C++ function
double __stdcall square_it(double &x)
{
return x*x;
}
which we assume is incorporated in square.dll so that we can use the following VBA import
Declare PtrSafe Function square_it Lib "square.dll" (ByRef x As Double) As Double
Private Sub TestSub()
MsgBox square_it(4.5)
End Sub
So my question is: is it possible to code a function in Scala and then call it from VBA in a similar fashion?
Scala is not going to be any different from Java here, and looking at Java questions such as Can you use Java libraries in a VB.net program? and Calling Java library (JAR) from VBA/VBScript/Visual Basic Classic, there are not good solutions to get the same level of integration you have with VBA/C++ in VBA/Java or VBA/Scala.
You can always use any external channel to comunicate between your VBA and your Scala, such at a shell, the file system, or even http, but that's not going to be as straightforward and efficient as your VBA/C++ example.
Here is what it could look like comunicating through a shell:
In example.scala:
object Example {
def main(args: Array[String]): Unit = {
val d = args.head.toDouble
println(d * d)
}
}
In example.vba:
Module Example
Sub Main()
Dim command As String
command = "scala /path/to/example.scala 123"
Range("A1").Value = CreateObject("WScript.Shell").Exec(command).StdOut.ReadAll
End Sub
End Module
Scala runs on the JVM, and VBA does not, Therefore there is no native way to pass objects between them.
There are two alternatives to communicate between Scala and VBA:
One option is to start a new process for each procedure call and parse the output, as #OlivierBlanvillain suggested in his answer.
I think that the preferred method, is communicating in web sockets, and particularly http using a web server.
Web Server
Use a scala web server (there are tons of them), for example scalatra, and each procedure call should be mapped to a http request to localhost:
Scala server code (with scalatra)
class ScalaCall extends ScalatraServlet {
get("/:func/:params") {
Calling function {params("func")} with parameters {params("params")}
}
}
VBA Client code
Public Function ScalaCall(ByVal func As String, ByVal params As String) As String
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", "http://127.0.0.1/" & func & "/" & params, False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
ScalaCall = WinHttpReq.ResponseBody
End If
End Function
Calling ScalaCall("f","x") on VBA should invoke a request to the scala server, that will output Calling function f with parameters x
You could use Obba - A Java Object Handler for Excel, LibreOffice and OpenOffice.

Search from code using FullTextSqlQuery - Search Service unavailable

I'm trying to search a Sharepoint 2007 site using the FullTextSqlQuery class, but I keep getting the following error "The search request was unable to connect to the Search Service"
My code looks like this
create a new FullTextSqlQuery class - use property intializers to set query
scope = "BuySale";
FullTextSqlQuery myQuery = new FullTextSqlQuery(SPContext.Current.Site)
{
QueryText = "SELECT Path FROM SCOPE() WHERE \"SCOPE\" = '" + scope + "'",
ResultTypes = ResultType.RelevantResults
};
ResultTableCollection queryResults = myQuery.Execute();
ResultTable queryResultsTable = queryResults[ResultType.RelevantResults];
queryDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);
Error from ULS log is this
Danish version
Log Query: Søgeanmodningen kunne ikke oprette forbindelse til
søgetjenesten. Yderligere oplysninger: Object or data matching the
name, range, or selection criteria was not found within the scope of
this operation.
English version
Log Query: The search request was unable to connect to the Search Service. Yderligere oplysninger: Object or data matching the
name, range, or selection criteria was not found within the scope of
this operation.
I've checked that all services is running and the scope exits.
I'm able to use the scope using sharepoint normal search and using the "SearchCoder" app that can help create search query.
Any ideas would be greatly appreciated.
Found the soltuion after spending a few more hours on google.
I was using the wrong dll to resolve the FullTextSqlQuery class
I was using this
Microsoft.SharePoint.Search.Query // WSS
but should have been using this
using Microsoft.Office.Server.Search.Query // MOSS
Thanks to Chris O'Connor
http://sharepointroot.com/2009/11/14/fulltextsqlquery-throwing-exception-this-site-is-not-assigned-to-an-indexer

return codes for Jira workflow script validators

I'm writing a workflow validator in Groovy to link two issues based on a custom field value input at case creation. It is required that the custom filed value to Jira issue link be unique. In other words, I need to ensure only one issue has a particular custom field value. If there is more than one issue that has the input custom field value, the validation should fail.
How or what do I return to cause a workflow validator to fail?
Example code:
// Set up jqlQueryParser object
jqlQueryParser = ComponentManager.getComponentInstanceOfType(JqlQueryParser.class) as JqlQueryParser
// Form the JQL query
query = jqlQueryParser.parseQuery('<my_jql_query>')
// Set up SearchService object used to query Jira
searchService = componentManager.getSearchService()
// Run the query to get all issues with Article number that match input
results = searchService.search(componentManager.getJiraAuthenticationContext().getUser(), query, PagerFilter.getUnlimitedFilter())
// Throw a FATAL level log statement because we should never have more than one case associated with a given KB article
if (results.getIssues().size() > 1) {
for (r in results.getIssues()) {
log.fatal('Custom field has more than one Jira ssue associated with it. ' + r.getKey() + ' is one of the offending issues')
}
return "?????"
}
// Create link from new Improvement to parent issue
for (r in results) {
IssueLinkManager.createIssueLink(issue.getId(), r.getId(), 10201, 1, getJiraAuthenticationContext().getUser())
}
try something like
import com.opensymphony.workflow.InvalidInputException
invalidInputException = new InvalidInputException("Validation failure")
this is based of the groovy script runner. If it doesn't work for you, i would recommend you using some sort of framework to make scripting easier, I like using either groovy script runner , Jira Scripting Suite or Behaviours Plugin
. All of them really makes script writing easier and much more intuitive.

ActionDispatch::ClosedError when testing Rails 3.1 model creation (RSpec/Cucumber)

I am creating a web application with Ruby on Rails 3.1 (RC1). I am using Factory Girl, RSpec and Cucumber (with Capybara) for testing, but I am experiencing unexpected raised ActionDispatch::ClosedErrors some of the times (not every time) when I am creating new users (through the User model's create action). Below is the error message that I get:
Cannot modify cookies because it was closed. This means it was already streamed
back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)
The error is raised when using these ways of creating users:
Creation using Factory Girl
Factory.create( :user )
Factory.build( :user ).save
Basic creation
User.create( { ... } )
User.new( { ... } ).save
What is funny is that they do work during some test, but not in others, and it does not seem random, although I cannot figure out the reason. Below is an excerpt from my code:
users_controller_spec.rb
require 'spec_helper'
def user
#user ||= Factory.create( :user )
end
def valid_attributes
Factory.attributes_for :user
end
describe UsersController do
describe 'GET index' do
it 'assigns all users as #users' do
users = [ user ] # The call to user() raises the error here
get :index
assigns[ :users ].should == users
end
end
describe 'GET show' do
it 'assigns the requested user as #user' do
get :show, id: user.id # The call to user() raises the error here
assigns[ :user ].should == user
end
end
However, the error is not raised in the following code block:
describe 'GET edit' do
it 'assigns the requested user as #user' do
get :edit, id: user.id # This raises no error
assigns[ :user ].should == user
end
end
Any other method below this does not raise the error, even though I am creating users in the exact same way.
Any suggestions to what I might be doing wrong would be greatly appreciated!
Someone posted a workaround here
https://github.com/binarylogic/authlogic/issues/262#issuecomment-1804988
This is due to the way rails 3 streams the response now. They posted a fix in edge for the same issue in flash but not in cookies yet. For now I have turned off my request specs. I am going to look at the problem this weekend if no one gets to it before then.
https://github.com/rails/rails/issues/1452
Just so we don't have to follow links, here's my modified version of the authlogic workaround:
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.maintain_sessions = false if Rails.env == "test"
end
end
Rather than deal with ensuring session management on every .save call, I just turn them off if I'm testing.

Resources