Pi4J v2 SPI w/ GPIO Pin - raspberry-pi

I'm trying to use Pi4J to talk to an SPI device where the CS pin is a GPIO pin (GPIO 5) and not one of the mapped CS pins. I don't see how to configure it this way in any of the examples or javadocs. I think it would be somewhere on my SpiConfig line.
// Initialize Pi4J with an auto context
// An auto context includes AUTO-DETECT BINDINGS enabled
// which will load all detected Pi4J extension libraries
// (Platforms and Providers) in the class path
var pi4j = Pi4J.newAutoContext();
// create SPI config
SpiConfig config = Spi.newConfigBuilder(pi4j).id("thermocouple-1")
.name("Thermocouple 1").bus(SpiBus.BUS_1)
.chipSelect(SpiChipSelect.CS_0).build();
// get a SPI I/O provider from the Pi4J context
SpiProvider spiProvider = pi4j.provider("pigpio-spi");
// use try-with-resources to auto-close SPI when complete
try (Spi spi = spiProvider.create(config)) {
byte data[] = new byte[]{0, 0, 0, 0};
It looks like this is possible with v1 of the library, but it's not the same in v2.

I ended up posting on the pi4j project on GitHub and through those conversations worked out what I needed. Here is a cross post from there.
Well looking at the DAC8552 example was the key. Here is a working
version that asks the device for it's ID (register 0xD0) and gives the
correct answer for BME280 (0x60). Thanks for the assist. Here is the
working code (needs to be cleaned up, but it's a basic start).
package com.pi4j.example.spi;
import com.pi4j.Pi4J;
import com.pi4j.context.Context;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import com.pi4j.io.spi.Spi;
import com.pi4j.io.spi.SpiBus;
import com.pi4j.io.spi.SpiChipSelect;
import com.pi4j.io.spi.SpiMode;
import com.pi4j.util.Console;
import com.pi4j.util.StringUtil;
public class BmeTest {
private static final SpiBus spiBus = SpiBus.BUS_0;
public static void main(String[] args) throws Exception {
final var console = new Console();
// print program title/header
console.title("<-- The Pi4J Project -->",
"Basic SPI Communications Example");
Context pi4j = Pi4J.newAutoContext();
var spiConfig = Spi.newConfigBuilder(pi4j)
.id("SPI" + spiBus + "_BME280")
.name("BME280")
.bus(spiBus)
.chipSelect(SpiChipSelect.CS_0) // not used
.mode(SpiMode.MODE_0)
.provider("pigpio-spi")
.build();
// required all configs
var outputConfig = DigitalOutput.newConfigBuilder(pi4j)
.id("CS_GPIO5")
.name("CS GPIO5")
.address(5)
.shutdown(DigitalState.HIGH)
.initial(DigitalState.HIGH)
.provider("pigpio-digital-output");
DigitalOutput csGpio = null;
try {
csGpio = pi4j.create(outputConfig);
} catch (Exception e) {
e.printStackTrace();
console.println("create DigOut DRDY failed");
System.exit(202);
}
// use try-with-resources to auto-close SPI when complete
try (var spi = pi4j.create(spiConfig)) {
byte data[] = new byte[] { (byte) (0x80 | 0xD0), (byte) 0x00 };
csGpio.high();
csGpio.low();
spi.transfer(data, data);
csGpio.high();
// take a breath to allow time for the SPI
// data to get updated in the SPI device
Thread.sleep(100);
// read data back from the SPI channel
console.println("--------------------------------------");
console.println("SPI [READ] :");
console.println(" [BYTES] 0x" + StringUtil.toHexString(data));
console.println(" [STRING] " + new String(data));
console.println("--------------------------------------");
}
// shutdown Pi4J
console.println("ATTEMPTING TO SHUTDOWN/TERMINATE THIS PROGRAM");
pi4j.shutdown();
}
}
With the following output:
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.util.Console - <-- The Pi4J Project -->
[main] INFO com.pi4j.util.Console - Basic SPI Communications Example
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console - ************************************************************
[main] INFO com.pi4j.util.Console -
[main] INFO com.pi4j.Pi4J - New auto context
[main] INFO com.pi4j.Pi4J - New context builder
[main] INFO com.pi4j.platform.impl.DefaultRuntimePlatforms - adding platform to managed platform map [id=raspberrypi; name=RaspberryPi Platform; priority=5; class=com.pi4j.plugin.raspberrypi.platform.RaspberryPiPlatform]
[main] INFO com.pi4j.util.Console - --------------------------------------
[main] INFO com.pi4j.util.Console - SPI [READ] :
[main] INFO com.pi4j.util.Console - [BYTES] 0xFF 60
[main] INFO com.pi4j.util.Console - [STRING] �`
[main] INFO com.pi4j.util.Console - --------------------------------------
[main] INFO com.pi4j.util.Console - ATTEMPTING TO SHUTDOWN/TERMINATE THIS PROGRAM

Related

How to load a drools rule externally

I have a drl file and a .class file in a folder. drl contains rule which is built on class attributes. Now through a java program i want to invoke this rule on some input. I am clueless here . please look at code below
class file
import java.io.Serializable;
public class Txn754909164
implements Serializable
{
String sequenceNo;
String accountNumber;
String customerNumber;
// setter and getters
}
drl file
import Txn754909164;
import java.util.*;
dialect "mvel"
rule "rule6"
when
txn:Txn754909164(sequence == 10)
then
System.out.println( "invoking rule ***********************" );
end
client code
public KieContainer kieContainer(String packageName) {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newUrlResource("drl resource url..."));
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem,MyInputClass.getClassLoader());
KieModule kieModule = null;
try {
kieBuilder.buildAll();
kieModule = kieBuilder.getKieModule();
} catch (Exception e) {
e.printStackTrace();
}
return kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId(),cls.getClassLoader());
}
and finally
StatelessKieSession kieSession = container.getKieBase().newStatelessKieSession();
kieSession.execute(obj);
logs
11:47:34.795 [http-nio-8282-exec-4] INFO o.d.c.k.b.impl.KieRepositoryImpl - KieModule was added: MemoryKieModule[releaseId=org.default:artifact:1.0.0-SNAPSHOT]
11:47:34.803 [http-nio-8282-exec-4] TRACE org.drools.core.phreak.AddRemoveRule - Adding Rule rule6
11:47:45.994 [AsyncResolver-bootstrap-executor-0] INFO c.n.d.s.r.aws.ConfigClusterResolver - Resolving eureka endpoints via configuration
11:47:49.899 [http-nio-8282-exec-4] TRACE o.drools.core.reteoo.EntryPointNode - Insert [fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664]
11:47:52.953 [http-nio-8282-exec-4] INFO o.k.a.e.r.DebugRuleRuntimeEventListener - ==>[ObjectInsertedEventImpl: getFactHandle()=[fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664], getObject()=Txn754909164#69298664, getKnowledgeRuntime()=KieSession[0], getPropagationContext()=PhreakPropagationContext [entryPoint=EntryPoint::DEFAULT, factHandle=[fact 0:1:1764329060:1764329060:1:DEFAULT:NON_TRAIT:Txn754909164:Txn754909164#69298664], leftTuple=null, originOffset=-1, propagationNumber=2, rule=null, type=INSERTION]]
11:48:41.571 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was INACTIVE is now FIRING_ALL_RULES
11:48:41.572 [http-nio-8282-exec-4] TRACE org.drools.core.common.DefaultAgenda - Starting Fire All Rules
11:48:41.573 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was FIRING_ALL_RULES is now HALTING
11:48:41.573 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was HALTING is now INACTIVE
11:48:41.574 [http-nio-8282-exec-4] TRACE org.drools.core.common.DefaultAgenda - Ending Fire All Rules
11:48:41.575 [http-nio-8282-exec-4] DEBUG org.drools.core.common.DefaultAgenda - State was INACTIVE is now DISPOSED
It should print statement in then clause of drl rule
above mentioned question and explanation is answer in itself. Found it working perfectly fine from next day. I guess it was just a workspace issue.

java.net.SocketException: Connection reset since TLSv1.2 protocol

I'm no more able to connect to api.softlayer.com
I'm calling the rest API from a WebSphere application portal 8.5 (java7) using Apache (HTTP-client-4.5.3.jar)
The coding is
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
The error is
17:44:00.997 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection request: [route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
17:44:01.044 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection leased: [id: 0][route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20]
17:44:01.044 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Opening connection {s}->https://api.softlayer.com:443
17:44:01.060 [main] DEBUG o.a.h.i.c.DefaultHttpClientConnectionOperator - Connecting to api.softlayer.com/66.228.119.120:443
17:44:01.060 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Connecting socket to api.softlayer.com/66.228.119.120:443 with timeout 0
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled protocols: [TLSv1]
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Enabled cipher suites:[TLS_EMPTY_RENEGOTIATION_INFO_SCSV, SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_RSA_WITH_AES_128_CBC_SHA256, SSL_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ECDH_RSA_WITH_AES_128_CBC_SHA256, SSL_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_AES_128_CBC_SHA, SSL_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, SSL_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ECDH_RSA_WITH_RC4_128_SHA, SSL_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_RC4_128_MD5]
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory - Starting handshake
17:44:01.747 [main] DEBUG o.a.h.i.c.DefaultManagedHttpClientConnection - http-outgoing-0: Shutdown connection
17:44:01.747 [main] DEBUG o.a.h.impl.execchain.MainClientExec - Connection discarded
17:44:01.747 [main] DEBUG o.a.h.i.c.PoolingHttpClientConnectionManager - Connection released: [id: 0][route: {s}->https://api.softlayer.com:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20]
17:44:01.747 [main] INFO o.a.http.impl.execchain.RetryExec - I/O exception (java.net.SocketException) caught when processing request to {s}->https://api.softlayer.com:443: Connection reset
17:44:01.747 [main] DEBUG o.a.http.impl.execchain.RetryExec - Connection reset
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:207) ~[na:1.7.0]
at java.net.SocketInputStream.read(SocketInputStream.java:133) ~[na:1.7.0]
at com.ibm.jsse2.a.a(a.java:110) ~[na:7.0 build_20131216]
at com.ibm.jsse2.a.a(a.java:141) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.a(qc.java:691) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.h(qc.java:266) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.a(qc.java:770) ~[na:7.0 build_20131216]
at com.ibm.jsse2.qc.startHandshake(qc.java:476) ~[na:7.0 build_20131216]
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396) ~[httpclient-4.5.3.jar:4.5.3]
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:355) ~[httpclient-4.5.3.jar:4.5.3]
The solution is to enable the enable TLSv1.2
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
public class HttpClientFactory {
private static CloseableHttpClient client;
public static HttpClient getHttpsClient() throws Exception {
if (client != null) {
return client;
}
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2"}, null, new NoopHostnameVerifier());
client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return client;
}
}
Softlayer's servers only accept TLSv1.2 connections you must make sure that your code is only performing connections with that protocol which it seems your code is not doing
17:44:01.606 [main] DEBUG o.a.h.c.s.SSLConnectionSocketFactory -
Enabled protocols: [TLSv1]

Swagger + Jersey + Grizzly

I have been trying to generate REST API doc using Swagger.
Followed the link but couldn't make it work. Got below error's
12:54:39.859 [main] INFO org.reflections.Reflections - Reflections took 63 ms to scan 1 urls, producing 73 keys and 122 values
12:54:39.906 [main] DEBUG i.s.jaxrs.ext.SwaggerExtensions - adding extension io.swagger.jersey.SwaggerJersey2Jaxrs#18be6e8
12:54:39.906 [main] DEBUG io.swagger.jaxrs.Reader - picking up response class from method public rest.beans.UserBean rest.frontend.UserResource.opAllocateUser(rest.beans.UserBean,javax.ws.rs.core.Request)
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty class rest.beans.UserBean
12:54:39.921 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class rest.beans.UserBean]
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - resolve [simple type, class rest.beans.UserBean]
12:54:39.921 [main] DEBUG i.s.c.ModelConverterContextImpl - trying extension io.swagger.jackson.ModelResolver#5ecce3
12:54:39.921 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class rest.beans.UserBean], rest.beans.UserBean
12:54:39.937 [main] DEBUG i.s.c.ModelConverterContextImpl - defineModel UserBean io.swagger.models.ModelImpl#c2b00fee
12:54:39.937 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.937 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.converter.ModelConverters - ModelConverters readAll from class rest.beans.UserBean
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolve class rest.beans.UserBean
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - trying extension io.swagger.jackson.ModelResolver#5ecce3
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - defineModel UserBean io.swagger.models.ModelImpl#c2b00fee
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG i.s.c.ModelConverterContextImpl - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - Can't check class [simple type, class java.lang.String], java.lang.String
12:54:39.952 [main] DEBUG io.swagger.jackson.ModelResolver - resolveProperty [simple type, class java.lang.String]
12:54:39.952 [main] DEBUG io.swagger.jaxrs.Reader - getParameters for [simple type, class rest.beans.UserBean]
12:54:39.952 [main] DEBUG io.swagger.jaxrs.Reader - trying extension io.swagger.jersey.SwaggerJersey2Jaxrs#18be6e8
Next searched and found link closest to my issue. Again followed it but still getting the above error. I can't see swagger.json getting generated.
Versions info
Jersey : 2.22.1
Jackson : 2.6.3
Swagger : 1.5.6
Grizzly : 2.3.23
Am I missing some configuration which is needed to make it work? Or Do I need more libraries?
Thanks
Statement : Generate Swagger UI for the listing of all the REST APIs through Grizzly and Jersey Application.
1. Add following dependency in pom.xml –
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.9</version>
</dependency>
2. Bundle Swagger UI and docs folder through you main application class using the below code –
package com.main;
import java.io.IOException;
import java.net.URI;
import org.glassfish.grizzly.http.server.CLStaticHttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.ServerConfiguration;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.swagger.jaxrs.config.BeanConfig;
public class MainApp {
// Base URI the Grizzly HTTP server will listen on
public static final URI BASE_URI = URI.create(“http://0.0.0.0:8080”);
public static HttpServer getLookupServer() {
String resources = “com.main”;
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion(“1.0.1”);
beanConfig.setSchemes(new String[] { “http” });
beanConfig.setBasePath(“”);
beanConfig.setResourcePackage(resources);
beanConfig.setScan(true);
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.packages(resources);
resourceConfig.register(io.swagger.jaxrs.listing.ApiListingResource.class);
resourceConfig.register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
resourceConfig.register(JacksonFeature.class);
resourceConfig.register(JacksonJsonProvider.class);
return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig);
}
public static void main(String[] args) throws IOException {
final HttpServer server = getLookupServer();
server.start();
ClassLoader loader = MainApp.class.getClassLoader();
CLStaticHttpHandler docsHandler = new CLStaticHttpHandler(loader, “swagger-ui/”);
docsHandler.setFileCacheEnabled(false);
ServerConfiguration cfg = server.getServerConfiguration();
cfg.addHttpHandler(docsHandler, “/docs/”);
}
}
3. Take the latest code of swagger-ui. Copy all the content of the dist folder and create a folder named swagger-ui inside src/main/resources and paste all the copied contents. Now change the url in index.file which is inside the copied folder like below –
url: http://0.0.0.0:8080/swagger.json
4. Lastly, annotate your controller with #Api and #ApiOperation.
Hope it works. Now to run your Grizzly Jersey Application, go to browser and type localhost:8080/docs/. You will see Swagger UI having all the details of your REST APIs.
Happy coding and sharing as well. 🙂 You can find the [git](https://guptakumartanuj.wordpress.com/2017/07/24/generate-swagger-ui-through-grizzly-and-jersey-application/) repo for the above implementation.

FactType.getFields return no fields drools KIE

I have created a fact type( CustomerFact ) with two fact fields(age and bonus) . A sample rule is also created using workbench. Now, I want to inject some test values and check whether the rules are getting fired. I used Eclipse IDE.
I am able to retrieve package name and the rule created in workbench in my java code. However, I am enable to get any fact fields. GetFields always returns an empty list whereas it should have returned 2 fields. Is there any alternative to this? I just want to set the field of the fact type and see whether the rules are getting fired. Any help is highly appreciated.
package org.demo.cityproject;
/**
* This class was automatically generated by the data modeler tool.
*/
public class CustomerFact implements java.io.Serializable
{
static final long serialVersionUID = 1L;
#org.kie.api.definition.type.Key
private int age;
#org.kie.api.definition.type.Key
private int bonus;
public CustomerFact()
{
}
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
this.age = age;
}
public int getBonus()
{
return this.bonus;
}
public void setBonus(int bonus)
{
this.bonus = bonus;
}
public CustomerFact(int age, int bonus)
{
this.age = age;
this.bonus = bonus;
}
#Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
org.demo.cityproject.CustomerFact that = (org.demo.cityproject.CustomerFact) o;
if (age != that.age)
return false;
if (bonus != that.bonus)
return false;
return true;
}
#Override
public int hashCode()
{
int result = 17;
result = 31 * result + age;
result = 31 * result + bonus;
return result;
}
}
Test Code
public static void main(String[] args)
{
String url = "http://localhost:8080/kie-drools-wb-distribution-wars-6.2.0.Final-jboss-as7/maven2/Project1/org/demo/CityProject/1.0/CityProject-1.0.jar";
ReleaseIdImpl releaseId = new ReleaseIdImpl("org.demo", "CityProject", "LATEST");
KieServices kieServices = KieServices.Factory.get();
kieServices.getResources().newUrlResource(url);
KieContainer kieContainer = kieServices.newKieContainer(releaseId);
KieScanner kieScanner = kieServices.newKieScanner(kieContainer);
kieScanner.scanNow();
Scanner scanner = new Scanner(System.in);
System.out.println("kieContainer.getKieBaseNames() "+kieContainer.getKieBaseNames());
KieSession newKieSession =kieContainer.newKieSession("session1");
KieBase lKieBase=newKieSession.getKieBase();
System.out.println("lPackage "+lKieBase.getKiePackages());
KiePackage lPackage=lKieBase.getKiePackage("org.demo.cityproject");
System.out.println("lPackage FactTypes: "+lPackage.getFactTypes());
for(FactType lFact:lPackage.getFactTypes())
{
System.out.println("lFacts: "+lFact.getName());
System.out.println("lFacts Fields: "+lFact.getFields());
}
}
Console o/p in eclipse
22:58:28.998 [main] DEBUG o.d.c.k.b.impl.KieRepositoryImpl - KieModule Lookup. ReleaseId org.demo:CityProject:LATEST was not in cache, checking maven repository
22:58:37.430 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:37.743 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.455 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:39.503 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:41.744 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=1, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=1, DefaultDependencyCollector.collectTime=32, DefaultDependencyCollector.transformTime=15}
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.230 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:42.246 [main] DEBUG o.e.a.i.i.DefaultDependencyCollector - Dependency collection stats: {ConflictMarker.analyzeTime=0, ConflictMarker.markTime=0, ConflictMarker.nodeCount=1, ConflictIdSorter.graphTime=0, ConflictIdSorter.topsortTime=0, ConflictIdSorter.conflictIdCount=0, ConflictIdSorter.conflictIdCycleCount=0, ConflictResolver.totalTime=0, ConflictResolver.conflictItemCount=0, DefaultDependencyCollector.collectTime=0, DefaultDependencyCollector.transformTime=0}
22:58:47.596 [main] INFO o.d.c.k.b.impl.KieRepositoryImpl - KieModule was added: ZipKieModule[releaseId=org.demo:CityProject:1.0,file=C:\Users\USER\.m2\repository\org\demo\CityProject\1.0\CityProject-1.0.jar]
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:47.957 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.426 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.442 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultLocalRepositoryProvider - Using manager EnhancedLocalRepositoryManager with priority 10.0 for C:\Users\USER\.m2\repository
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
22:58:48.457 [main] DEBUG o.e.a.i.i.DefaultUpdateCheckManager - Skipped remote request for org.demo:CityProject/maven-metadata.xml, locally installed metadata up-to-date.
kieContainer.getKieBaseNames() [KnowledgeBaseALL]
22:58:50.532 [main] DEBUG o.drools.core.impl.KnowledgeBaseImpl - Starting Engine in PHREAK mode
lPackage [[Package name=org.demo.cityproject]]
lPackage FactTypes: [ClassDefinition{className='org.demo.cityproject.CustomerFact', superClass='java.lang.Object', interfaces=[java.io.Serializable], definedClass=class org.demo.cityproject.CustomerFact, traitable=null, abstract=false, fields={}, annotations=null}]
lFacts: org.demo.cityproject.CustomerFact
**lFacts Fields: []**
As you can see in the output fact field is empty.
The - rather disappointing - situation is that there are two or even three kinds of FactTypes:
Fact types defined by a declare statement in a DRL file
Fact types resulting from Java classes and imported explicitly or implicitly
JDK types used as fact types
Method getFactTypes does not return #3. Method getFields returns an empty list for #2.
Finally I found an answer. Such fields can be invoked by reflection.
Here is how the rules get triggered
for(FactType lFct:lusedpackage.getFactTypes())
{
// System.out.println("Customer class "+lFct.getFactClass());
**Constructor constructor=lFct.getFactClass().getConstructor(String.class,java.math.BigInteger.class);**
**Object s1=constructor.newInstance(lcity,lcustomerID);**
//System.out.println("constructor "+constructor);
//System.out.println("Object "+s1);
**Method lCustID=lFct.getFactClass().getMethod("getCustomerID");**
System.out.println("*************************************************************");
System.out.println("Customer value before firing the rule: "+ lCustID.invoke(s1));
**Method setCity = lFct.getFactClass().getMethod("getCity");**
System.out.println("City value before firing the rule: "+ setCity.invoke(s1));
//System.out.println("method "+lCustID);
System.out.println("*************************************************************");
newKieSession.insert(s1);
newKieSession.fireAllRules();
System.out.println("Customer value after firing the rule: "+ **lCustID.invoke(s1)**);
System.out.println("City value after firing the rule: "+ setCity.invoke(s1));
System.out.println("*************************************************************");
}

JMeter - XMPP Authentication

I am building a test plan to test XMPP with JMeter. But I always meet an error when I send a authentication string to server even the authentication string is correct. Does anybody have the same problem or know how to fix this issue? Thanks.
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: Running the test!
2014/07/04 10:23:22 INFO - jmeter.gui.util.JMeterMenuBar: setRunning(true,*local*)
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: Thread will continue on error
2014/07/04 10:23:22 INFO - jmeter.threads.ThreadGroup: Starting thread group number 1 threads 1 ramp-up 1 perThread 1000.0 delayedStart=false
2014/07/04 10:23:22 INFO - jmeter.threads.ThreadGroup: Started thread group number 1
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: All thread groups have been started
2014/07/04 10:23:22 INFO - jmeter.threads.JMeterThread: Thread started: Thread Group 1-1
2014/07/04 10:23:22 ERROR - ru.yandex.jmeter.XMPPClientImpl: Error reading data java.lang.RuntimeException: Retries more than 1000, aborting read
at ru.yandex.jmeter.XMPPClientImpl.read(XMPPClientImpl.java:116)
at org.apache.jmeter.protocol.tcp.sampler.TCPSampler.sample(TCPSampler.java:414)
at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:428)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256)
at java.lang.Thread.run(Unknown Source)
2014/07/04 10:23:22 ERROR - jmeter.protocol.tcp.sampler.TCPSampler: java.lang.RuntimeException: Error reading data
at ru.yandex.jmeter.XMPPClientImpl.read(XMPPClientImpl.java:152)
at org.apache.jmeter.protocol.tcp.sampler.TCPSampler.sample(TCPSampler.java:414)
at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:428)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.RuntimeException: Retries more than 1000, aborting read
at ru.yandex.jmeter.XMPPClientImpl.read(XMPPClientImpl.java:116)
... 4 more
2014/07/04 10:23:22 INFO - jmeter.threads.JMeterThread: Thread finished: Thread Group 1-1
2014/07/04 10:23:22 INFO - jmeter.engine.StandardJMeterEngine: Notifying test listeners of end of test
2014/07/04 10:23:22 INFO - jmeter.gui.util.JMeterMenuBar: setRunning(false,*local*)
I had tried using XMPPClientImpl plugin but always got the same error ("Retries more than 1000, aborting read"), so I decided to leave it and write my own code.
I use a BeanShell Sampler in which I run the following code (using smack library) to connect to XMPP server.
String CLASS_PATH = "C:/JMeter/apache-jmeter-2.13/lib/ext/smack/";
addClassPath(CLASS_PATH + "smack-android-extensions-4.1.3.jar");
addClassPath(CLASS_PATH + "smack-tcp-4.1.3.jar");
addClassPath(CLASS_PATH + "smack-android-4.1.3.jar");
// explicitly import every class you need
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
String jabberId = "...";
String jabberPass = "...";
String SERVER_ADDRESS = "...";
int PORT = 5222; // or any other port
XMPPTCPConnection getConnection() {
XMPPTCPConnectionConfiguration config =
XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(jabberId, jabberPass)
.setHost(SERVER_ADDRESS)
.setServiceName(SERVER_ADDRESS)
.setPort(DEFAULT_PORT)
// .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setSendPresence(true)
// .setDebuggerEnabled(YouMe.DEBUG)
.build();
XMPPTCPConnection con = new XMPPTCPConnection(config);
int REPLY_TIMEOUT = 50000; // 50 seconds, but can be shorter
con.setPacketReplyTimeout(REPLY_TIMEOUT);
return con;
}
Don't forget to add the smack path (e.g. C:\JMeter\apache-jmeter-2.13\lib\ext\smack) to the library field (under "Add directory or jar classpath") in the Test Plan node of your test plan.
To connect -
con = getConnection();
con.connect();
To login -
con.login(jabberId, jabberPass);
You can also add connection listener -
ConnectionListener listener = new ConnectionListener() {
public void connected(XMPPConnection xmppConnection) {
// run main code incl. the login code
runMain();
}
public void authenticated(XMPPConnection xmppConnection, boolean resumed) {
}
public void connectionClosed() {
}
public void connectionClosedOnError(Exception e) {
}
public void reconnectingIn(int i) {
}
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception e) {
}
};
con.addConnectionListener(listener);
// connect
con.connect();
runMain() {
con.login(jabberId, jabberPass);
// ...
}