CommonsXsdSchemaCollection xsd into a Jar/War - Spring Boot WS - java

Good morning and happy new year.
I can not get files inside a WAR file, running in IBM Websphere, once it is compiled, the files are the path in \WEB-INF\classes\Schemas but I do not know how to get them from Java, in the project it works correctly (like this in the example, inside of resources)
#Bean
public XsdSchemaCollection consultarCollectorXsd() throws Exception {
CommonsXsdSchemaCollection xsds = new CommonsXsdSchemaCollection(
new ClassPathResource("/Schemas/Bancogalicia/Methods/ListarEstadosMensajeRequest-1.0.0.xsd"),
new ClassPathResource("/Schemas/Bancogalicia/Methods/ListarEstadosMensajeResponse-1.0.0.xsd"),
new ClassPathResource("/Schemas/Bancogalicia/Methods/ListarMensajesRequest-1.0.0.xsd"),
new ClassPathResource("/Schemas/Bancogalicia/Methods/ListarMensajesResponse-1.0.0.xsd"),
new ClassPathResource("/Schemas/Bancogalicia/Methods/ObtenerUltimoEstadoMensajeRequest-1.0.0.xsd"),
new ClassPathResource("/Schemas/Bancogalicia/Methods/ObtenerUltimoEstadoMensajeResponse-1.0.0.xsd")
);
xsds.setInline(true);
return xsds;
}

Related

How can I use Maven Artifact Resolver to list transitive dependencies?

I am working on an application for my company which needs to resolve dependencies for a maven project. This is a standalone application, not a maven plugin. The only thing I am trying to do at the moment is print the resolved dependencies to confirm that they were found. I am using Apache Maven Model (v4.0.0-alpha-2), Apache Maven Artifact Resolver (v1.8.2), and Maven Artifact Resolver Implementation (v1.8.2) to support my endeavor.
The initial setup is really what's nerfing me. I haven't had any luck finding update-to-date examples or documentation. This is the code I drafted up:
public static void main(String[] args)
throws LoadException, IOException, XmlPullParserException, DependencyResolutionException {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(new FileReader(new File("C:\\Users\\lc70844\\eclipse-workspace\\test\\pom.xml")));
DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();
DefaultRepositorySystem repositorySystem = new DefaultRepositorySystem();
for (Dependency dependency : model.getDependencies()) {
DependencyRequest request = new DependencyRequest();
request.setRoot(new DefaultDependencyNode(
new org.eclipse.aether.graph.Dependency(toArtifact(dependency), dependency.getScope())));
DependencyResult result = repositorySystem.resolveDependencies(session, request);
result.getArtifactResults().stream().map(a -> a.getArtifact())
.map(a -> a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getVersion()).forEach(System.out::println);
}
}
It is throwing an exception saying "repository system session's local repository manager cannot be null." This is pretty self-explanatory; we all know what I need to do. However, DefaultRepositorySystemSession#setLocalRepositoryManager(LocalRepositoryManager) requires a LocalRepositoryManager parameter, which is what I am having trouble figuring out how to setup. The repository I want to use is the the local repo at: %userprofile%/.m2/repository.
I found a few similar questions pertaining to my issue, but they seem to have the wrong context or are using deprecated libraries to achieve their end. I am hoping for a reliable, up-to-date solution.
Hopefully I am least heading in the right direction. What more do I need to do to get my list of dependencies?

Can I store an XML file inside a jar file?

I built an Jar using Maven.
The behavior I am trying to implement is: when the user uses the command create , I want to store an XML file inside a a folder of the jar. Is it possible to do it?
Let's say this is a project and I added the jar of the migration tool to it.
I want to be able to see and edit the properties file
3-It has some things that need to be altered like for example
migration files and the file with the database information
Not 100% sure if I understood your requirements correctly, but I've implemented some utility classes which support:
default config in JAR
config in installation directory
config in user directory
simple command line arguments/ switches support
and more...
Maybe this helps.
public static void main(String[] args) throws URISyntaxException, IOException, MissingPropertyException, Exception {
CommandLineArgs commandLineArgs = CommandLineArgs.parseCommandLineArgs(args);
DromblerClientStarter<DromblerClientConfiguration> main = new DromblerClientStarter<DromblerClientConfiguration>(new DromblerClientConfiguration(commandLineArgs)) {
#Override
protected ApplicationInstanceListener getApplicationInstanceListener() {
return additionalArgs -> {
// additionalArgs not handled
};
}
};
if (main.init()) {
main.start();
}
}
Source code: https://github.com/Drombler/drombler-commons/tree/master/drombler-commons-client/drombler-commons-client-startup-main
Maven:
<dependency>
<groupId>org.drombler.commons</groupId>
<artifactId>drombler-commons-client-startup-main</artifactId>
<version>1.0</version>
</dependency>
Javadoc: https://www.drombler.org/drombler-commons/1.0/docs/site/apidocs/org/drombler/commons/client/startup/main/package-summary.html

