I'm currently trying to have my device (program) show up as a mock chromecast on the network. The application itself can see the Mock-Caster as a chromecast but if i try searching for it using Youtube or any other sender app, the "Mock-Caster" does not appear in the list.
I registered a service on jmDNS with all the criteria that would be available on an actual chromecast as well.
Is there something that I am missing or getting wrong?
Here's what I have so far.
public void postConstruct() throws Exception {
InetAddress discoveryInterface = InetAddress.getByName("192.168.1.1");
CAST_DEVICE_MONITOR.startDiscovery(discoveryInterface, "Mock-Server");
CAST_DEVICE_MONITOR.registerListener(new DeviceDiscoveryListener() {
#Override
public void deviceDiscovered(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
#Override
public void deviceRemoved(CastDevice castDevice) {
System.out.println("New chrome cast detected: " + castDevice);
}
});
JmDNS jmdns = JmDNS.create(discoveryInterface, "Mock-Server");
final String name = "Mock-Caster";
final String id = UUID.randomUUID().toString();
// Register a service
HashMap<String, String> properties = new HashMap<>();
//values scraped from chromecast or another java project
properties.put("sf", "1");
properties.put("id", id);
properties.put("md", name);
properties.put("fd", name);
properties.put("s#", "1");
properties.put("ff", "0");
properties.put("ci", "1");
properties.put("c#", Integer.toString(1));
properties.put("pv", "1.1");
properties.put("cd", "E465315D08CFDEF2742E1264D78F6035");
properties.put("rm", "ED724E435DA8115C");
properties.put("ve", "05");
properties.put("ic", "/setup/icon.png");
properties.put("ca", "201221");
properties.put("st", "0");
properties.put("bs", "FA8FCA771881");
properties.put("nf", "1");
properties.put("rs", "");
ServiceInfo serviceInfo = ServiceInfo.create("_googlecast._tcp.local.", name, 8009, 1, 1, properties);
jmdns.registerService(serviceInfo);
}
//This is where i know that the mock-caster is registered and available
#Bean
public IntegrationFlow tcpServer() throws Exception {
TcpNioServerConnectionFactory factory = new TcpNioServerConnectionFactory(8009);
DefaultTcpSSLContextSupport defaultTcpSSLContextSupport = new DefaultTcpSSLContextSupport(keystore, keystore, password, password);
defaultTcpSSLContextSupport.setProtocol("TLS");
factory.setTcpNioConnectionSupport(new DefaultTcpNioSSLConnectionSupport(defaultTcpSSLContextSupport));
factory.setTcpSocketSupport(new DefaultTcpSocketSupport(false));
factory.setDeserializer(TcpCodecs.lengthHeader4());
factory.setSerializer(TcpCodecs.lengthHeader4());
TcpInboundGatewaySpec inboundGateway = Tcp.inboundGateway(factory);
return IntegrationFlows
.from(inboundGateway)
.handle(message -> {
String ip_address = message.getHeaders().get("ip_address").toString();
if(ip_address.equalsIgnoreCase("192.168.1.1")) {
System.out.println("Self IP Address received");
System.out.println("Payload: " + message.getPayload());
System.out.println("MessageHeaders: " + message.getHeaders());
}else{
System.out.println("Other IP address received: " + ip_address);
}
})
.get();
}
//Mock-Caster detected here
#Scheduled(fixedRate = 15000)
public void checkCasters() throws Exception {
Set<CastDevice> casters = CAST_DEVICE_MONITOR.getCastDevices();
System.out.println("Current CCs: " + casters.size());
for (CastDevice device : casters) {
System.out.println("CC (" + device.getDisplayName() + ")");
var receiver = new CastEvent.CastEventListener() {
#Override
public void onEvent(#Nonnull CastEvent<?> castEvent) {
System.out.println("Event: " + castEvent);
}
};
var appId = DEFAULT_MEDIA_RECEIVER_APP;
try {
if (!device.isConnected()) {
device.connect();
}
device.addEventListener(receiver);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
device.removeEventListener(receiver);
device.disconnect();
}
}
Related
I need to set up a JITR (Just in time registration) process to AWS IOT core for my Android Application using Android AWS IOT SDK. My implementation is done referring this . However, When trying to create a thing after creating a fresh X.509 certificate (On the first connection attempt), Even though the certificate is created on the server, the Server returns errors regarding "unmatched signatures and an empty template body".
This is my current sample implementation,
public class MainActivity extends AppCompatActivity {
private boolean thingExist;
private String certificateARN;
// IoT endpoint
// AWS Iot CLI describe-endpoint call returns: XXXXXXXXXX.iot.<region>.amazonaws.com
private static final String CUSTOMER_SPECIFIC_ENDPOINT = "";
// Cognito pool ID. For this app, pool needs to be unauthenticated pool with
// AWS IoT permissions.
private static final String COGNITO_POOL_ID = "";
// Name of the AWS IoT policy to attach to a newly created certificate
private static final String AWS_IOT_POLICY_NAME = "";
// Region of AWS IoT
private static final Regions MY_REGION = Regions.US_EAST_2;
// Filename of KeyStore file on the filesystem
private static final String KEYSTORE_NAME = "iot_keystore";
// Password for the private key in the KeyStore
private static final String KEYSTORE_PASSWORD = "password";
// Certificate and key aliases in the KeyStore
private static final String CERTIFICATE_ID = "default";
AWSIotClient mIotAndroidClient;
AWSIotMqttManager mqttManager;
String clientId;
String keystorePath;
String keystoreName;
String keystorePassword;
private boolean isAWSConnected;
private listThings mTask;
private boolean certificateExist;
private final String LOG_TAG = "AWS";
private final String serialId = "1110";
KeyStore clientKeyStore = null;
String certificateId;
CognitoCachingCredentialsProvider credentialsProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientId = Settings.Global.getString(getApplicationContext().getContentResolver(), "device_name");
// Initialize the AWS Cognito credentials provider
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(), // context
COGNITO_POOL_ID, // Identity Pool ID
MY_REGION // Region
);
Region region = Region.getRegion(MY_REGION);
// MQTT Client
mqttManager = new AWSIotMqttManager(clientId, CUSTOMER_SPECIFIC_ENDPOINT);
// Set keepalive to 10 seconds. Will recognize disconnects more quickly but will also send
// MQTT pings every 10 seconds.
mqttManager.setKeepAlive(10);
// Set Last Will and Testament for MQTT. On an unclean disconnect (loss of connection)
// AWS IoT will publish this message to alert other clients.
AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("Last will",
new Gson().toJson("Android client lost connection"), AWSIotMqttQos.QOS0);
mqttManager.setMqttLastWillAndTestament(lwt);
mIotAndroidClient = new AWSIotClient(credentialsProvider);
mIotAndroidClient.setRegion(region);
keystorePath = getFilesDir().getPath();
keystoreName = KEYSTORE_NAME;
keystorePassword = KEYSTORE_PASSWORD;
certificateId = CERTIFICATE_ID;
// To load cert/key from keystore on filesystem
try {
if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) {
if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath,
keystoreName, keystorePassword)) {
Log.i(LOG_TAG, "Certificate " + certificateId
+ " found in keystore - using for MQTT.");
// load keystore from file into memory to pass on connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
certificateExist = true;
mTask = (listThings) new listThings().execute();
} else {
Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore.");
}
} else {
Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found.");
}
} catch (Exception e) {
Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e);
}
if (clientKeyStore == null) {
certificateExist = false;
Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
new Thread(new Runnable() {
#Override
public void run() {
try {
// Create a new private key and certificate. This call
// creates both on the server and returns them to the
// device.
CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
new CreateKeysAndCertificateRequest();
createKeysAndCertificateRequest.setSetAsActive(true);
final CreateKeysAndCertificateResult createKeysAndCertificateResult;
createKeysAndCertificateResult =
mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);
Log.i(LOG_TAG,
"Cert ID: " +
createKeysAndCertificateResult.getCertificateId() +
" created.");
// store in keystore for use in MQTT client
// saved as alias "default" so a new certificate isn't
// generated each run of this application
AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
createKeysAndCertificateResult.getCertificatePem(),
createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
keystorePath, keystoreName, keystorePassword);
certificateARN = createKeysAndCertificateResult.getCertificateArn();
// load keystore from file into memory to pass on
// connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
// Attach a policy to the newly created certificate.
// This flow assumes the policy was already created in
// AWS IoT and we are now just attaching it to the
// certificate.
AttachPrincipalPolicyRequest policyAttachRequest =
new AttachPrincipalPolicyRequest();
policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
policyAttachRequest.setPrincipal(createKeysAndCertificateResult
.getCertificateArn());
mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
mTask = (listThings) new listThings().execute();
} catch (Exception e) {
Log.e(LOG_TAG,
"Exception occurred when generating new private key and certificate.",
e);
}
}
}).start();
}
}
private class listThings extends AsyncTask<Void, Void, Boolean> {
// Listing registered things to verify whether a thing already exist under the same device ID.
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(LOG_TAG, "Listing Things");
final ListThingsRequest request = new ListThingsRequest().withAttributeName("Device_ID")
.withAttributeValue(serialId).withMaxResults(1);
final ListThingsResult result = mIotAndroidClient.listThings(request);
if (!result.getThings().isEmpty()) {
thingExist = true;
return true;
} else {
thingExist = false;
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Log.d(LOG_TAG, "onPostExecute: " + aBoolean.toString());
if (certificateExist) {
new createThing().execute();
} else {
new awsAsync().execute();
}
mTask.cancel(true);
}
}
private class awsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (thingExist) {
//Thing Exist, certificate doesn't exist
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
Log.d(LOG_TAG, "certificateARN " + certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
/*check if previous certificates are available and delete them*/
} else {
//Thing Doesn't Exist, certificate doesn't exist
try {
Log.d(LOG_TAG, "Thing does not Exist, certificate doesn't exist");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(certificateARN);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
connectToAWS();
}
}
private class createThing extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
if (!thingExist) {
try {
//Thing doesn't exist, Certificate exist
Log.d(LOG_TAG, "Thing does not Exist. Creating a thing");
Map<String, String> attributes = new HashMap<String, String>() {{
put("Device_ID", serialId);
put("Android_version", Build.VERSION.RELEASE);
}};
CreateThingRequest createThingRequest = new CreateThingRequest();
createThingRequest.setThingName(serialId);
AttributePayload attributePayload = new AttributePayload();
attributePayload.setAttributes(attributes);
createThingRequest.setThingTypeName("Consenz_search");
createThingRequest.setAttributePayload(attributePayload);
mIotAndroidClient.createThing(createThingRequest);
AddThingToThingGroupRequest addThingToThingGroupRequest = new AddThingToThingGroupRequest();
addThingToThingGroupRequest.setThingName(serialId);
addThingToThingGroupRequest.setThingGroupName("Consenz_Group");
mIotAndroidClient.addThingToThingGroup(addThingToThingGroupRequest);
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
thingPrincipalRequest.setPrincipal(AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE_PASSWORD);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
//need to attach the current thing to existing certificate.
} catch (Exception e) {
Log.e(LOG_TAG,
"Excepetion occured when creating thing",
e);
}
} else {
//Thing exist, Certificate exist
//need to attach the current thing to existing certificate.
Log.d(LOG_TAG, "We here");
final ListThingPrincipalsRequest request = new ListThingPrincipalsRequest().withThingName(serialId);
final ListThingPrincipalsResult result = mIotAndroidClient.listThingPrincipals(request);
DescribeCertificateRequest request1 = new DescribeCertificateRequest().withCertificateId("default");
DescribeCertificateResult result1 = mIotAndroidClient.describeCertificate(request1);
String arn = result1.getCertificateDescription().getCertificateArn();
result.toString();
Log.d(LOG_TAG, "arn " + arn);
Log.d(LOG_TAG, "certificates " + result);
//Log.d(LOG_TAG, "Thing Exists. Attaching thing to certificate");
AttachThingPrincipalRequest thingPrincipalRequest = new AttachThingPrincipalRequest();
thingPrincipalRequest.setThingName(serialId);
//String arn = thingPrincipalRequest.getPrincipal(c);
//Log.d(LOG_TAG, "arn "+arn);
mIotAndroidClient.attachThingPrincipal(thingPrincipalRequest);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Log.d(LOG_TAG, "Done creating thing");
connectToAWS();
}
}
private void connectToAWS() {
try {
Log.d(LOG_TAG, "Client ID: " + clientId);
mqttManager.connect(clientKeyStore, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
Log.d(LOG_TAG, "Connecting...");
isAWSConnected = false;
} else if (status == Connected) {
Log.d(LOG_TAG, "Connected");
isAWSConnected = true;
//creatething
publishToAWS();
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
isAWSConnected = false;
}
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
} else {
isAWSConnected = false;
Log.d(LOG_TAG, "Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.d(LOG_TAG, "Error! " + e.getMessage());
}
}
private void publishToAWS() {
//publishing MQQT messages to AWS
String version = "";
String versionRelease = Build.VERSION.RELEASE;
try {
version = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
try {
mqttManager.publishString(new Gson().toJson(serialId), "Device_ID", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(version), "APK_Version", AWSIotMqttQos.QOS0);
mqttManager.publishString(new Gson().toJson(versionRelease), "Android_Version", AWSIotMqttQos.QOS0);
} catch (Exception e) {
Log.e(LOG_TAG, "Publish error.", e);
}
}
}
what am I doing wrong here? thanks in advance.
I have this sendmail function that I want to Test in Junit 4 using MockMvc.
I have provided my test case and WiserAssertions.java file I am using to test the function.
When testing the Junit test case I am getting the AssertionError that
java.lang.AssertionError: No message from [demoprojintern#gmail.com] found!
at com.appointment.request.controller.WiserAssertions.lambda$7(WiserAssertions.java:67)
Can someone help me out what am I missing?
sendmail() function
public void sendmail(Request request) throws AddressException, MessagingException, IOException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
String email = request.getEmail();
int requestId1 = request.getRequestId();
String requestId = Integer.toString(requestId1);
String name = request.getLegalName();
String cause = request.getCause();
String doa = request.getDateOfAppointment();
String toa = request.getAppointmentTime();
int status = request.getRequestStatus();
String generic = "Hello, " + name + "<br><br>" + "Your request with Request ID: " + requestId + " for " + "the cause of "
+ cause + " on " + doa + " at " + toa + " has been ";
String regards = "<br><br><br>Thanks and Regards,<br>";
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("<my-email-id>", "<my-email-id's password");
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("<my-email-id>", false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
msg.setSubject("Regarding your Appointment Request");
msg.setContent(" ", "text/html");
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
if (status == 0) {
String messageForPendingRequest = generic + "<strong>RECEIVED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
if (status == 1) {
String messageForPendingRequest = generic + "<strong>APPROVED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
if (status == 2) {
String messageForPendingRequest = generic + "<strong>SUGGESTED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
}
These are the dependencies of my pom.xml for sending the email and testing the mail respectively
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>3.1.7</version>
<scope>test</scope>
</dependency>
This is my junit test case
private Wiser wiser;
#Test
public void send() throws Exception {
Request request = new Request(1234, "Richie Rich", "<patient's-email-id>", "Brain", 27, "2019-12-17", "13:00", 0, "", "", "");
String email = request.getEmail();
int requestId1 = request.getRequestId();
String requestId = Integer.toString(requestId1);
String name = request.getLegalName();
String cause = request.getCause();
String doa = request.getDateOfAppointment();
String toa = request.getAppointmentTime();
String generic = "Hello, " + name + "<br><br>" + "Your request with Request ID: "
+ requestId + " for " + "the cause of "
+ cause + " on " + doa + " at " + toa + " has been ";
String regards = "<br><br><br>Thanks and Regards,<br>";
String jsonRequest = objectMapper.writeValueAsString(request);
this.mockMvc.perform(post("/sendemail").content(jsonRequest).contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
// assert
WiserAssertions.assertReceivedMessage(wiser)
.from("<sender-mail-id>")
.to(email)
.withSubject("Regarding your Appointment Request")
.withContent(generic + "<strong>RECEIVED</strong>." + regards);
}
This is my WiserAssertions.java that I got from a blog
public class WiserAssertions {
private final List<WiserMessage> messages;
private WiserAssertions(List<WiserMessage> messages) {
this.messages = messages;
}
public static WiserAssertions assertReceivedMessage(Wiser wiser) {
return new WiserAssertions(wiser.getMessages());
}
private static Supplier<AssertionError> assertionError(String errorMessage, String... args) {
return () -> new AssertionError(MessageFormat.format(errorMessage, args));
}
public static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public WiserAssertions from(String from) {
findFirstOrElseThrow(m -> m.getEnvelopeSender().equals(from),
assertionError("No message from [{0}] found!", from));
return this;
}
public WiserAssertions to(String to) {
findFirstOrElseThrow(m -> m.getEnvelopeReceiver().equals(to),
assertionError("No message to [{0}] found!", to));
return this;
}
public WiserAssertions withSubject(String subject) {
Predicate<WiserMessage> predicate = m -> subject.equals(unchecked(getMimeMessage(m)::getSubject));
findFirstOrElseThrow(predicate,
assertionError("No message with subject [{0}] found!", subject));
return this;
}
public WiserAssertions withContent(String content) {
findFirstOrElseThrow(m -> {
ThrowingSupplier<String> contentAsString =
() -> ((String) getMimeMessage(m).getContent()).trim();
return content.equals(unchecked(contentAsString));
}, assertionError("No message with content [{0}] found!", content));
return this;
}
private void findFirstOrElseThrow(Predicate<WiserMessage> predicate, Supplier<AssertionError> exceptionSupplier) {
messages.stream().filter(predicate)
.findFirst().orElseThrow(exceptionSupplier);
}
private MimeMessage getMimeMessage(WiserMessage wiserMessage) {
return unchecked(wiserMessage::getMimeMessage);
}
interface ThrowingSupplier<T> {
T get() throws Throwable;
}
}
I have simple Vertx-based websocket chatting app. It consists of two parts MsgServerVerticle and MsgClientVerticle (source code below). So, if I am instantiating one server and only one client it looks like working normally. After second client connects, server starts trying to announce it to other clients. And things gonna weird. Log says that netty backed are encoding-decoding websocket frames continuously in loop. There is no difference what type of frames I am using, binary or text, issues are the same.
log screenshot here
What's wrong?
MsgClientVerticle Source code:
private Logger L;
private String eBusTag;
private String backwardTag;
private String targetHost;
private int port;
private String id;
private String path;
private EventBus eBus;
private HttpClient client;
public MsgClientVerticle(String eBusTag, String targetHost, int port, String path, String id, String backwardTag) {
this.eBusTag = eBusTag;
this.targetHost = targetHost;
this.path = path;
this.port = port;
this.id = id;
this.backwardTag = backwardTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
L.info("Initializing client connection to " + targetHost + ":" + port + path);
eBus = vertx.eventBus();
try {
client = vertx.createHttpClient();
client.websocket(port, targetHost, path, webSock -> {
L.info("Connected to " + targetHost + ":" + port + "/" + path);
eBus.publish(backwardTag, Utils.msg("Connected"));
webSock.binaryMessageHandler(buf -> {
eBus.publish(backwardTag, Utils.bufToJson(buf));
});
eBus.consumer(eBusTag).handler(msg -> {
JsonObject message = (JsonObject) msg.body();
webSock.writeBinaryMessage(Utils.jsonToBuf(message));
});
});
} catch (NullPointerException e) {
L.error("Null Pointer: " + e.getLocalizedMessage());
e.printStackTrace();
}
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
L.info("Connection to " + targetHost + ":" + port + "/" + path + " closed");
client.close();
stopFuture.complete();
}
And MsgServerVerticle source:
private Logger L;
private String path;
private int port;
private String eBusTag;
private String backwardTag;
private HttpServer server;
private EventBus eBus;
private Set<ServerWebSocket> conns;
public MsgServerVerticle(int port, String eBusTag, String backwardTag) {
this.port = port;
this.eBusTag = eBusTag;
this.backwardTag = backwardTag;
conns = new ConcurrentSet<>();
path = eBusTag;
L = LoggerFactory.getLogger(eBusTag);
}
#Override
public void start(Future<Void> startFuture) throws Exception {
eBus = vertx.eventBus();
L.info("Initializing server instance at port " + port);
server = vertx.createHttpServer();
server.websocketHandler(webSock -> {
if (!webSock.path().equals(path)) {
webSock.reject();
} else {
conns.add(webSock);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(Utils.jsonToBuf(Utils.msg("SERVER: new client " + webSock.remoteAddress().toString())));
}
});
eBus.publish(backwardTag, Utils.msg("SERVER: new client " + webSock.remoteAddress().toString()));
webSock.binaryMessageHandler(buf -> {
JsonObject msg = Utils.bufToJson(buf);
conns.forEach(sock -> {
if (sock != webSock) {
sock.writeBinaryMessage(buf);
}
});
eBus.publish(backwardTag, msg);
});
}
});
server.listen(port);
startFuture.complete();
}
#Override
public void stop(Future<Void> stopFuture) throws Exception {
conns.forEach(sock -> {
sock.writeFinalTextFrame("Server is shutting down...");
});
server.close();
stopFuture.complete();
}
I wasn't able to reproduce your original problem. But I had to make a few changes in the first place to test it.
One change is in initialization of your server:
this.path = "/" + eBusTag;
Otherwise this check will always fail:
if (!webSock.path().equals(this.path)) {
Since websock.path() will always start with /, hence /anything=/=anything
Second, please take a look how I initialized the clients, and check if you do the same:
final Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new MsgServerVerticle(8080,
"ebus",
"back"), new DeploymentOptions().setWorker(true), (r) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"a",
"back"), new DeploymentOptions().setWorker(true), (r2) -> {
vertx.deployVerticle(new MsgClientVerticle("ebus",
"127.0.0.1",
8080,
"/ebus",
"b",
"back"), new DeploymentOptions().setWorker(true), (r3) -> {
System.out.println("Done");
});
});
});
And third, as far as I could understand, your Utils class is something you implemented. My implementation looks as follows:
public class Utils {
public static Buffer jsonToBuf(final JsonObject message) {
return message.toBuffer();
}
public static JsonObject bufToJson(final Buffer buf) {
return buf.toJsonObject();
}
public static JsonObject msg(final String msg) {
return new JsonObject("{\"value\":\"" + msg + "\"}");
}
}
Hope that helps pinpoint your problem.
I have use alljoyn for wifi share. I want device list connected to wifi network on channel base.
I have follow one demo but it not call implemented method announced
AboutListener is part of alljoyn.
import org.alljoyn.bus.AboutListener;
public class OnboardingApplication extends Application implements AboutListener {
#Override
public void announced(String busName, int version, short port, AboutObjectDescription[] objectDescriptions, Map<String, Variant> aboutMap) {
Map<String, Object> newMap = new HashMap<String, Object>();
try {
newMap = TransportUtil.fromVariantMap(aboutMap);
String deviceId = (newMap.get(AboutKeys.ABOUT_APP_ID).toString());
String deviceFriendlyName = (String) newMap.get(AboutKeys.ABOUT_DEVICE_NAME);
m_logger.debug(TAG, "onAnnouncement received: with parameters: busName:" + busName + ", port:" + port + ", deviceid" + deviceId + ", deviceName:" + deviceFriendlyName);
addDevice(deviceId, busName, port, deviceFriendlyName, objectDescriptions, newMap);
} catch (BusException e) {
e.printStackTrace();
}
}
}
In order to get the announced method called you'll need to register your AboutListener:
org.alljoyn.bus.alljoyn.DaemonInit.PrepareDaemon(getApplicationContext());
//Bus Connection
Status status = mBus.connect();
//Check if connection is established
if (status != Status.OK) {
return;
}
//Setup Bus Attachment
mBus.useOSLogging(true);
mBus.setDebugLevel("ALLJOYN_JAVA", 7);
mBus.registerAboutListener(mListener);
//Start AboutData Listener
status = mBus.whoImplements(null);
if (status != Status.OK) {
Log.e(TAG, "whoImplements Error");
} else {
Log.w(TAG, "whoImplements Success");
}
mListener is your object that implements AboutListener.
When you call whoImplements(null) you are saying you want all announcements from all interfaces.
In addition to what LopesFigueiredo said, try creating your BusAttachment with a remote message policy of Receive. For example:
BusAttachment mBus = new BusAttachment("My Attachment", BusAttachment.RemoteMessage.Receive);
5 with jdk1.8 when I run the project. I got an Exception ExceptionInInitializerError. But when I run the same project in jdk1.6. It is running successfully. That error message as
Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at org.ofbiz.entity.GenericDelegator.initEntityEcaHandler(GenericDelegator.java:339)
at org.ofbiz.entity.DelegatorFactory.getDelegator(DelegatorFactory.java:42)
at org.ofbiz.catalina.container.CatalinaContainer.init(CatalinaContainer.java:175)
at org.ofbiz.base.container.ContainerLoader.loadContainer(ContainerLoader.java:189)
at org.ofbiz.base.container.ContainerLoader.load(ContainerLoader.java:66)
at org.ofbiz.base.start.Start.initStartLoaders(Start.java:260)
at org.ofbiz.base.start.Start.init(Start.java:97)
at org.ofbiz.base.start.Start.main(Start.java:411)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
at org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:308)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:331)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.createClassInfoFromStream(AsmClassInfo.java:790)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getClassInfo(AsmClassInfo.java:273)
at org.codehaus.aspectwerkz.reflect.impl.asm.AsmClassInfo.getInterfaces(AsmClassInfo.java:619)
at org.codehaus.aspectwerkz.reflect.ClassInfoHelper.implementsInterface(ClassInfoHelper.java:56)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:237)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.collectCustomProceedMethods(AbstractJoinPointCompiler.java:208)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.initialize(AbstractJoinPointCompiler.java:149)
at org.codehaus.aspectwerkz.transform.inlining.compiler.AbstractJoinPointCompiler.(AbstractJoinPointCompiler.java:133)
at org.codehaus.aspectwerkz.transform.inlining.compiler.MethodExecutionJoinPointCompiler.(MethodExecutionJoinPointCompiler.java:33)
at org.codehaus.aspectwerkz.transform.inlining.compiler.JoinPointFactory.compileJoinPoint(JoinPointFactory.java:86)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager$CompiledJoinPoint.(JoinPointManager.java:262)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.compileJoinPoint(JoinPointManager.java:251)
at org.codehaus.aspectwerkz.joinpoint.management.JoinPointManager.loadJoinPoint(JoinPointManager.java:118)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.aw$initJoinPoints(DelegatorEcaHandler.java)
at org.ofbiz.entityext.eca.DelegatorEcaHandler.(DelegatorEcaHandler.java)
... 13 more"
I found two files are problem when I run the project in jdk1.8 that coding files are:
CatalinaContainer.java
/**
* CatalinaContainer - Tomcat 5
*
*/
public class CatalinaContainer implements Container {
public static final String CATALINA_HOSTS_HOME = System.getProperty("ofbiz.home") + "/framework/catalina/hosts";
public static final String J2EE_SERVER = "OFBiz Container 3.1";
public static final String J2EE_APP = "OFBiz";
public static final String module = CatalinaContainer.class.getName();
protected static Map<String, String> mimeTypes = new HashMap<String, String>();
// load the JSSE propertes (set the trust store)
static {
SSLUtil.loadJsseProperties();
}
protected Delegator delegator = null;
protected Embedded embedded = null;
protected Map<String, ContainerConfig.Container.Property> clusterConfig = new HashMap<String, ContainerConfig.Container.Property>();
protected Map<String, Engine> engines = new HashMap<String, Engine>();
protected Map<String, Host> hosts = new HashMap<String, Host>();
protected boolean contextReloadable = false;
protected boolean crossContext = false;
protected boolean distribute = false;
protected boolean enableDefaultMimeTypes = true;
protected String catalinaRuntimeHome;
/**
* #see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
*/
public void init(String[] args, String configFile) throws ContainerException {
// get the container config
ContainerConfig.Container cc = ContainerConfig.getContainer("catalina-container", configFile);
if (cc == null) {
throw new ContainerException("No catalina-container configuration found in container config!");
}
// embedded properties
boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
//int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);
// grab some global context settings
this.delegator = DelegatorFactory.getDelegator(ContainerConfig.getPropertyValue(cc, "delegator-name", "default"));
this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);
this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");
// set catalina_home
System.setProperty("catalina.home", System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
// configure JNDI in the StandardServer
StandardServer server = (StandardServer) ServerFactory.getServer();
try {
server.setGlobalNamingContext(new InitialContext());
} catch (NamingException e) {
throw new ContainerException(e);
}
// create the instance of Embedded
embedded = new Embedded();
embedded.setUseNaming(useNaming);
// create the engines
List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
if (UtilValidate.isEmpty(engineProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no engines defined!");
}
for (ContainerConfig.Container.Property engineProp: engineProps) {
createEngine(engineProp);
}
// load the web applications
loadComponents();
// create the connectors
List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
if (UtilValidate.isEmpty(connectorProps)) {
throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
}
for (ContainerConfig.Container.Property connectorProp: connectorProps) {
createConnector(connectorProp);
}
try {
embedded.initialize();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
}
public boolean start() throws ContainerException {
// Start the embedded server
try {
embedded.start();
} catch (LifecycleException e) {
throw new ContainerException(e);
}
for (Connector con: embedded.findConnectors()) {
ProtocolHandler ph = con.getProtocolHandler();
if (ph instanceof Http11Protocol) {
Http11Protocol hph = (Http11Protocol) ph;
Debug.logInfo("Connector " + hph.getProtocols() + " # " + hph.getPort() + " - " +
(hph.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
} else {
Debug.logInfo("Connector " + con.getProtocol() + " # " + con.getPort() + " - " +
(con.getSecure() ? "secure" : "not-secure") + " [" + con.getProtocolHandlerClassName() + "] started.", module);
}
}
Debug.logInfo("Started " + ServerInfo.getServerInfo(), module);
return true;
}
protected Engine createEngine(ContainerConfig.Container.Property engineConfig) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Engine without Embedded instance!");
}
ContainerConfig.Container.Property defaultHostProp = engineConfig.getProperty("default-host");
if (defaultHostProp == null) {
throw new ContainerException("default-host element of server property is required for catalina!");
}
String engineName = engineConfig.name;
String hostName = defaultHostProp.value;
StandardEngine engine = (StandardEngine) embedded.createEngine();
engine.setName(engineName);
engine.setDefaultHost(hostName);
// set the JVM Route property (JK/JK2)
String jvmRoute = ContainerConfig.getPropertyValue(engineConfig, "jvm-route", null);
if (jvmRoute != null) {
engine.setJvmRoute(jvmRoute);
}
// create the default realm -- TODO: make this configurable
String dbConfigPath = "catalina-users.xml";
MemoryRealm realm = new MemoryRealm();
realm.setPathname(dbConfigPath);
engine.setRealm(realm);
// cache the engine
engines.put(engine.getName(), engine);
// create a default virtual host; others will be created as needed
Host host = createHost(engine, hostName);
hosts.put(engineName + "._DEFAULT", host);
// configure clustering
List<ContainerConfig.Container.Property> clusterProps = engineConfig.getPropertiesWithValue("cluster");
if (clusterProps != null && clusterProps.size() > 1) {
throw new ContainerException("Only one cluster configuration allowed per engine");
}
if (UtilValidate.isNotEmpty(clusterProps)) {
ContainerConfig.Container.Property clusterProp = clusterProps.get(0);
createCluster(clusterProp, host);
clusterConfig.put(engineName, clusterProp);
}
// request dumper valve
boolean enableRequestDump = ContainerConfig.getPropertyValue(engineConfig, "enable-request-dump", false);
if (enableRequestDump) {
RequestDumperValve rdv = new RequestDumperValve();
engine.addValve(rdv);
}
// configure the CrossSubdomainSessionValve
boolean enableSessionValve = ContainerConfig.getPropertyValue(engineConfig, "enable-cross-subdomain-sessions", false);
if (enableSessionValve) {
CrossSubdomainSessionValve sessionValve = new CrossSubdomainSessionValve();
engine.addValve(sessionValve);
}
// configure the access log valve
String logDir = ContainerConfig.getPropertyValue(engineConfig, "access-log-dir", null);
AccessLogValve al = null;
if (logDir != null) {
al = new AccessLogValve();
if (!logDir.startsWith("/")) {
logDir = System.getProperty("ofbiz.home") + "/" + logDir;
}
File logFile = new File(logDir);
if (!logFile.isDirectory()) {
throw new ContainerException("Log directory [" + logDir + "] is not available; make sure the directory is created");
}
al.setDirectory(logFile.getAbsolutePath());
}
// configure the SslAcceleratorValve
String sslAcceleratorPortStr = ContainerConfig.getPropertyValue(engineConfig, "ssl-accelerator-port", null);
if (UtilValidate.isNotEmpty(sslAcceleratorPortStr)) {
Integer sslAcceleratorPort = Integer.valueOf(sslAcceleratorPortStr);
SslAcceleratorValve sslAcceleratorValve = new SslAcceleratorValve();
sslAcceleratorValve.setSslAcceleratorPort(sslAcceleratorPort);
engine.addValve(sslAcceleratorValve);
}
String alp2 = ContainerConfig.getPropertyValue(engineConfig, "access-log-pattern", null);
if (al != null && !UtilValidate.isEmpty(alp2)) {
al.setPattern(alp2);
}
String alp3 = ContainerConfig.getPropertyValue(engineConfig, "access-log-prefix", null);
if (al != null && !UtilValidate.isEmpty(alp3)) {
al.setPrefix(alp3);
}
boolean alp4 = ContainerConfig.getPropertyValue(engineConfig, "access-log-resolve", true);
if (al != null) {
al.setResolveHosts(alp4);
}
boolean alp5 = ContainerConfig.getPropertyValue(engineConfig, "access-log-rotate", false);
if (al != null) {
al.setRotatable(alp5);
}
if (al != null) {
engine.addValve(al);
}
embedded.addEngine(engine);
return engine;
}
protected Host createHost(Engine engine, String hostName) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Host without Embedded instance!");
}
Host host = embedded.createHost(hostName, CATALINA_HOSTS_HOME);
host.setDeployOnStartup(true);
host.setAutoDeploy(true);
host.setRealm(engine.getRealm());
engine.addChild(host);
hosts.put(engine.getName() + hostName, host);
return host;
}
protected Cluster createCluster(ContainerConfig.Container.Property clusterProps, Host host) throws ContainerException {
String defaultValveFilter = ".*.gif;.*.js;.*.jpg;.*.htm;.*.html;.*.txt;";
ReplicationValve clusterValve = new ReplicationValve();
clusterValve.setFilter(ContainerConfig.getPropertyValue(clusterProps, "rep-valve-filter", defaultValveFilter));
String mcb = ContainerConfig.getPropertyValue(clusterProps, "mcast-bind-addr", null);
String mca = ContainerConfig.getPropertyValue(clusterProps, "mcast-addr", null);
int mcp = ContainerConfig.getPropertyValue(clusterProps, "mcast-port", -1);
int mcf = ContainerConfig.getPropertyValue(clusterProps, "mcast-freq", 500);
int mcd = ContainerConfig.getPropertyValue(clusterProps, "mcast-drop-time", 3000);
if (mca == null || mcp == -1) {
throw new ContainerException("Cluster configuration requires mcast-addr and mcast-port properties");
}
McastService mcast = new McastService();
if (mcb != null) {
mcast.setMcastBindAddress(mcb);
}
mcast.setAddress(mca);
mcast.setPort(mcp);
mcast.setMcastDropTime(mcd);
mcast.setFrequency(mcf);
String tla = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-host", "auto");
int tlp = ContainerConfig.getPropertyValue(clusterProps, "tcp-listen-port", 4001);
int tlt = ContainerConfig.getPropertyValue(clusterProps, "tcp-sector-timeout", 100);
int tlc = ContainerConfig.getPropertyValue(clusterProps, "tcp-thread-count", 6);
//String tls = getPropertyValue(clusterProps, "", "");
if (tlp == -1) {
throw new ContainerException("Cluster configuration requires tcp-listen-port property");
}
NioReceiver listener = new NioReceiver();
listener.setAddress(tla);
listener.setPort(tlp);
listener.setSelectorTimeout(tlt);
listener.setMaxThreads(tlc);
listener.setMinThreads(tlc);
//listener.setIsSenderSynchronized(false);
ReplicationTransmitter trans = new ReplicationTransmitter();
try {
MultiPointSender mps = (MultiPointSender)Class.forName(ContainerConfig.getPropertyValue(clusterProps, "replication-mode", "org.apache.catalina.tribes.transport.bio.PooledMultiSender")).newInstance();
trans.setTransport(mps);
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid replication-mode property: " + exc.getMessage());
}
String mgrClassName = ContainerConfig.getPropertyValue(clusterProps, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
//int debug = ContainerConfig.getPropertyValue(clusterProps, "debug", 0);
// removed since 5.5.9? boolean expireSession = ContainerConfig.getPropertyValue(clusterProps, "expire-session", false);
// removed since 5.5.9? boolean useDirty = ContainerConfig.getPropertyValue(clusterProps, "use-dirty", true);
SimpleTcpCluster cluster = new SimpleTcpCluster();
cluster.setClusterName(clusterProps.name);
Manager manager = null;
try {
manager = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
//cluster.setManagerClassName(mgrClassName);
//host.setManager(manager);
//cluster.registerManager(manager);
cluster.setManagerTemplate((org.apache.catalina.ha.ClusterManager)manager);
//cluster.setDebug(debug);
// removed since 5.5.9? cluster.setExpireSessionsOnShutdown(expireSession);
// removed since 5.5.9? cluster.setUseDirtyFlag(useDirty);
GroupChannel channel = new GroupChannel();
channel.setChannelReceiver(listener);
channel.setChannelSender(trans);
channel.setMembershipService(mcast);
cluster.setChannel(channel);
cluster.addValve(clusterValve);
// removed since 5.5.9? cluster.setPrintToScreen(true);
// set the cluster to the host
host.setCluster(cluster);
Debug.logInfo("Catalina Cluster [" + cluster.getClusterName() + "] configured for host - " + host.getName(), module);
return cluster;
}
protected Connector createConnector(ContainerConfig.Container.Property connectorProp) throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot create Connector without Embedded instance!");
}
// need some standard properties
String protocol = ContainerConfig.getPropertyValue(connectorProp, "protocol", "HTTP/1.1");
String address = ContainerConfig.getPropertyValue(connectorProp, "address", "0.0.0.0");
int port = ContainerConfig.getPropertyValue(connectorProp, "port", 0);
boolean secure = ContainerConfig.getPropertyValue(connectorProp, "secure", false);
if (protocol.toLowerCase().startsWith("ajp")) {
protocol = "ajp";
} else if ("memory".equals(protocol.toLowerCase())) {
protocol = "memory";
} else if (secure) {
protocol = "https";
} else {
protocol = "http";
}
Connector connector = null;
if (UtilValidate.isNotEmpty(connectorProp.properties)) {
connector = embedded.createConnector(address, port, protocol);
try {
for (ContainerConfig.Container.Property prop: connectorProp.properties.values()) {
connector.setProperty(prop.name, prop.value);
//connector.setAttribute(prop.name, prop.value);
}
embedded.addConnector(connector);
} catch (Exception e) {
throw new ContainerException(e);
}
}
return connector;
}
protected Context createContext(ComponentConfig.WebappInfo appInfo) throws ContainerException {
// webapp settings
Map<String, String> initParameters = appInfo.getInitParameters();
List<String> virtualHosts = appInfo.getVirtualHosts();
Engine engine = engines.get(appInfo.server);
if (engine == null) {
Debug.logWarning("Server with name [" + appInfo.server + "] not found; not mounting [" + appInfo.name + "]", module);
return null;
}
// set the root location (make sure we set the paths correctly)
String location = appInfo.componentConfig.getRootLocation() + appInfo.location;
location = location.replace('\\', '/');
if (location.endsWith("/")) {
location = location.substring(0, location.length() - 1);
}
// get the mount point
String mount = appInfo.mountPoint;
if (mount.endsWith("/*")) {
mount = mount.substring(0, mount.length() - 2);
}
// configure persistent sessions
Property clusterProp = clusterConfig.get(engine.getName());
Manager sessionMgr = null;
if (clusterProp != null) {
String mgrClassName = ContainerConfig.getPropertyValue(clusterProp, "manager-class", "org.apache.catalina.ha.session.DeltaManager");
try {
sessionMgr = (Manager)Class.forName(mgrClassName).newInstance();
} catch (Exception exc) {
throw new ContainerException("Cluster configuration requires a valid manager-class property: " + exc.getMessage());
}
} else {
sessionMgr = new StandardManager();
}
// create the web application context
StandardContext context = (StandardContext) embedded.createContext(mount, location);
context.setJ2EEApplication(J2EE_APP);
context.setJ2EEServer(J2EE_SERVER);
context.setLoader(embedded.createLoader(ClassLoaderContainer.getClassLoader()));
context.setCookies(appInfo.isSessionCookieAccepted());
context.addParameter("cookies", appInfo.isSessionCookieAccepted() ? "true" : "false");
context.setDisplayName(appInfo.name);
context.setDocBase(location);
context.setAllowLinking(true);
context.setReloadable(contextReloadable);
context.setDistributable(distribute);
context.setCrossContext(crossContext);
context.setPrivileged(appInfo.privileged);
context.setManager(sessionMgr);
context.getServletContext().setAttribute("_serverId", appInfo.server);
context.getServletContext().setAttribute("componentName", appInfo.componentConfig.getComponentName());
// create the Default Servlet instance to mount
StandardWrapper defaultServlet = new StandardWrapper();
defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
defaultServlet.setServletName("default");
defaultServlet.setLoadOnStartup(1);
defaultServlet.addInitParameter("debug", "0");
defaultServlet.addInitParameter("listing", "true");
defaultServlet.addMapping("/");
context.addChild(defaultServlet);
context.addServletMapping("/", "default");
// create the Jasper Servlet instance to mount
StandardWrapper jspServlet = new StandardWrapper();
jspServlet.setServletClass("org.apache.jasper.servlet.JspServlet");
jspServlet.setServletName("jsp");
jspServlet.setLoadOnStartup(1);
jspServlet.addInitParameter("fork", "false");
jspServlet.addInitParameter("xpoweredBy", "true");
jspServlet.addMapping("*.jsp");
jspServlet.addMapping("*.jspx");
context.addChild(jspServlet);
context.addServletMapping("*.jsp", "jsp");
// default mime-type mappings
configureMimeTypes(context);
// set the init parameters
for (Map.Entry<String, String> entry: initParameters.entrySet()) {
context.addParameter(entry.getKey(), entry.getValue());
}
if (UtilValidate.isEmpty(virtualHosts)) {
Host host = hosts.get(engine.getName() + "._DEFAULT");
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
} else {
// assume that the first virtual-host will be the default; additional virtual-hosts will be aliases
Iterator<String> vhi = virtualHosts.iterator();
String hostName = vhi.next();
boolean newHost = false;
Host host = hosts.get(engine.getName() + "." + hostName);
if (host == null) {
host = createHost(engine, hostName);
newHost = true;
}
while (vhi.hasNext()) {
host.addAlias(vhi.next());
}
context.setRealm(host.getRealm());
host.addChild(context);
context.getMapper().setDefaultHostName(host.getName());
if (newHost) {
hosts.put(engine.getName() + "." + hostName, host);
}
}
return context;
}
protected void loadComponents() throws ContainerException {
if (embedded == null) {
throw new ContainerException("Cannot load web applications without Embedded instance!");
}
// load the applications
List<ComponentConfig.WebappInfo> webResourceInfos = ComponentConfig.getAllWebappResourceInfos();
List<String> loadedMounts = FastList.newInstance();
if (webResourceInfos != null) {
for (int i = webResourceInfos.size(); i > 0; i--) {
ComponentConfig.WebappInfo appInfo = webResourceInfos.get(i - 1);
String mount = appInfo.getContextRoot();
if (!loadedMounts.contains(mount)) {
createContext(appInfo);
loadedMounts.add(mount);
} else {
appInfo.appBarDisplay = false; // disable app bar display on overrided apps
Debug.logInfo("Duplicate webapp mount; not loading : " + appInfo.getName() + " / " + appInfo.getLocation(), module);
}
}
}
}
public void stop() throws ContainerException {
try {
embedded.stop();
} catch (LifecycleException e) {
// don't throw this; or it will kill the rest of the shutdown process
Debug.logVerbose(e, module); // happens usually when running tests, disabled unless in verbose
}
}
protected void configureMimeTypes(Context context) throws ContainerException {
Map<String, String> mimeTypes = CatalinaContainer.getMimeTypes();
if (UtilValidate.isNotEmpty(mimeTypes)) {
for (Map.Entry<String, String> entry: mimeTypes.entrySet()) {
context.addMimeMapping(entry.getKey(), entry.getValue());
}
}
}
protected static synchronized Map<String, String> getMimeTypes() throws ContainerException {
if (UtilValidate.isNotEmpty(mimeTypes)) {
return mimeTypes;
}
if (mimeTypes == null) mimeTypes = new HashMap<String, String>();
URL xmlUrl = UtilURL.fromResource("mime-type.xml");
// read the document
Document mimeTypeDoc;
try {
mimeTypeDoc = UtilXml.readXmlDocument(xmlUrl, true);
} catch (SAXException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (ParserConfigurationException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
} catch (IOException e) {
throw new ContainerException("Error reading the mime-type.xml config file: " + xmlUrl, e);
}
if (mimeTypeDoc == null) {
Debug.logError("Null document returned for mime-type.xml", module);
return null;
}
// root element
Element root = mimeTypeDoc.getDocumentElement();
// mapppings
for (Element curElement: UtilXml.childElementList(root, "mime-mapping")) {
String extension = UtilXml.childElementValue(curElement, "extension");
String type = UtilXml.childElementValue(curElement, "mime-type");
mimeTypes.put(extension, type);
}
return mimeTypes;
}
}
Class.class file
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
I'm confused state. Please help me to recover this issue.
Thanks in advance.
In the stacktrace there is a
Caused by: java.lang.ArrayIndexOutOfBoundsException: 5747 at
org.codehaus.aspectwerkz.org.objectweb.asm.ClassReader.readClass(Unknown Source)
ASM is a tool to read and manipulate Java class files.
There have been changes to the class file format between JDK 6 and 8 and you (most probably) have an outdated version of ASM which runs into problems when reading Java 8 class files.
To solve the issue try to upgrade to the latest version of ASM (or Ofbiz).
EDIT: As commented by integratingweb Opentaps only supports JDK 6.