Groovy syntax error - groovy

I have an error ("unexpected token"). I don't know Groovy very well , but how to fix it? Part of my code:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
#Override
int compare(Agent o1, Agent o2) {
if(o1.issueCount == o2.issueCount){
if(o2.lastAssignedTime == o1.lastAssignedTime){
return o1.user.name.compareTo(o2.user.name)
}
else{
return o1.lastAssignedTime.compareTo(o2.lastAssignedTime)
}
}
else{
return o1.issueCount - o2.issueCount
}
}
})
I have an error in &lt case

Your problem is caused by HTML entities that encoded < and > characters:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
It should be:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
The code you have pasted wont compile neither in Groovy nor in Java.

Related

PowerMockito Error

Need a quick help. I am trying to write a test class and getting below error
"can not resolve the method .thenreturn(org.apache.kafka.clients.producer)
#Test
public void testPublishData_Success() throws java.lang.Exception {
when(GetPropValues.getPropValue(PublisherConstants.ATMID)).thenReturn("ATM");
when(GetPropValues.getPropValue(PublisherConstants.DATA_SOURCE)).thenReturn("PCE");
ReadAndWriteFiles mockFiles = Mockito.mock(ReadAndWriteFiles.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withNoArguments().thenReturn(mockFiles);
Mockito.when(mockFiles.getAllFiles()).thenReturn("someValue");
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
producer.publishData(null, "Test", "Data1");
}
Powermockito is fine in returning ReadAndWriteFiles.class object but it is throwing an error for KafkaProducer.class. on line
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
Is there any other way to for this work around? Any suggestion will be appreciated.
Note: KafkaProducer.class is in not a custom class but its inside from apache spark kafka libraries
Main code is as per below
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);
InputData inputMessage;
try {
inputMessage = populateData(timeStamp, dataCategory, data, atmId, topic);
ReadAndWriteFiles readerWriter = new ReadAndWriteFiles();
File[] directory = readerWriter.getAllFiles();
if (directory != null && directory.length > 0) {
if (connectionSet && !publishingData) {
sendDataFromFiles(producer, directory);
publishingData = false;
}
} else {
producer.send(keyedMsg, new KafkaResponseHandler(inputMessage));
}
} catch (IOException e) {
}
I think the error is
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(mockProducer)
I think the returned value should be a mock for ReadAndWriteFiles class not a KafkaProducer
ReadAndWriteFiles readMock = Mockito.mock(ReadAndWriteFiles.class)
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(readMock)
Mockito.when(readMock.getAllFiles()).thenReturn(anArrayOfFiles);
The signature of the thenReturn method is as follow
OngoingStubbing<T> [More ...] thenReturn(T value);
So you are using to return a ReadAndWriteFiles you shouls return an object of the same class

OrientDB ClassCastException

I get the following exception when trying to access a relationship document:
java.lang.ClassCastException: com.orientechnologies.orient.core.id.ORecordId cannot be cast to com.orientechnologies.orient.core.record.impl.ODocument
via:
Collection<ODocument> field = myDoc.field("MY_FIELD_NAME");
if(field != null) {
return field;
} else {
return Collections.emptySet();
}
The strange thing is that is happes not always, most of the time it works like expected.
Depending by what the field contains, you could use the interface OIdentifiable instead of ODocument.
Try using:
Collection<OIdentifiable> field = myDoc.field("MY_FIELD_NAME");
if(field != null) {
return field;
} else {
return Collections.emptySet();
}

Creation of custom comparator for map in groovy

I have class in groovy
class WhsDBFile {
String name
String path
String svnUrl
String lastRevision
String lastMessage
String lastAuthor
}
and map object
def installFiles = [:]
that filled in loop by
WhsDBFile dbFile = new WhsDBFile()
installFiles[svnDiffStatus.getPath()] = dbFile
now i try to sort this with custom Comparator
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
#Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return 1
} else if (FilenameUtils.getBaseName(o1.name) > FilenameUtils.getBaseName(o2.name)) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
but get this error java.lang.String cannot be cast to WhsDBFile
Any idea how to fix this? I need to use custom comparator, cause it will be much more complex in the future.
p.s. full source of sample gradle task (description of WhsDBFile class is above):
project.task('sample') << {
def installFiles = [:]
WhsDBFile dbFile = new WhsDBFile()
installFiles['sample_path'] = dbFile
Comparator<WhsDBFile> whsDBFileComparator = new Comparator<WhsDBFile>() {
#Override
int compare(WhsDBFile o1, WhsDBFile o2) {
if (o1.name > o2.name) {
return 1
} else if (o1.name > o2.name) {
return -1
}
return 0
}
}
installFiles.sort(whsDBFileComparator);
}
You can try to sort the entrySet() :
def sortedEntries = installFiles.entrySet().sort { entry1, entry2 ->
entry1.value <=> entry2.value
}
you will have a collection of Map.Entry with this invocation. In order to have a map, you can then collectEntries() the result :
def sortedMap = installFiles.entrySet().sort { entry1, entry2 ->
...
}.collectEntries()
sort can also take a closure as parameter which coerces to a Comparator's compare() method as below. Usage of toUpper() method just mimics the implementation of FilenameUtils.getBaseName().
installFiles.sort { a, b ->
toUpper(a.value.name) <=> toUpper(b.value.name)
}
// Replicating implementation of FilenameUtils.getBaseName()
// This can be customized according to requirement
String toUpper(String a) {
a.toUpperCase()
}