JavaFx MediaPlayer behaves differently in unit test vs application, why?

I want to load meta data from an MP3 file, to be played by a JavaFx MediaPlayer. This works fine in the unit test, but not in the application. In the unit test, 6 items of metaData reported, but zero in the application. The method that "does the work" is the same.
The main class of the application extends Application. The test class extends ApplicationTest from TestFx. Could that affect the behavior?
The application:
public class MediaMain extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Map<String, Object> meta = metaData();
System.out.printf("Number of meta data: %d.%n", meta.size());
System.out.println(meta);
}
Map<String, Object> metaData() {
File audioFile = new File("src/main/resources", "beingBoiled.mp3");
final URI uri = audioFile.toURI();
final String source = uri.toString();
Media media = new Media(source);
new MediaPlayer(media);
return media.getMetadata();
}
}
The unit test:
class MediaMainTest extends ApplicationTest {
#Test
void testMeta() {
MediaMain main = new MediaMain();
Map<String, Object> metaData = main.metaData();
assertNotEquals(0, metaData.size());
System.out.printf("Number of meta data: %d.%n", metaData.size());
System.out.println(metaData);
}
}
Printout from the application:
Number of meta data: 0.
{}
Printout from the unit test:
Number of meta data: 6.
{year=1980, artist=The Human League, raw metadata={ID3=java.nio.HeapByteBufferR[pos=254 lim=3214 cap=3214]}, album=Travelogue, genre=(52), title=Being Boiled}
What could be the reason? It's a mystery to me. Written with Java 11, JavaFx 11.0.2 and TestFx 4.0.15-alpha.
You are referencing a file with a location of src/main/resources, this is probably not a good idea as your deployed application likely won't have a src/main/resources directory, plus the resource might be bundled within the application jar rather than as a file on disk, so using a file protocol to access it won't work.
It is probably best to use something like below:
String mediaLoc = getClass().getResource("/beingBoiled.mp3").toExternalForm()
Media media = new Media(mediaLoc)
Like in How load css file in javafx8. The exact location of the resource to be loaded may differ based on build and project structure. If you don't want to load from the class path, but instead via a File or over network http call, then you would need to use something else.
The above code assumes that your build system is setup to copy the media from the src/main/resources to your target packaging location and package the resource into the application distributable (e.g. an application jar file) in the root of the jar file.
Make sure that your build system is actually copying the file to the target location. You can check if it is there by running your build, looking at the resultant jar and running jar tvf <myjarfilename>.jar to see if the mp3 resource is in the correct location at the root of the jar file.

Spark can't load static files from webjars

