Groovy can't compile the code from a solution given on StackOverflow - grails

Answer 1 to this StackOverflow post provides some Groovy code, but it doesn't compile (for me, Groovy Console Version 2.1.3, or in my Grails 2.2.3 app).
Can you please assist in letting me know what I need to change to make this code work? The error I get is:
unexpected token: public at line 14, column: 52 (... which is the "public X509 Certificate[]")
For quick reference the code solution provided in Answer 1 is:
import javax.net.ssl.X509TrustManager
import javax.net.ssl.SSLContext
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManager
import java.security.SecureRandom
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry
def http = new HTTPBuilder( "https://your_unsecure_certificate_host" )
//=== SSL UNSECURE CERTIFICATE ===
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [ new X509TrustManager() {public X509Certificate[]
getAcceptedIssuers() {null }
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
} ] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
def httpsScheme = new Scheme("https", sf, 443)
http.client.connectionManager.schemeRegistry.register( httpsScheme )
//================================

You probably have a newline between the public X509Certificate[] and getAcceptedIssuers() {null} as a result of pasting the code in.
Try removing the newline (and formatting the code to something moderately readable while you're at it) and the error should disappear.

Related

New assignment to collection-type class field absent from flow program with Rascal, unlike to local variables

Consider the following Java code:
import java.util.LinkedList;
import java.util.List;
class Library {
List<String> loans = new LinkedList<>();
public List<String> searchUser(String name) {
List<String> usersFound = new LinkedList<>();
return loans;
}
}
and the following Rascal module:
module Mwe
import lang::java::flow::JavaToObjectFlow;
import lang::java::jdt::m3::AST;
import IO;
void m() {
ast = createAstFromEclipseFile(|project://test/src/test.java|, true);
fp = createOFG({ast});
print(fp);
}
The resulting flow program will be:
flowProgram({
attribute(|java+field:///Library/loans|),
method(|java+method:///Library/searchUser(java.lang.String)|,[|java+parameter:///Library/searchUser(java.lang.String)/scope(name)/scope(0)/name|]),
constructor(|java+constructor:///Library/Library()|,[])
},{
assign(|java+method:///Library/searchUser(java.lang.String)/return|,|id:///|,|java+field:///Library/loans|),
newAssign(|java+variable:///Library/searchUser(java.lang.String)/usersFound|,|java+class:///java/util/LinkedList|,|java+constructor:///java/util/LinkedList/LinkedList()|,[])
})
So, there is a new assignment of LinkedList to usersFound, but nothing comparable for loans. Why would that happen? Is that the intended behaviour?
Just checked the implementation, the field initializers are not included in the getStatements function (see lang::java::flow::JavaToObjectFlow on line 169). Similarly the static initializers of a class are ignored.
The best way forward would be to either report it as a bug, or fix it and turn it into a pull-request. (pull request is the quickest way to getting it fixed on unstable)
As a possible, yet work intensive workaround you rewrite the AST to put the field initializers inside all existing constructors (or add a constructor if there is none).

Trying to trigger JMX Mbean functions from command line

My application is running on Wildfly-8.0.1. Currently, I am able to trigger MBean methods through JConsole using service:jmx:http-remoting-jmx://localhost:9990.
I want to write some script to trigger those commands but I didn't find a supporting tool to accomplish that.
I tried below tools, but it seems like they are not supporting http-remoting-jmx protocol or may be I am not using in right way
1. JMXTerm
2. Cmdline_JMXClient
3. JManage
4. CJMX
Here is the error from JMXTerm
$>open service:jmx:http-remoting-jmx://localhost:9990
RuntimeIOException: Runtime IO exception: Unsupported protocol: http-remoting-j
mx
any help would greatly be appreciated.
Create custom jar file using below class.
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class JMXCli {
//private static List<String> operations;
private static final String SERVICE_URL = "service:jmx:http-remoting-jmx://";
public static void main(String[] args) throws Exception {
JMXServiceURL url = new JMXServiceURL(SERVICE_URL + args[0]);
JMXConnector connector = JMXConnectorFactory.connect(url);
MBeanServerConnection connection = connector.getMBeanServerConnection();
ObjectName objectName = new ObjectName("com.xyz.com:name=<<Your MBean class name>>");
System.out.println(connection.invoke(objectName, args[1], null, null));
}
}

JMockit Mocking java.net.URL causes test not run

I'm using the newest versions of junit and jmockit and Oracle JDK 7 in Eclipse. When I try to mock java.net.URL my test won't run.
I have in my code something like:
URL url = new URL("String representing the url.");
So I figured in my test I could mock this like so:
#Mocked private URL _url;
Since this works for pretty much everything else, I know URL is final but I thought that was okay with JMockit.
When I run a test class with the above mock in eclipse the result is a grey line(as opposed to green or red.) So I'm assuming some kind of initialization problem. The rest of the test or code doesn't seem to matter, no matter what I put that #Mocked line in, this happens.
A workaround would be great, an explanation of what is actually causing this would be even better. Any help is definitely appreciated! Thanks!
Quick example. This actually gives an exception, but I think it is basically doing the same thing I have seen:
package demo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Connecting {
public boolean connectionattempt() throws IOException {
URL url = new URL("http://nowhere/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection != null) {
return true;
}
else {
return false;
}
}
}
And this test:
package demo;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
public class TestConnecting {
#Mocked URL _url;
#Mocked HttpURLConnection _connection;
#Tested Connecting _sut;
#Test
public void testConnect() throws IOException {
new Expectations() { {
_url.openConnection(); result = _connection;
} };
assertEquals(true, _sut.connectionattempt());
}
}
and the stack trace:
java.lang.NoClassDefFoundError: org/eclipse/jdt/internal/junit/runner/TestReferenceFailure
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:91)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestListener.testFailure(JUnit4TestListener.java:69)
at org.junit.runner.notification.RunNotifier$4.notifyListener(RunNotifier.java:139)
at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:61)
at org.junit.runner.notification.RunNotifier.fireTestFailures(RunNotifier.java:134)
at org.junit.runner.notification.RunNotifier.fireTestFailure(RunNotifier.java:128)
at org.junit.internal.runners.model.EachTestNotifier.addFailure(EachTestNotifier.java:23)
at org.junit.runners.ParentRunner.run(ParentRunner.java:315)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
I executed the test on Eclipse Kepler SR2, IntelliJ IDEA 13.1, and Netbeans 8.0.1, using JMockit 1.13, JUnit 4.11, and Oracle JDK 1.7.0_67.
The test passes in every case, it's all green! So, I don't know what could possibly be the problem in your environment. Are you sure the "newest version" of JMockit (1.13 at this time) was the one actually used?

Code cannot find a line on a website

I've been trying to find a line and print it out on this website: http://www.easports.com/player-hub/360/Its+McDoom
Right now it prints out everything on the website, but I cannot find the line I am looking for. I am trying to print out "H2h Skill Points: 1053", but I cannot find anything like that in the console.
I only really want it to print that 1 line, not the whole thing, but I can't even find it.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class ElectronicArtsStatHub {
/**
* #param args
*/
public static void main (String[] args) throws Exception{
URL oracle = new URL("http://www.easports.com/player-hub/360/Its+McDoom");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
The first problem is that the information your trying to find isn't actually in the data you are currently outputting.
When you open the page in your browser you get the main page elements but then your browser then runs some Javascript code which presumably uses AJAX to get the stats and fill in the table.
The URLConnection receives the same data that your browser initially does and does not execute the Javascript so if you check your output that data your looking for isn't actually there at all.
Possible solutions include finding a different source for this data or executing the Javascript in Java possibly by using HTMLUnit
There may be some helpful infomation on this related question

Using new Groovy Grape capability results in "unable to resolve class" error

I've tried to use the new Groovy Grape capability in Groovy 1.6-beta-2 but I get an error message;
unable to resolve class com.jidesoft.swing.JideSplitButton
from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
I even tried running the grape command line tool to ensure the library is imported. Like this;
$ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss
which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?
There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first:
groovy.grape.Grape.initGrape()
Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so
import com.jidesoft.swing.JideSplitButton
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
new TestClassAnnotation().testMethod()
I finally got it working for Groovy Shell (1.6.5, JVM: 1.6.0_13). This should be documented better.
First at the command line...
grape install org.codehaus.groovy.modules.http-builder http-builder 0.5.0-RC2
Then in groovysh...
groovy:000> import groovy.grape.Grape
groovy:000> Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')
groovy:000> def http= new groovyx.net.http.HTTPBuilder('http://rovio')
===> groovyx.net.http.HTTPBuilder#91520
The #grab is better used in a file than the shell.
Ok. Seems like this a short working demo (running from the groovyConsole)
groovy.grape.Grape.initGrape()
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')
public class UsedToExposeAnnotationToComplier {}
com.jidesoft.swing.JideSplitButton.class.name
When run it produces
Result: "com.jidesoft.swing.JideSplitButton"
Very cool!!
The import statement must appear after the grabs.
Ps. At least one import statement must exists after the grabs
#Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')
import com.jidesoft.swing.JideSplitButton
public class TestClassAnnotation {
public static String testMethod () {
return JideSplitButton.class.name
}
}
Different example using latest RC-2 (note: Grab annotates createEmptyInts):
// create and use a primitive array
import org.apache.commons.collections.primitives.ArrayIntList
#Grab(group='commons-primitives', module='commons-primitives', version='1.0')
def createEmptyInts() { new ArrayIntList() }
def ints = createEmptyInts()
ints.add(0, 42)
assert ints.size() == 1
assert ints.get(0) == 42
Another example (note: Grab annotates getHtml):
// find the PDF links in the Java 1.5.0 documentation
#Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def getHtml() {
def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
parser.parse("http://java.sun.com/j2se/1.5.0/download-pdf.html")
}
html.body.'**'.a.#href.grep(~/.*\.pdf/).each{ println it }
Another example (note: Grab annotates getFruit):
// Google Collections example
import com.google.common.collect.HashBiMap
#Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')
def getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }
assert fruit.inverse().yellow == 'lemon'

Resources