Arquillian ShrinkWrap how to add an asset to the file system path - jboss-arquillian

I am importing a library that reads from the file system instead of my web archive's resource folder. I want to be able to essentially mock that file by adding an asset with that path using ShrinkWrap, so I can run tests on my build server without guaranteeing the file system has all these files. I tried to add a String Asset in the appropriate path, but the code can't find that asset. Here's an example of what I'm trying to achieve.
Rest Resource
#Path("/hello-world")
public class HelloWorldResource {
#GET
public Response getHelloWorld(){
return Response.ok(getFileContent()).build();
}
private String getFileContent() {
StringBuilder builder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(
"/usr/myFile.txt"));
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line);
line = bufferedReader.readLine();
}
}
catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
}
Test
#RunWith(Arquillian.class)
public class HelloWorldResourceTest {
#Deployment
public static WebArchive createDeployment()
{
WebArchive webArchive = ShrinkWrap
.create(WebArchive.class)
.addPackages(true,
HelloWorldApplication.class.getPackage(),
HelloWorldResource.class.getPackage(),
Hello.class.getPackage())
.add(new StringAsset("Blah"),"/usr/myFile.txt")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
System.out.println("WebArchive: " + webArchive.toString(true));
return webArchive;
}
#Test
#RunAsClient
public void testHello(
#ArquillianResteasyResource("hello-world") final WebTarget webTarget)
{
final Response response = webTarget
.request(MediaType.APPLICATION_JSON)
.get();
String hello = response.readEntity(String.class);
System.err.println("Hello: " + hello);
Assert.assertEquals("Status is not OK", response.getStatus(), 200);
}
}
Web Archive toString
/WEB-INF/
/WEB-INF/classes/
/WEB-INF/classes/com/
/WEB-INF/classes/com/
/WEB-INF/classes/com/
/WEB-INF/classes/com/helloworld/
/WEB-INF/classes/com/helloworld/application/
/WEB-INF/classes/com/helloworld/application/HelloWorldApplication.class
/WEB-INF/classes/com/helloworld/resource/
/WEB-INF/classes/com/helloworld/resource/HelloWorldResourceTest.class
/WEB-INF/classes/com/helloworld/resource/HelloWorldResource.class
/WEB-INF/classes/com/helloworld/dataobjects/
/WEB-INF/classes/com/helloworld/dataobjects/Hello.class
/WEB-INF/beans.xml
/usr/
/usr/myFile.txt
I get the following error:
java.io.FileNotFoundException: /usr/myFile.txt (No such file or
directory)
Seems like ShrinkWrap is adding /usr/myFile.txt as a relative path within the archive instead of making it seem like /usr/myFile.txt is at the root directory of my file system. Is there any way I can get ShrinkWrap to do what I want?

Shrinkwrap is intended to create archives, so the API is scoped to create assets within the archive you are creating. If you want to have resources created in the regular filesystem simply use JDK, there is nothing Shrinkwrap could help you with.
Alternatively, if possible, change your resource to read resources from the classpath, not filesystem path. With this approach, you can easily swap content for the test using Shrinkwrap as you are trying now with your example.

Related

How to write/serialize lucene's ByteBuffersDirectory to disk?

How one would write a Lucene 8.11 ByteBuffersDirectory to disk?
something similar to Lucene 2.9.4 Directory.copy(directory, FSDirectory.open(indexPath), true)
You can use the copyFrom method to do this.
For example:
You are using a ByteBuffersDirectory:
final Directory dir = new ByteBuffersDirectory();
Assuming you are not concurrently writing any new data to that dir, you can declare a target where you want to write the data - for example, a FSDirectory (a file system directory):
Directory to = FSDirectory.open(Paths.get(OUT_DIR_PATH));
Use whatever string you want for the OUT_DIR_PATH location.
Then you can iterate over all the files in the original dir object, writing them to this new to location:
IOContext ctx = new IOContext();
for (String file : dir.listAll()) {
System.out.println(file); // just for testing
to.copyFrom(dir, file, file, ctx);
}
This will create the new OUT_DIR_PATH dir and populate it with files, such as:
_0.cfe
_0.cfs
_0.si
segments_1
... or whatever files you happen to have in your dir.
Caveat:
I have only used this with a default IOContext object. There are other constructors for the context - not sure what they do. I assume they give you more control over how the write is performed.
Meanwhile I figured it out by myself and created a straight forward method for it:
#SneakyThrows
public static void copyIndex(ByteBuffersDirectory ramDirectory, Path destination) {
FSDirectory fsDirectory = FSDirectory.open(destination);
Arrays.stream(ramDirectory.listAll())
.forEach(fileName -> {
try {
// IOContext is null because in fact is not used (at least for the moment)
fsDirectory.copyFrom(ramDirectory, fileName, fileName, null);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
});
}

jbehave run only specific story

I have jbehave integrated with Selenium. I am running my tests through command line as below
C:\eclipse_workspace\MySeleniumTests>mvn clean test -Dwebdriver.firefox.bin="C:\Program Files\Mozilla\Firefox\firefox.exe"
I have used jbehave-maven-plugin. Maven picks up all the Embedder impl (JunitStories in my case) from the source directory and execute them one by one. Configuration for that is <include>**/*Stories.java</include> in pom.xml
It then looks for relevant .story files in the specified dir and executes them. Say, I have two story files one.story and two.story, both of them are executed.
Over a time, number of story files are going to increase I only want to execute specific story files should there be a way to do this? I am thinking to pass specific story file names as run time parameters but don’t know what is required to make that happen.
I got it working with the below code
mvn clean test -Dwebdriver.firefox.bin="C:\Program Files\Mozilla\Firefox\firefox.exe" -Dstory=myStory.story
Override storyPaths() method in embedder class as below.
public class MyTestStories extends JUnitStories /* InjectableEmbedder */{
#Override
protected List<String> storyPaths() {
List<String> storiesToRun = new ArrayList<String>();
String storyProperty = System.getProperty("story");
if (storyProperty == null || storyProperty.isEmpty()) {
throw new RuntimeException("Please specify which stories to run");
}
String[] storyNames = storyProperty.split(",");
StoryFinder sf = new StoryFinder();
URL baseUrl = CodeLocations.codeLocationFromClass(this.getClass());
for (String storyName : storyNames) {
storiesToRun.addAll(sf.findPaths(baseUrl, storyName, ""));
}
return storiesToRun;
}
Try the following:
mvn clean test -Dwebdriver.firefox.bin="C:\Program Files\Mozilla\Firefox\firefox.exe" -Djbehave.story.name=<story filename without extension (wildcards are supported)>
You should also use custom test suite implementation:
public abstract class JBehaveTestSuite extends ThucydidesJUnitStories {
private static final String STORY_NAME_PATTERN = "**/${jbehave.story.name:*}.story";
public JBehaveTestSuite() {
findStoriesCalled(storyNamesFromEnvironmentVariable());
}
#Override
public void run() throws Throwable {
super.run();
}
private String storyNamesFromEnvironmentVariable() {
return SystemPropertyUtils.resolvePlaceholders(STORY_NAME_PATTERN);
}
}

Different project settings for user Intellij Idea

How can I do different project settings for users in the same project. I have a project with some .properties file like email.properties which contains user-specific settings.I need something like user-specific enviroment settings, something like this: email..properties, and variable contains in OS enviroment or, maybe, in project file
Here's how I've done this in some projects. I create a System Property to the path of the property file. The path is outside of the project so the properties file is never committed. But to help others who are running the project for the first time, I commit a template properties file with default options.
In intellij, I start the project with a different -D option than my coworkers do and the startup options don't get committed (because we don't commit the .idea folder).
As a result a do the same: at first I created properties folder in propject root, add there file env.properties which contains current environment name (or user can add it as JVM start paramenter -Denv=<env name>. I add static class and method Properties getProperty(String fileName) which receive property file name as parameter and return all records in file as java.util.Properties.
public static Properties loadProperties(String fileName)
{
Properties properties = null;
if (propertiesMap.containsKey(fileName)) {
properties = (Properties)properties.get(fileName);
} else {
String environment = getEnvironment();
try {
properties = (new PropertiesLoaderImpl()).LoadAllPropertiesForUtilAndEnv(environment, fileName);
} catch (FileNotFoundException exception) {}
}
return properties;
}
private static String getEnvironment() {
// Проверка на наличие параметра при запуске java-машины
String environment = System.getProperty("env");
if (environment == null) {
try {
// Попытка найти файл env.properties
ResourceBundle bundle = ResourceBundle.getBundle("properties/env");
environment = bundle.getString("env");
} catch (MissingResourceException exception) {
environment = "";
}
}
return environment;
}
Property search implements that way:
1. look in ..proeprties;
2. if there is no suitable property, then look in .property;
3. else return empy.

context path for file upload without HttpRequest in REST application

I am building REST application. I want to upload a file and I want to save it for example in /WEB-INF/resource/uploads
How can I get path to this directory ? My Controller looks like this
#RequestMapping(value = "/admin/house/update", method = RequestMethod.POST)
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
try {
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
fileName = "D:/" + file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch(Exception ex) {
ex.printStackTrace();
}
model.addAttribute("step", 3);
this.houseDao.update(house);
return "houseAdmin";
}
Second question...what is the best place to upload user files ?
/WEB-INF is a bad place to try to store file uploads. There's no guarantee that this is an actual directory on the disk, and even if it is, the appserver may forbid write access to it.
Where you should store your files depends on what you want to do with them, and what operating system you're running on. Just pick somewhere outside of the webapp itself, is my advice. Perhaps create a dedicated directory
Also, the process of transferring the MultipartFile to another location is much simpler than you're making it out to be:
#RequestMapping(value = "/admin/house/update", method = RequestMethod.POST)
public String updateHouse(House house, #RequestParam("file") MultipartFile srcFile, Model model) throws IOException {
File destFile = new File("/path/to/the/target/file");
srcFile.transferTo(destFile); // easy!
model.addAttribute("step", 3);
this.houseDao.update(house);
return "houseAdmin";
}
You shouldn't store files in /WEB-INF/resource/uploads. This directory is either inside your WAR (if packaged) or exploded somewhere inside servlet container. The first destination is read-only and the latter should not be used for user files.
There are usually two places considered when storing uploaded files:
Some dedicated folder. Make sure users cannot access this directory directly (e.g. anonymous FTP folder). Note that once your application runs on more than one machine you won't have access to this folder. So consider some form of network synchronization or a shared network drive.
Database. This is controversial since binary files tend to occupy a lot of space. But this approach is a bit simpler when distributing your application.

Changing Location of Velocity.Log File

Seems pretty straight forward. Documentation at http://velocity.apache.org/engine/devel/developer-guide.html#Configuring_Logging
says to set the runtime.log property. Here's what I got for all my properties.
velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatesPath);
velocityEngine.setProperty("runtime.log", "/path/to/my/file/velocity.log");
velocityEngine.setProperty("resource.loader", "string");
velocityEngine.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
velocityEngine.setProperty("string.resource.loader.repository.class", "org.apache.velocity.runtime.resource.util.StringResourceRepositoryImpl");
Not finding any log file where I told it to place it and instead finding the new errors placed into old (folder of initialization) location. Any ideas? :D
i had similar problem when setting at runtime some options. I figured out those problem whit a custom VelocityBuilder and an external velocity.properties file where you can put all the runtime properties.
Here is the code:
public class BaseVelocityBuilder implements VelocityBuilder {
private VelocityEngine engine;
private Log logger = LogFactory.getLog(getClass());
#Autowired
private WebApplicationContext webApplicationContext;
public VelocityEngine engine() {
if(engine == null) {
engine = new VelocityEngine();
Properties properties = new Properties();
InputStream in = null;
try {
in = webApplicationContext.getServletContext().getResourceAsStream("/WEB-INF/velocity.properties");
properties.load(in);
engine.init(properties);
} catch (IOException e) {
e.printStackTrace();
logger.error("Error loading velocity engine properties");
throw new ProgramException("Cannot load velocity engine properties");
}
IOUtils.closeQuietly(in);
}
return engine;
}
}
See this line:
in = webApplicationContext.getServletContext().getResourceAsStream("/WEB-INF/velocity.properties");
properties.load(in);
engine.init(properties);
So i have a velocity.properties file in /WEB-INF where i put some configuration:
resource.loader = webinf, class
webinf.resource.loader.description = Framework Templates Resource Loader
webinf.resource.loader.class = applica.framework.library.velocity.WEBINFResourceLoader
webapp.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoader
webapp.resource.loader.path =
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path =
class.resource.loader.description = Velocity Classpath Resource Loader
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
runtime.log='/pathYouWant/velocity.log'
In the end in your application.xml :
<bean class="applica.framework.library.velocity.BaseVelocityBuilder" />
In this way you can have for example different file log for different application and when you give the war in production, the sysadm can change the properties due to env configuration of the production server.