I am using Spark Framework in my application, and use
staticFileLocation("/META-INF/resources/");
so that I can use webjars, which contain css and js files in there. I also have my own resources put in my projects src/main/resources/META-INF/resources folder because my gradle build picks them up from there.
My build uses a fat-jar approach, where everything ends up in a single jar and all files are served perfectly by Spark.
My problem is that when I run some unit tests standalone from Eclipse, even though I ensured that the webjars are on classpath, they are not served by Spark, only my own project static resources are.
#Test
public void testStartup() throws InterruptedException {
InputStream schemaIS = this.getClass().getClassLoader().getResourceAsStream("META-INF/resources/webjars/bootstrap/3.2.0/js/bootstrap.min.js");
System.out.println(schemaIS == null);
staticFileLocation("/META-INF/resources/");
// depending on the trailing / the bootstrap js is found, but Spark never serves it
}
I think this has something to do with classloaders, but I am not finding the way to make this work. Looking at Spark code, it says The thread context class loader will be used for loading the resource. I also see that the code itself removes the trailing slash, which makes big difference in the plain getResourceAsStream.
Is it a bug in Spark, or is there any way to make it work properly?
Note that removing the leading slash is required by jetty not by Spark.
Unfortunately with Spark you cannot mix static files (in a physical directory/folder) with files served as resources in a jar. And many jars will not work either in Spark.
I had a look at this a few weeks ago and came to a conclusion this is a minor weakness in Spark (or a bug if you may say).
The only way I found out was to reverse Spark and figure out how jetty works. I managed with the following Nashorn javascript snippets to make webjars and static files to work together.
Unless Spark author changes his code to allow inclusion of tailor made context handlers, this will not help you out. But if you wish to pursue in jetty instead, this code with adaptation can help you out.
This code is for Nashorn jjs (from JDK8) but can be easily ported to Java. With this code I was able to use 3 separate webjars jquery/bootstrap/angular and the rest of my client code was in a physical directory/folder public.
app.js:
with(new JavaImporter(
org.eclipse.jetty.server
, org.eclipse.jetty.server.handler
)) {
var server = new Server(4567);
var ctxs = new ContextHandlerCollection();
ctxs.setHandlers(Java.to([
load('src/static.js')
, load('src/webjars.js')
], Handler.class.getName().concat('[]')));
server.setHandler(ctxs);
server.start();
server.join();
}
src/static.js:
(function () {
var context;
with(new JavaImporter(
org.eclipse.jetty.server.handler
, org.eclipse.jetty.util.resource
)) {
context = new ContextHandler();
context.setContextPath("/");
var handler = new ResourceHandler();
handler.setBaseResource(Resource.newResource("public"));
context.setHandler(handler);
}
return context;
})();
src/webjars.js:
(function () {
var context;
with(new JavaImporter(
org.eclipse.jetty.server.handler
, org.eclipse.jetty.util.resource
)) {
context = new ContextHandler();
context.setContextPath("/");
var handler = new (Java.extend(ResourceHandler, {
getResource: function(req) {
var path = req.getUri();
var resource = Resource.newClassPathResource(path);
if (resource == null || !resource.exists()) {
resource = Resource.newClassPathResource("META-INF/resources/webjars" + path);
}
return resource;
}
}))();
handler.setDirectoriesListed(true); // true when debugging, false in production
context.setHandler(handler);
}
return context;
})();

Arquillian: path relative to project instead of server

How can I use a project-relative path when using Arquillian/Shrinkwrap to test my testcases?
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File("src\\ZZZZZ.xml"));
insertFromXML(dataSet);
Will give me this exception when testing
java.io.FileNotFoundException: C:\Uprogs\jboss-eap-6.2.4\bin\src\ZZZZZ.xml
It tries to locate the file within the folders of the server on which I deploy the test onto.
Rather than that, I want him to look in the folders relative to my project (e.g. C:\Users\xy\workspaces\MyProject\src\ZZZZZ.xml). Searched the internet but found nothing
Shrinkwrap gets deployed like this:
#Deployment
public static Archive<?> createDeployment() {
File[] libs = Maven.resolver()
.loadPomFromFile("pom.xml").resolve(
"jcifs:jcifs"
, "org.dbunit:dbunit"
, "com.ibm:db2jcc_license_cisuz"
, "com.ibm:db2jcc"
)
.withTransitivity()
.asFile();
return ShrinkWrap.create(WebArchive.class, "test.war")
.addAsLibraries(libs)
.addPackage("de.abc.RuleEditor")
.addAsResource("de/abc/RuleEditor/messages.properties", "messages.properties")
.addAsManifestResource("test-jboss-deployment-structure.xml","jboss-deployment-structure.xml")
.addAsWebInfResource("test-beans.xml", "beans.xml")
.addAsWebInfResource(
new StringAsset("<faces-config version=\"2.0\"/>"), "faces-config.xml")
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory("src/main/webapp").as(GenericArchive.class), "/", Filters.include(".*\\.xhtml$"));
}
How can I use a project-relative path when using Arquillian/Shrinkwrap (...)?
It's a ridiculous approach, don't go that way :]
The idea behind Arquillian is to create micro-deployments (it means: jar/war/ear archive using ShrinkWrap tool) and include everything inside that archive.
So please modify your deployment:
#Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
(...)
.addAsLibraries(libs)
// Add in below way any additional file to the archive
.addAsResource("path-to-testset.xml", "dbunit/testset.xml")
.addPackage("de.abc.RuleEditor")
.addAsResource("de/abc/RuleEditor/messages.properties", "messages.properties")
.addAsManifestResource("test-jboss-deployment-structure.xml","jboss-deployment-structure.xml")
(...)
}
And then use getResourceAsStream() to load file from the class path:
#Test
public void test_something() {
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
builder.setColumnSensing(true);
FlatXmlDataSet xmlDataSet = builder.build(
this.getClass().getResourceAsStream("/dbunit/testset.xml"));
// ...
It is much better, as everything what is needed to test, is already included inside archive. No relative, nor absolute path names.
My personal advice is: be careful about DbUnit, as perhaps you notice in the future, crafting and managing many xml data sets may become bigger and bigger problem as your project will grow. That is why I prefer DbSetup.

Categories

Resources