How to get entire classpath of the modules added to wildfly server - jboss

I have tried below snippet
String path = System.getProperty("java.class.path");
I get
../wildfly-8.2.0.Final/jboss-modules.jar
String modulepath = System.getProperty("jboss.module.path");
// ../wildfly-8.2.0.Final/jboss-modules.jar
and not the ones which i have added in modules
when i try
StringBuffer buffer = new StringBuffer();
for (URL url :
((URLClassLoader) (Thread.currentThread()
.getContextClassLoader())).getURLs()) {
buffer.append(new File(url.getPath()));
buffer.append(System.getProperty("path.separator"));
}
Getting :
java.lang.ClassCastException: org.jboss.modules.ModuleClassLoader cannot be cast to java.net.URLClassLoader

Use getResourceAsStream on your application class path which is using the same class loader as your app.

Related

How to create a builtin file and folder in custom eclipse plugin

I am developing an Eclipse plugin which need to be shipped with builtin ant build file. Its working when I am running the project. However, when I am exporting the plugin and deploying the exported plugin in another eclipse, the ant build file is not getting generated. My suspect is that in the runtime, the source of the ant build file is not accessed. Any pointer how to solve the issue? Here is the code :
private void createAntFile(IProject project, Properties properties) throws CoreException, IOException {
InputStream antFileInputStream =null;
try {
String antFileName = properties.getProperty("name.ant.file");
String antFilePath = properties.getProperty("path.ant.file");
IFile file = project.getFile(antFileName);
antFileInputStream = Activator.getDefault().getBundle().getEntry(antFilePath).openStream();
file.create(antFileInputStream, false, null);
antFileInputStream.close();
}finally{
if(antFileInputStream!=null){
try {
antFileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
name.ant.file=build.xml
path.ant.file=src/weblogic/ant/build.xml
The source build file I am hard coding in the path src/weblogic/ant/build.xml
Edit:
Here is the code to create builtin folders:
private void createWeblogicTemplate(IProject project, Properties properties) throws IOException, CoreException {
String weblogicTemplateSourcePath = properties.getProperty("path.weblogic.template.source");
Path path = new Path(weblogicTemplateSourcePath);
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileURL = FileLocator.find(bundle, path, null);
String filePath = FileLocator.resolve(fileURL).getPath();
System.out.println(filePath);
File sourceFile = new File(filePath);
String weblogicTemplateTargetPath = properties.getProperty("path.weblogic.template.target");
IFolder folder = project.getFolder(weblogicTemplateTargetPath);
copyFolder(sourceFile,folder,project,properties);
}
The line System.out.println(filePath) is printing path as
/C:/Users//Desktop/eclipse-rcp-luna-SR2-win32-x86_64/eclipse/../../../workspace-plugin/weblogic/resources/weblogictemplate/
So, locally its working. However, its not working when I deploy the pluin in some other eclipse. Any pointer how to create builtin folders?
You appear to be expecting the src/weblogic/ant/ directory to be included in the exported plugin jar - the src directory is not normally included in the plugin jar.
Put resources you want to include in the plugin in a separate directory (such as resources) and include that directory in the plugin build.properties so that it is included in the exported plugin jar.

Plug-In that Converted Note entity pre-existing attachment XML file into new .MMP file

strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.

Exception when initializing new PlatformClient()

I am using the jar provided by intuit (ipp-java-devkit-2.0.11-jar-with-dependencies.jar) and having some difficulty. I am able to create my PlatformSessionContext so I know that it is not completely broken. When calling new PlatformClient() I get the following exception:
16:29:58,204 ERROR [[requestHandlerBlueDot]] Servlet.service() for servlet requestHandlerBlueDot threw exception java.lang.IllegalStateException: org.slf4j.LoggerFactory could not be successfully initialized. See also http://www.slf4j.org/codes.html#unsuccessfulInit
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:288)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252)
at com.intuit.platform.util.LoggerImpl.getLogger(LoggerImpl.java:48)
at com.intuit.platform.util.LoggerImpl.getInstance(LoggerImpl.java:32)
at com.intuit.platform.client.PlatformClient.<clinit>(PlatformClient.java:52)
at com.jt.quickbooks.BlueDotMenuServlet.doGet(BlueDotMenuServlet.java:66)
Is there something that I missed?
Figured it out. Issue was that the slf4j logging jars were newer versions and incompatible with what I already have running on my server. Found a (jBoss) deployment error that I didn't notice before:
16:27:26,172 ERROR [STDERR] SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
16:27:26,173 ERROR [STDERR] SLF4J: Your binding is version 1.5.5 or earlier.
16:27:26,173 ERROR [STDERR] SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x
Fix was to remove ipp-java-devkit-2.0.11-jar-with-dependencies.jar and replace with ipp-java-devkit-2.0.11.jar then add a couple jars for the missing dependencies.
The jars I needed to add were:
org.apache.felix.bundlerepository-1.0.3.jar for xmlpull.v1.xmlpullparser, xmlpull.v1.xmlserializer, kdom.Document
signpost-core-1.2.1.1.jar for OAuth stuff
Please check if your menuproxy url is correct. That can create this issue.
Reference:
https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started/0020_connect/0010_from_within_your_app/add_the_connect_button
It is working fine for me. Can you please try the following.
final PlatformSessionContext context = getPlatformContext(accesstoken,
accessstokensecret, realmID, dataSource);
PlatformClient client = new PlatformClient();
System.out.println("User's email " + client.getUserInfo(context).getEmail());
JavaDoc Ref - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
(com.intuit.platform.client.PlatformClient)
Please let me know if it works for you.
import com.intuit.platform.client.PlatformClient;
import com.intuit.platform.client.PlatformServiceType;
import com.intuit.platform.client.PlatformSessionContext;
import com.intuit.platform.client.security.OAuthCredentials;
public class Test {
String accesstoken = "keys ****";
String accessstokensecret = "keys ****";
String realmID = "*********";
String dataSource = "QBD";
String appToken = "keys ****";
String oauth_consumer_key = "keys ****";
String oauth_consumer_secret = "keys ****";
Test(){
final PlatformSessionContext context = getPlatformContext(accesstoken,
accessstokensecret, realmID, dataSource);
System.out.println(context);
PlatformClient client = new PlatformClient();
System.out.println("User's email " + client.getUserInfo(context).getEmail());
}
public PlatformSessionContext getPlatformContext(final String accessToken,
final String accessTokenSecret, final String realmID,
final String dataSource) {
PlatformServiceType serviceType;
if (dataSource.equalsIgnoreCase("QBO")) {
serviceType = PlatformServiceType.QBO;
} else {
serviceType = PlatformServiceType.QBD;
}
final OAuthCredentials oauthcredentials = new OAuthCredentials(
oauth_consumer_key, oauth_consumer_secret,
accessToken, accessTokenSecret);
final PlatformSessionContext context = new PlatformSessionContext(
oauthcredentials, appToken, serviceType, realmID);
return context;
}
public static void main(String args[]){
Test test = new Test();
}
}
Thanks

Serving static /public/ file from Play 2 Scala controller

What is the preferred method to serve a static file from a Play Framework 2 Scala controller?
The file is bundled with my application, so it's not possible to hardcode a filesystem absolute /path/to/the/file, because its location depends on where the Play app happens to be installeld.
The file is placed in the public/ dir, but not in app/assets/, because I don't want Play to compile it.
(The reason I don't simply add a route to that file, is that one needs to login before accessing that file, otherwise it's of no use.)
Here is what I've done so far, but this breaks on my production server.
object Application ...
def viewAdminPage = Action ... {
... authorization ...
val adminPageFile = Play.getFile("/public/admin/index.html")
Ok.sendFile(adminPageFile, inline = true)
}
And in my routes file, I have this line:
GET /-/admin/ controllers.Application.viewAdminPage
The problem is that on my production server, this error happens:
FileNotFoundException: app1/public/admin/index.html
Is there some other method, rather than Play.getFile and OK.sendFile, to specify which file to serve? That never breaks in production?
(My app is installed in /some-dir/app1/ and I start it from /some-dir/ (without app1/) — perhaps everything would work if I instead started the app from /some-dir/app1/. But I'd like to know how one "should" do, to serve a static file from inside a controller? So that everything always works also on the production servers, regardless of from where I happen to start the application)
Check Streaming HTTP responses doc
def index = Action {
Ok.sendFile(
content = new java.io.File("/tmp/fileToServe.pdf"),
fileName = _ => "termsOfService.pdf"
)
}
You can add some random string to the fileName (individual for each logged user) to avoid sharing download link between authenticated and non-authinticated users and also make advanced download stats.
I did this: (but see the Update below!)
val fileUrl: java.net.URL = this.getClass().getResource("/public/admin/file.html")
val file = new java.io.File(adminPageUrl.toURI())
Ok.sendFile(file, inline = true)
(this is the controller, which is (and must be) located in the same package as the file that's being served.)
Here is a related question: open resource with relative path in java
Update
Accessing the file via an URI causes an error: IllegalArgumentException: URI is not hierarchical, if the file is then located inside a JAR, which is the case if you run Play like so: play stage and then target/start.
So instead I read the file as a stream, converted it to a String, and sent that string as HTML:
val adminPageFileString: String = {
// In prod builds, the file is embedded in a JAR, and accessing it via
// an URI causes an IllegalArgumentException: "URI is not hierarchical".
// So use a stream instead.
val adminPageStream: java.io.InputStream =
this.getClass().getResourceAsStream("/public/admin/index.html")
io.Source.fromInputStream(adminPageStream).mkString("")
}
...
return Ok(adminPageFileString) as HTML
Play has a built-in method for this:
Ok.sendResource("public/admin/file.html", classLoader)
You can obtain a classloader from an injected Environment with environment.classLoader or from this.getClass.getClassLoader.
The manual approach for this is the following:
val url = Play.resource(file)
url.map { url =>
val stream = url.openStream()
val length = stream.available
val resourceData = Enumerator.fromStream(stream)
val headers = Map(
CONTENT_LENGTH -> length.toString,
CONTENT_TYPE -> MimeTypes.forFileName(file).getOrElse(BINARY),
CONTENT_DISPOSITION -> s"""attachment; filename="$name"""")
SimpleResult(
header = ResponseHeader(OK, headers),
body = resourceData)
The equivalent using the assets controller is this:
val name = "someName.ext"
val response = Assets.at("/public", name)(request)
response
.withHeaders(CONTENT_DISPOSITION -> s"""attachment; filename="$name"""")
Another variant, without using a String, but by streaming the file content:
def myStaticRessource() = Action { implicit request =>
val contentStream = this.getClass.getResourceAsStream("/public/content.html")
Ok.chunked(Enumerator.fromStream(contentStream)).as(HTML)
}

Apache FOP: How to set base URL for accessing external resource using relative path

In my .xsl file I am using external graphics like this
<fo:external-graphic width="90pt" height="29pt" src="url(xsl/logo.jpg)"/>
But image is not getting loaded in the generated PDF and I get this error in console.
[ERROR] Error while creating area : Error with image URL: xsl\logo.jpg (The system cannotfind the path specified) and no base URL is specified
How do I solve this issue? I guess setting the base URL will do. But how to set the base URL? Please help.
I got a solution from this link
http://groups.yahoo.com/group/XSL-FO/message/6116
set base dir using Java code
ServletContext servletContext = getServletConfig().getServletContext();
String appPath = servletContext.getRealPath(""); //root of web app
org.apache.fop.configuration.Configuration.put("baseDir",appPath);
This worked for me.
Please post if you know any better solution.
I am using Apache FOP 1.1 Ver.
fopFactory = FopFactory.newInstance();
// for image base URL : images from Resource path of project
String serverPath = request.getSession().getServletContext().getRealPath("/");
fopFactory.setBaseURL(serverPath);
// for fonts base URL : .ttf from Resource path of project
fopFactory.getFontManager().setFontBaseURL(serverPath);
I added all images and required font font files in resource director of my project.
It is working fine for me.
Thank you
I had the same problem and this only works for me in the version 0.95 of fop.
SetBaseUrl is ignored in version 1.0
Solution for versions 1.0, 1.1 :
In fop 1.0 and 1.1 method setBaseURL() does not work correctly with local files, so you can use method setURIResolveri and write your implementation of interface URIResolver.
1.Add in uses
import javax.xml.transform.URIResolver;
2.Add in mainClass
private static class LocalResolver implements URIResolver {
private String BaseFolder;
#Override
public Source resolve(String href, String base) throws TransformerException {
File f = new File(BaseFolder + "\\" + href);
if (f.exists())
return new StreamSource(f);
else
throw new TransformerException("File " + f.getAbsolutePath() +" not found!");
}
public LocalResolver(String BaseFolder) {
this.BaseFolder = BaseFolder;
}
}
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
3.Add before call transformer.transform(src, res) this:
fop.getUserAgent().setURIResolver(new LocalResolver("C:\\Users\\photon\\Downloads\\fop-1.1-bin\\fop-1.1"));