asmack - receiving custom XML messages || - java

I've spend some time to add smack.providers in the android device, which is picked up by my application just fine. I've added the default iqProviders and extensionProviders, but I've also added my custom extensionProvider, which is the following:
<extensionProvider>
<elementName>players</elementName>
<namespace>boxer:players</namespace>
<className>company.games.boxer.PlayerListProvider</className>
</extensionProvider>
Let me also introduce the PlayerListProvider class, which is currently there just to see if it will get called (which it doesn't) - I'll implement it fully when I'll know it gets called, therefore at least that part of functionality works:
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.provider.EmbeddedExtensionProvider;
import android.util.Log;
#SuppressWarnings("deprecation")
class PlayerListProvider extends EmbeddedExtensionProvider {
protected PacketExtension createReturnExtension(String currentElement, String currentNamespace, Map<String,String> attributeMap, List<? extends PacketExtension> content) {
Log.w("***** AAAAAAAAAAAAAAAAAAAA *******", "0");
return new XMLPlayerList();
}
}
class XMLPlayerList implements PacketExtension {
public String getElementName() {
return "aaaaa";
}
public String getNamespace() {
return "aaaaa";
}
public String toXML() {
return "aaaaa";
}
}
And I'm getting the following message when I run the client android app:
<message to="eee#localhost" type="chat" id="9" from="admin#localhost">
<body>
<players xmlns="boxer:players" command="playerlist">
<player>test1</player>
<player>test2</player>
</players>
</body>
<thread>3P0i00</thread>
</message>
My question now is, why isn't the PlayerListProvider (EmbeddedExtensionProvider) called upon receiving the message. The message contains the tag and has the namespace of boxer:player, as I specified in smack.providers.
Any thoughts?

After reading about similar issues here on SO, I came across this question/answer and this blog post about another way (part 1) (part 2) to implement the custom message sending/receiving.
Have you considered using PacketExtensionProvider instead of EmbeddedExtensionProvider?
It's explained in more detail here, if you are interested in trying it out in place of the EmbeddedExtensionProvider. It might not be exactly what you are looking for... (it appears like it takes more of a manual-parsing approach,) but it might get your PlayerListProvider class recognized (via extending the PEPEvent class.)

Related

JUnit Testing: How to test a custom, empty java class that extends Exception?

I am currently attempting to extend test coverage for a school-based-assignment web application after I came across a completely empty class that extends Exception and contains no coverage according to the coverage report.
Normally, I would assume that something like this could be disregarded. However, our overall test coverage factor directly into our individual grading for this course. Because of this and it being near the end of the semester, I am trying to go through the code flagged within the coverage report line-by-line and tidy up anything I can.
After going through course content and searches online, I am unsure of how to proceed with writing a test for a class such as this. This server-side class was included in our initial code base that was given to us at the start of the semester by the instructor (we build onto the code base as the semester progresses).
The entire code for the Java class:
package <package_name>;
/*
* This is a custom exception that fits our personal
* needs and won't collide with existing issues.
*/
public class BadRequestException extends Exception {}
One example of how the class is used (still code that was provided by instructor):
private String processHttpRequest(spark.Request httpRequest, spark.Response httpResponse, Type requestType) {
setupResponse(httpResponse);
String jsonString = httpRequest.body();
try {
JSONValidator.validate(jsonString, requestType);
Request requestObj = new Gson().fromJson(jsonString, requestType);
return buildJSONResponse(requestObj);
} catch (IOException | BadRequestException e) { // <---- Here
log.info("Bad Request - {}", e.getMessage()); // <----
httpResponse.status(HTTP_BAD_REQUEST);
} catch (Exception e) {
log.info("Server Error - ", e);
httpResponse.status(HTTP_SERVER_ERROR);
}
return jsonString;
}
What I have so far (practically nothing):
package <package_name>;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
public class TestBadRequestException {
#Test
#DisplayName("Test Empty BadRequestException Class")
public void testBadRequestException() {
}
}
Prior to the start of the semester, I had no experience with JUnit. So, any feedback/references/recommendations are greatly appreciated.
EDIT (Solution):
The first comment on this post provided the solution I was looking for. I had not occurred to me that it would be this simple.
The solution is in the answer below with proper credit.
I think write a unit test for that class is unnecessary.
You can try exclude that on your code coverage rules
Solution credit to #f1sh
f1sh's comment (original solution) recommended to add new BadRequestException() within the JUnit test.
This gave an me idea on how I could hopefully improve upon that recommendation.
My final result:
package <package_name>;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class TestBadRequestException {
#Test
#DisplayName("Test Empty BadRequestException Class")
public void testBadRequestException() {
assertNotNull(new BadRequestException()); // <---- Here
}
}

GWT generator to get compile time

I am trying to understand GWT generators but facing few issues. I am trying to display the compile time in an app using generators and running into this error -
Rebind result 'com.example.client.Function' must be a class
Here is what i have -
This is how i am calling my generated method -
Function b = GWT.create(Function.class);
label.setText(b.getBuildTime());
gwt.xml-
<generate-with class="example.frontend.client.gin.FunctionGenerator">
<when-type-assignable class="com.example.frontend.client.gin.Function" />
</generate-with>
Function.java
package com.example.frontend.client.gin;
public interface Function{
public String getBuildTime();
}
Generator class -
package com.example.frontend.egenerator;
import java.io.PrintWriter;
import java.util.Date;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import com.example.frontend.client.gin.Function;
public class FunctionGenerator extends Generator {
private static final String IMPL_TYPE_NAME = Function.class.getSimpleName() + "Impl";
private static final String IMPL_PACKAGE_NAME = Function.class.getPackage().getName();
#Override
public String generate(final TreeLogger logger, final GeneratorContext context, final String requestedClass) throws UnableToCompleteException {
TypeOracle typeOracle = context.getTypeOracle();
JClassType functionType = typeOracle.findType(requestedClass);
assert Function.class.equals(functionType.getClass());
ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(IMPL_PACKAGE_NAME, IMPL_TYPE_NAME);
composerFactory.addImport(Function.class.getCanonicalName());
composerFactory.addImplementedInterface(Function.class.getName());
PrintWriter printWriter = context.tryCreate(logger, IMPL_PACKAGE_NAME, IMPL_TYPE_NAME);
SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
if(sourceWriter != null) {
sourceWriter.print("public String getBuildTime() {");
sourceWriter.print(" return \"" + new Date() + "\" ;");
sourceWriter.print("}");
sourceWriter.commit(logger);
}
return IMPL_PACKAGE_NAME + "." + IMPL_TYPE_NAME;
}
}
Any ideas, what I am missing?
I believe you also need to null check the PrintWriter created by tryCreate, as it may return null. On the other hand, createSourceWriter will not return null, so no need to null check that.
Your generate-with is also incorrect, at least for the sample that you have here. It should have a different package (according to your FunctionGenerator source at least), com.example.frontend.egenerator, not com.example.frontend.client.gin:
<generate-with class="com.example.frontend.egenerator.FunctionGenerator">
<when-type-assignable class="com.example.frontend.client.gin.Function" />
</generate-with>
In general, your generators should not be in the client package, if for no other reason than preventing spurious errors which slow down the compiler (and really slow down super dev mode).
Beyond that, the full log could help a lot to track down the issue, though without mapping the generator correctly there wouldn't be much of an error. Also be sure to compile with strict turned on when working on generators to ensure that the compiler fails as soon as possible and you can stop at the very first error.
With all of that said, tend to avoid new Generators at this point - they will slow down Super Dev Mode slightly (since they must be re-run every time you refresh), and they will not be supported in future versions of GWT. Annotation Processors (aka APT) are the preferred way to do this, but in your case you might also just be able to generate the class in ant or maven with a plugin.

How to implement a SocketImplFactory using systems default sockets

I have a small problem with implementing a own SocketImplFactory in Java.
My goal is to write a factory which offers me a way to close all open sockets with one simple method call. So I only want to have a kind of "proxy factory" which stores all the created sockets in a list. On this list I could perform all the actions I need.
I tried to implement it like this:
package java.net;
import java.io.IOException;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import com.crosscloud.applicationlayer.logger.CCLogger;
public class CCSocketImplFactory implements SocketImplFactory
{
private List<SocketImpl> _openSockets;
public CCSocketImplFactory()
{
_openSockets = new LinkedList<>();
}
#Override
public SocketImpl createSocketImpl()
{
SocketImpl impl = new SocksSocketImpl();
_openSockets.add(impl);
return impl;
}
public void closeAll()
{
_openSockets.forEach((socket)->
{
try
{
socket.close();
}
catch (Exception e)
{
logException(this, e);
}
});
}
public static CCSocketImplFactory register()
{
CCSocketImplFactory fact = new CCSocketImplFactory();
try
{
Socket.setSocketImplFactory(fact);
}
catch (IOException e)
{
logException(CCSocketImplFactory.class, e);
}
return fact;
}
The problem I have now is that I have to create the class in the package java.net because the class SocksSocketImpl(In my opinion this should be the standard type) is only visible in this package.
When I now want to run the code I get a SecurityException because the package name is probhibited.
Is there a workaround for my problem?
Thank you!
It appears that you are trying to use only one class from java.net There is no need to move you class tot hat package just to create an instance of it. I suggest using reflection instead.
Constructor cons = Class.forName("java.net.SocksSocketImpl").getDeclaredConstructor();
cons.setAccessible(true);
SocketImpl si = (SocketImpl) cons.newInstance();
However using SOCKS by default is likely to be a bad idea as it will change the default not just for your sockets, but all sockets even ones for internal use such as JMX or VisualVM.
What would be an alternative instead of always using SocksSocketImpl?
I also found this example which shows some extended possibilities of this method.
Finding out what network sockets are open in the current Java VM

GXT 3 XTemplate: Custom Formatter - ClassNotFoundException

I am trying to use a custom formatter to turn a boolean into "Yes" or "No" and have run into a roadblock.
My IDE (Eclipse) does not indicate any errors but when I try to compile I receive
[ERROR] Annotation error: cannot resolve foobar.client.formatter.YesNoFormatter - exception: ClassNotFoundException
followed by a few other exceptions that appear to stem from this exception. I understand what a ClassNotFoundException indicates however I cannot figure out why I would be getting it since, as my code shows, the YesNoFormatter class is located in foobar.client.formatter and I can access it through
GWT.log("True: " + YesNoFactory.getFormat().format(Boolean.TRUE);
I am using GXT 3.1.0 and GWT 2.6.1.
Could anybody have an idea of why I am getting this exception? The example given at http://docs.sencha.com/gxt-guides/3/utility/xtemplates/XTemplates.html doesn't mention anything (as far as I can see) about these classes needing to be in specific locations so I am at a loss.
EntryPoint:
package foobar.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.sencha.gxt.core.client.XTemplates.FormatterFactories;
import com.sencha.gxt.core.client.XTemplates.FormatterFactory;
public class TestClass implements EntryPoint {
#FormatterFactories(#FormatterFactory(factory=YesNoFactory.class, name="yesNo"))
public interface Renderer extends XTemplates {
#XTemplate(source="yesNo.html")
SafeHtml render(Boolean b);
}
#Override
public void onModuledLoad() {
GWT.log("True: " + YesNoFactory.getFormat().format(Boolean.TRUE);
Renderer r = GWT.create(Renderer.class);
Window.alert(r.render(true).asString());
}
}
YesNo:
package foobar.client.formatter;
import com.sencha.gxt.core.client.XTemplates.Formatter;
public class YesNo implements Formatter<Boolean> {
#Override
public String format(Boolean data) {
if (data == null) {
return null;
}
return (data) ? "Yes" : "No";
}
}
YesNoFactory:
package foobar.client.formatter;
public class YesNoFactory {
public static YesNo getFormat() {
return new YesNo();
}
}
in foobar
<?xml version="1.0 encoding="UTF-8"?>
<module>
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.sencha.gxt.GXT'/>
<entry-point class='foobar.client.TestClass'/>
<source path='client'/>
</module>
foobar/client/yesNo.html:
{b:yesNo()}
My formatter classes (YesNo and YesNoFactory) apparently have to be in a location that gets compiled prior to compiling the client-side code. After I moved these classes to my 'shared' package - the package that houses code used by the client and server - everything worked.
This was not obvious in the XTemplates portion of the guide at http://docs.sencha.com/gxt-guides/3/utility/xtemplates/XTemplates.html which does not seem to specify where the files used for custom formatters need to be located. Maybe that should have been obvious but not to me.

Overriding service-definition.xml of one of Webcenter libraries in ADF application

Here in webcenter-driven ADF application we have a standard library called generic-site-resources-model.jar which contains file META-INF/service-definition.xml, which i wish to alter at one line, to add view resource' security permission, as in:
## -1189,7 +1189,7 ##
<resource-permission>
<resource-permission-impl>oracle.webcenter.security.auth.WebCenterResourcePermission</resource-permission-impl>
<resource-permission-target-id>resource_oracle_webcenter_siteresource_#scope#_navigation_#resource#</resource-permission-target-id>
- <resource-permission-action-list>manage,update</resource-permission-action-list>
+ <resource-permission-action-list>view,manage,update</resource-permission-action-list>
</resource-permission>
</permission-metadata>
</security-definition>
How this is can be possibly done without alterning weblogic domain containing this library itself, somehow configuring our application? Maybe some way to override the whole generic-site-resources-model.jar with application-shipped clone? Or (ideally) some way to replace the targeted resource permission? Or some custom way of taking control over resource loading in application?
It is possible to implement appending custom actions to specific resource type using initialization phase listener and a little bit code, without any overriding at all.
Here is how:
ViewControllerProject/src/META-INF/adf-settings.xml
<?xml version="1.0" encoding="UTF-8" ?>
<adf-settings xmlns="http://xmlns.oracle.com/adf/settings">
<adfc-controller-config xmlns="http://xmlns.oracle.com/adf/controller/config">
<lifecycle>
<phase-listener>
<listener-id>PortalInitializer</listener-id>
<class>com.otr.portal.initializer.PortalInitializer</class>
</phase-listener>
</lifecycle>
</adfc-controller-config>
</adf-settings>
com.otr.portal.initializer.PortalInitializer
package com.otr.portal.initializer;
import oracle.adf.controller.v2.lifecycle.Lifecycle;
import oracle.adf.controller.v2.lifecycle.PagePhaseEvent;
import oracle.adf.controller.v2.lifecycle.PagePhaseListener;
import oracle.webcenter.security.internal.common.SecurityUtil;
import oracle.webcenter.security.model.exception.SecExtensionNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PortalInitializer implements PagePhaseListener {
private static final Log log = LogFactory.getLog(PortalInitializer.class);
private boolean firstCall = true;
#Override
public void afterPhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.INIT_CONTEXT_ID) {
if (firstCall) {
setupViewNavigationResourcePermssion();
firstCall = false;
}
}
}
private void setupViewNavigationResourcePermssion() {
try {
SecurityUtil.getSecurityExtension("oracle.webcenter.siteresources.navigation").getExtensionPermMetadata().getResourcePermMetadata().getResourcePermActionsList().add("view");
} catch (SecExtensionNotFoundException e) {
log.error("Error adding view resource permission to navigation resource type", e);
}
}
#Override
public void beforePhase(PagePhaseEvent pagePhaseEvent) {
}
}

Categories

Resources