com.netflix.hystrix.exception.HystrixRuntimeException: execute timed-out and no fallback available - java

I am writing an test class for Integration Testing using groovy file
My Groovy File :
#UseModules(value = [MiddleModule])
class MiddleServiceIT extends Specification{
#Inject
MiddleService middleService
#Rule
public WireMockRule Server = new WireMockRule(wireMockConfig().port(9090));
def 'validate config'() {
expect:
middleService != null
}
def 'validate get'() {
/* String urlPath = 'http://localhost:8889/middle/?acctID=80873000101&vodSource=ais&headendID=louis&activeOnly=true&limit=50&startDate=2014-10-09&inclNonSyncData=test' */
String urlPath = 'http://localhost:8889/middle/'
given:
Server.stubFor(get(urlPathEqualTo(urlPath)).willReturn(MiddleServiceStub.buildSuccess()))
when:
MiddleMessage response = middleService.get( '80873000101','ais', 'louis', 'true', '50', '2014-10-09', 'test')
then:
response != null
}
}
Here my requirement is when it hits that URL, it has to give the response which I mentioned in the stubFor call.
My Original Method :
#Override
public MiddleMessage get(String acctID, String vodSource, String headendID, String activeOnly, String limit, String startDate, String inclNonSyncData){
String url = rentalsMiddleBaseUrl + "/?acctID=" + acctID + "&vodSource=" + vodSource + "&headendID=" + headendID + "&activeOnly=" + activeOnly + "&limit=" + limit + "&startDate=" + startDate + "&inclNonSyncData=" + inclNonSyncData;
System.out.println("***** For Test URL "+url);
return (MiddleMessage) commandBuilder.build(url,MiddleMessage.class).execute();
}
My Stub Method in MiddleServiceStub Class:
public static ResponseDefinitionBuilder buildSuccess() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MiddleSet middleSet = new MiddleSet();
MiddleMessage middleMessage = new MiddleMessage();
middleMessage.setMiddleSet(middleSet);
String json = mapper.writeValueAsString(middleMessage);
ResponseDefinitionBuilder responseDefinitionBuilder = ResponseDefinitionBuilder.like(ResponseDefinition.created()).withBody(json);
return responseDefinitionBuilder;
}
When I run the above code using maven command "clean install" it is giving the following exception
validate get(com.config.MiddleServiceTest) Time elapsed: 1.918 sec <<< ERROR!
com.netflix.hystrix.exception.HystrixRuntimeException: execute timed-out and no fallback available.
at com.netflix.hystrix.HystrixCommand.getFallbackOrThrowException(HystrixCommand.java:1646)
at com.netflix.hystrix.HystrixCommand.access$1900(HystrixCommand.java:103)
at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.run(HystrixCommand.java:1023)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37)
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57)
at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$2.tick(HystrixCommand.java:1047)
at com.netflix.hystrix.HystrixCommand$1.performBlockingGetWithTimeout(HystrixCommand.java:627)
at com.netflix.hystrix.HystrixCommand$1.get(HystrixCommand.java:522)
at com.netflix.hystrix.HystrixCommand.execute(HystrixCommand.java:431)
at com.client.MiddleService.get(MiddleService.java:72)
at com.config.MiddleServiceTest.validate get(MiddleServiceTest.groovy:22)
Caused by: java.util.concurrent.TimeoutException

The parameter you pass to urlPathEqualTo(...) should be a relative URL, not absolute.
I don't know if this is what's causing the exception you've pasted, but WireMock will return a 404 given your current setup, which I suspect isn't what you want.

Related

Problem while authenticating URL in spock testing

I have a groovy file gitClone.groovy which has a function call.
def call(credentials, url, project, branch, path, refs, noTags=false,
timeout=20)
{
}
I am writing a test for validating the 'url'. I want to write a test case which will validate if the url is correct or not. My test file is as follows:
gitCloneSpec.groovy
import com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification;
import spock.lang.*
import java.net.URL;
public class gitCloneSpec extends JenkinsPipelineSpecification {
def gitClone = null
def check = 0
def setup() {
gitClone = loadPipelineScriptForTest("vars/gitClone.groovy")
gitClone.getBinding().setVariable( "url", "https://www.google.com/")
}
def "validate url"(){
when:
try {
URL u = new URL(url)
u.toURI()
check = 1
}
// If there was an Exception
// while creating URL object
catch (Exception e) {
check = 2;
}
then:
check == 1
}
}
Somehow url is not able to store the string "http://www.google.com" and it is throwing the exception where 'check' is getting updated with value '2'
How can I perform this test?

Mockito test for MultipartFile.transferto() in Service layer