Cannot convert lambda expression to type 'int' because it is not a delegate type

In this c# code I need to convert the userName value from string to int type.
Is anyone know please help me. I have got error as a compilation error "Cannot convert lambda expression to type 'int' because it is not a delegate type" like this.
ShoppingCartPartRecord cartRecord = null;
try {
cartRecord = _shoppingCartRepository.Get(r => r.Username == userName);
}
catch (InvalidOperationException ex) {
if (ex.Message == "Sequence contains more than one element") {
var badCarts = _shoppingCartRepository.Table.Where(x => x.Username == userName);
foreach (var shoppingCartPartRecord in badCarts) {
_shoppingCartRepository.Delete(shoppingCartPartRecord);
}
}
}
Thank you in advance.
Without the source to your repository we can only guess at what the methods do.
From the errors you are describing the get function expects either an index into an array or an integer primary key and so is the wrong function
You should be able to change the code as follows to achieve the desired effect
ShoppingCartPartRecord cartRecord = null;
try {
cartRecord = _shoppingCartRepository.Table.Single(r => r.Username == userName);
}
catch (InvalidOperationException ex) {
if (ex.Message == "Sequence contains more than one element") {
var badCarts = _shoppingCartRepository.Table.Where(x => x.Username == userName);
foreach (var shoppingCartPartRecord in badCarts) {
_shoppingCartRepository.Delete(shoppingCartPartRecord);
}
}
}

groovy multithreading

I'm newbie to groovy/grails.
How to implement thread for this code . Had 2500 urls and this was taking hours of time for checking each url.
so i decided to implement multi-thread for this :
Here is my sample code :
def urls = [
"http://www.wordpress.com",
"http://67.192.103.225/QRA.Public/" ,
"http://www.subaru.com",
"http://baldwinfilter.com/products/start.html"
]
def up = urls.collect { ur ->
try {
def url = new URL(ur)
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
} catch (Exception e) {
return false
}
}
For this code i need to implement multi-threading .
Could any one please suggest me the code.
thanks in advance,
sri.
I would take a look at the Groovy Parallel Systems library. In particular I think that the Parallel collections section would be useful.
Looking at the docs, I believe that collectParallel is a direct drop-in replacement for collect (bearing in mind the obvious caveats about side-effects). The following works fine for me:
def urls = [
"http://www.wordpress.com",
"http://www.subaru.com",
"http://baldwinfilter.com/products/start.html"
]
Parallelizer.doParallel {
def up = urls.collectParallel { ur ->
try {
def url = new URL(ur)
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
} catch (Exception e) {
return false
}
}
println up
}
See the Groovy docs for an example how to use an ExecutorService to do what you want.
You can use this to check the URL in a separate thread.
class URLReader implements Runnable
{
def valid
def url
URLReader( url ) {
this.url = url
}
void run() {
try {
def connection = url.toURL().openConnection()
valid = ( connection.responseCode == 200 ) as Boolean
} catch ( Exception e ) {
println e.message
valid = Boolean.FALSE
}
}
}
def reader = new URLReader( "http://www.google.com" )
new Thread( reader ).start()
while ( reader.valid == null )
{
Thread.sleep( 500 )
}
println "valid: ${reader.valid}"
Notes: The valid attribute will be either null, Boolean.TRUE or Boolean.FALSE. You'll need to wait for a while to give all the threads a chance to open the connection. Depending on the number of URLs you're checking you will eventually hit a limit of the number of threads / connections you can realistically handle, so should check URLs in batches of the appropriate size.
I think this way is very simple to achieve.
import java.util.concurrent.*
//Thread number
THREADS = 100
pool = Executors.newFixedThreadPool(THREADS)
defer = { c -> pool.submit(c as Callable) }
def urls = [
"http://www.wordpress.com",
"http://www.subaru.com",
]
def getUrl = { url ->
def connection = url.openConnection()
if (connection.responseCode == 200) {
return true
} else {
return false
}
}
def up = urls.collect { ur ->
try {
def url = new URL(ur)
defer{ getUrl(url) }.get()
} catch (Exception e) {
return false
}
}
println up
pool.shutdown()
This is how I implemented:
class ValidateLinks extends Thread{
def valid
def url
ValidateLinks( url ) {
this.url = url
}
void run() {
try {
def connection = url.toURL().openConnection()
connection.setConnectTimeout(5000)
valid = ( connection.responseCode == 200 ) as Boolean
} catch ( Exception e ) {
println url + "-" + e.message
valid = Boolean.FALSE
}
}
}
def threads = [];
urls.each { ur ->
def reader = new ValidateLinks(ur.site_url)
reader.start()
threads.add(reader);
}
while (threads.size() > 0) {
for(int i =0; i < threads.size();i++) {
def tr = threads.get(i);
if (!tr.isAlive()) {
println "URL : " + tr.url + "Valid " + tr.valid
threads.remove(i);
i--;
}
}
}

Resources