public void saveFile(MultipartFile file , int id) throws IOException {
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyMMddHHmmss"));
String destination = goldenFileLocation + "/" + file.getOriginalFilename() + date;
file.transferTo(new File(destination));
}
I need to write a Mockito test for the above service layer code. I have the below code but not sure how to test if the file exists in the mentioned location.
#Test
public void testSaveFile() throws IOException {
MockMultipartFile firstFile = new MockMultipartFile("pdf", "response.pdf", "multipart/form-data", "data".getBytes());
saveFile(firstFile,1);
//check if file got stored in the mentioned location
}

APPLICATION FAILED TO START when I try to work with mongoDB and SpringBoot

I have implemented a spring boot application to retrieve file data from files and save it in separate collections. When I run the application it gives the following error. I couldn't resolve it. Can anyone help me to do this?
Error
Description:
Parameter 2 of constructor in com.bezkoder.spring.jwt.mongodb.SpringBootSecurityJwtMongodbApplication required a bean of type 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' that could not be found.
Action:
Consider defining a bean of type 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' in your configuration.
Disconnected from the target VM, address: '127.0.0.1:55297', transport: 'socket'
LogRecordController.java
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api/auth/log")
public class LogRecordController {
#Autowired
LogRecordRepository logRecordRepository;
#GetMapping("")
public ResponseEntity<?> getAllLogRecordsByLogFileId(#RequestParam("fileId") String fileId) {
try{
LogRecordCollection logRecordCollection = new LogRecordCollection();
logRecordCollection.setCollectionName(fileId);
// List<LogRecord> logRecords = logRecordRepository.findAll(PageRequest.of(1, 10, Sort.by(Sort.Direction.ASC, "no"))).getContent();
List<LogRecord> logRecords = logRecordRepository.findAll();
return ResponseEntity.ok().body(logRecords);
}catch (Exception e){
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
}
}
}
SpringBootSecurityJwtMongodbApplication.java
#SpringBootApplication
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/api/auth/logFile")
public class SpringBootSecurityJwtMongodbApplication {
public SpringBootSecurityJwtMongodbApplication(LogFileRepository logfileRepo, LogRecordRepository logrecordRepo, LogRecordCollection logrecordColl) {
this.logfileRepo = logfileRepo;
this.logrecordRepo = logrecordRepo;
this.logrecordColl = logrecordColl;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityJwtMongodbApplication.class, args);
}
#Bean
public ApplicationRunner runner(FTPConfiguration.GateFile gateFile) {
return args -> {
List<File> files = gateFile.mget(".");
for (File file : files) {
JSONArray arr = new JSONArray();
System.out.println("Result:" + file.getAbsolutePath());
run(file, arr);
}
};
}
void run(File file, JSONArray arr) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Pcap pcap = Pcap.openStream(file);
JSONObject obj = new JSONObject();
String fileName = file.getName();
pcap.loop(
packet -> {
String Time = null;
String Source = null;
String Destination = null;
String dataProtocol = null;
Long Length = null;
if (packet.hasProtocol(Protocol.TCP)) {
TCPPacket packet1 = (TCPPacket) packet.getPacket(Protocol.TCP);
Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
Source = packet1.getSourceIP();
Destination = packet1.getDestinationIP();
dataProtocol = packet1.getProtocol().toString();
Length = packet1.getTotalLength();
} else if (packet.hasProtocol(Protocol.UDP)) {
UDPPacket packet1 = (UDPPacket) packet.getPacket(Protocol.UDP);
Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
Source = packet1.getSourceIP();
Destination = packet1.getDestinationIP();
dataProtocol = packet1.getProtocol().toString();
Length = packet1.getTotalLength();
} else {
System.out.println("Not found protocol. | " + packet.getProtocol());
}
obj.put("Time", Time);
obj.put("Source", Source);
obj.put("Destination", Destination);
obj.put("Protocol", dataProtocol);
obj.put("Length", Length);
arr.add(obj);
return packet.getNextPacket() != null;
}
);
System.out.println(arr);
System.out.println(fileName);
Calendar calendar = Calendar.getInstance();
String now = String.valueOf(calendar.getTime());
LogFile data =logfileRepo.save(new LogFile("", fileName, now));
String collectionName = data.getFileName();
System.out.println(collectionName);
//Converting jsonData string into JSON object
//Creating an empty ArrayList of type Object
ArrayList<Object> listdata = new ArrayList<>();
//Checking whether the JSON array has some value or not
if (arr != null) {
//Iterating JSON array
for (int i=0;i<arr.size();i++){
//Adding each element of JSON array into ArrayList
listdata.add(arr.get(i));
}
}
logrecordColl.setCollectionName(collectionName);
listdata.addAll(logrecordRepo.findAll());
}
private final LogFileRepository logfileRepo;
private final LogRecordRepository logrecordRepo;
private final LogRecordCollection logrecordColl;
}
LogRecordRepository.java
import com.bezkoder.spring.jwt.mongodb.models.LogRecord;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface LogRecordRepository extends MongoRepository<LogRecord, String>{
}
LogRecordCollection.java
public class LogRecordCollection {
private static String collectionName = "undefined";
public static String getCollectionName(){
return collectionName;
}
public void setCollectionName(String collectionName){
this.collectionName = collectionName;
}
}
Parameter 2 of constructor in com.bezkoder.spring.jwt.mongodb.SpringBootSecurityJwtMongodbApplication required a bean of type 'com.bezkoder.spring.jwt.mongodb.models.LogRecordCollection' that could not be found.
In an nutshell, the exception like this is self-explanatory. It means that Spring could not find a bean to be injected into your class
In your case the class SpringBootSecurityJwtMongodbApplication has a constructor:
public SpringBootSecurityJwtMongodbApplication(LogFileRepository logfileRepo, LogRecordRepository logrecordRepo, LogRecordCollection logrecordColl) {
this.logfileRepo = logfileRepo;
this.logrecordRepo = logrecordRepo;
this.logrecordColl = logrecordColl;
}
Now, LogRecordCollection has to be a bean (annotated with #Component for example, or defined in via java configuration (#Configuration marked classes and method annotated with #Bean that creates this class). Otherwise spring won't "recognize" this class a bean.
So strictly speaking this is your issue.
Now, having said that - the code you've presented in the question looks extremely messy - you mix #SpringBootApplication which is an entry point to the application, the rest controller and what not. I really recommend you to separate all this to different files to improve the code clarity and avoid unexpected exceptions that can be tricky to fix.
add below annotations in SpringBootSecurityJwtMongodbApplication
#SpringBootApplication
#ComponentScan("com.bezkoder.spring.jwt.mongodb") //to scan packages mentioned
#EnableMongoRepositories("com.bezkoder.spring.jwt.mongodb") //to activate MongoDB repositories
public class SpringBootSecurityJwtMongodbApplication { ... }

Groovy sandbox and Java: execute Groovy script

Task: execute groovy script with Groovy sandbox:
http://groovy.codehaus.org/api/overview-summary.html
http://groovy-sandbox.kohsuke.org/
Groovy Script to execute:
query.reverse(); // QUERY is a some string that should be reversed
File "GroovyScriptSandbox.groovy" should get two parameters(script and values for this script):
package test.my.groovy.sandbox
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.codehaus.groovy.control.customizers.SecureASTCustomizer
import org.springframework.stereotype.Component
#Component
class GroovyScriptSandbox {
def config
def shell
public String runScript(final String script, final String query) {
final ImportCustomizer imports = new ImportCustomizer()
.addStarImports('groovyx.net.http')
.addStaticStars('groovyx.net.http.ContentType', 'groovyx.net.http.Method')
config = new CompilerConfiguration()
config.addCompilationCustomizers(imports)
def newScript = "{ query -> " + script + "}"
shell = new GroovyShell(config)
def clos = shell.evaluate(newScript)
return clos.call(query)
}
}
Java method that executes "GroovyScriptSandbox.groovy":
#Resource
private GroovyScriptSandbox groovyScriptSandbox;
#RequestMapping(value = "/run", method = RequestMethod.POST)
#ResponseBody
public String runScript(#RequestParam("script") final String script,
#RequestParam("query") final String query) {
return groovyScriptSandbox.runScript(script, query);
}
In that case all works fine:
Java controller getting script parameter equal "query.reverse()" and query parameter equals "0123"
Groovy file executes script "query.reverse()" in sandbox where query equals "0123"
Result equals "3210"
Question:
I'm trying to replace "GroovyScriptSandbox.groovy" file with "GroovyScriptSandbox.java" and I don't know how to write the same groovy code in Java.
Finally found solution:
public String scriptRunner(final String script, final String query) {
final ImportCustomizer imports = new ImportCustomizer();
imports.addStaticStars("java.lang.Math");
imports.addStarImports("groovyx.net.http");
imports.addStaticStars("groovyx.net.http.ContentType", "groovyx.net.http.Method");
final SecureASTCustomizer secure = new SecureASTCustomizer();
secure.setClosuresAllowed(true);
final CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(imports, secure);
final Binding intBinding = new Binding(); // alow parameters in the script
intBinding.setVariable("query", query);
final GroovyShell shell = new GroovyShell(intBinding, config); // create shall
// code execution
final Object clos = shell.evaluate(script);
if (clos == null) {
return "No result avalible!";
}
return clos.toString();
}

Read test data from Mercury Quality center 9 via java

We use Mercury Quality Center 9 for storage tests and test results.
I need to read test data from Test Plan and to write test result into Test Lab via java.
I tried to find about this in google but I have not found anything.
UPDATE:
I tried to use qctools4j for working with MQC 9 with the following code:
public void connect() {
try{
IQcConnection conn = QcConnectionFactory.createConnection("http://qc/qcbin");
conn.connect("login", "password", "DEFAULT","project");
TestClient tc = conn.getTestClient();
System.out.println("Connection success!!!");
}
catch (QcException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
I got the following exception message:
*org.qctools4j.exception.QcException: Can't co-create object
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)
at org.qctools4j.clients.QcConnectionImpl.<init>(Unknown Source)
at org.qctools4j.QcConnectionFactory.createConnection(Unknown Source)
at automation_framework1.automation_framework1.QCWorker.connect1(QCWorker.java:38)
at automation_framework1.automation_framework1.Main.main(Main.java:12)
Caused by: com.jacob.com.ComFailException: Can't co-create object
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)*
What am I doing wrong?
I took part in developping QC 9 and I am not sure there is Java API. However, there is a COM interface or OTA API. You can use some library that helps to call COM API from Java.
For example:
Jacob it is open source and here are some examples.
Nevaobject - it is commercial but more stable.
Good luck!
EDIT:
just saw qctools4j (it is based on Jacob) - never tried it.
I found how to solve the problem. I used groovy scriptom with the following code (may be it will help somebody):
def tdc;
public QualityCenterController(){
static{
System.load("C:\\WINDOWS\\system32\\OTAClient.dll");
System.load("D:\\Work\\automation_framework\\libs\\lib\\jacob-1.16-M2-x86.dll");
}
public void connect(){
tdc = new ActiveXObject ("TDApiOle80.TDConnection");
tdc.InitConnectionEx("http://qc/qcbin");
tdc.Login("username", "password");
tdc.Connect("DEFAULT","PROJECT");
System.out.println("login is success");
}
//ReqFactory Object
public void getRequirements(){
def requironmetns = tdc.ReqFactory();
def listReq = requironmetns.NewList("");
for (def iterReq : listReq) {
getRequirement(iterReq);
}
println listReq.count();
}
//Req Object
public void getRequirement(def itemReq){
println 'ID: '+itemReq.ID();
println 'Name:' + itemReq.Name();
println 'Path:' + itemReq.Path();
println 'Reviewed:' + itemReq.Reviewed();
println 'Author:' + itemReq.Author();
println 'Priority: ' + itemReq.Priority();
println 'Comment: '+removeHtmlTag(itemReq.Comment());
println 'Type: ' + itemReq.Type();
}
public Test getTestsFromTestLab(String path){
Test resultTest = new Test();
def labFolder = tdc.TestSetTreeManager.NodeByPath(path);
def tsList = labFolder.FindTestInstances("");
for (def iterable_element : tsList){
Test test = getTestData(iterable_element);
def steps = iterable_element.Test().DesignStepFactory();
TestStep testStep = getTest(steps);
}
return resultTest;
}
public TestStep getTest(def testData){
TestStep testStep = new TestStep();
def listSteps = testData.NewList("");
for(def item1 : listSteps){
testStep = getTestStepData(item1);
showTestStep(testStep);
}
return testStep;
}
private TestStep getTestStepData(def stepData){
TestStep testStep = new TestStep();
testStep.setId(stepData.ID());
testStep.setName(stepData.StepName());
testStep.setDescription(removeHtmlTag(stepData.StepDescription()));
testStep.setExpected(removeHtmlTag(stepData.StepExpectedResult()));
testStep.setStepOrder(stepData.Order());
return testStep;
}
public Test getTestData(def testData){
Test test = new Test();
test.setId(Integer.parseInt(testData.Id()));
test.setName(testData.Name());
test.setExecStatus(testData.Status());
showTest(test);
return test;
}
private String removeHtmlTag(String html){
String result = "";
result = Jsoup.parse(html).text();
return result;
}
public void showTestStep(TestStep testStep){
println testStep.getId();
println testStep.getName();
println testStep.getDescription();
println testStep.getExpected();
println testStep.getStepOrder();
}
public void showTest(Test test){
println test.getId();
println test.getName();
println test.getExecStatus();
}

Categories

Resources