PropertiesConfiguration how to reference config.properties - apache

I am new to Java so forgive me for my lack of knowledge. I am trying to utilize a properties file in my web app. While researching I found this article http://commons.apache.org/configuration/howto_properties.html which seemed pretty straight forward so I attempted to implement this. I attempted to implement as follows :
Configuration config = new PropertiesConfiguration("stream.bundle.config");
I have tried stream.bundle.config, bundle.config and many other combinations but every time I get back an exception that says Cannot locate configuration source. The file is in a folder under src called bundle. My question is a) where should the file be? b) how should I reference it. I apologize for my lack of knowledge. Thanks in advance.
update:
I also tried
FileInputStream in;
Properties p = new Properties();
try{
in = new FileInputStream("config.properties");
p.load(in);
}
catch(Exception e){
System.out.println("Error: " + e);
}
and I get java.io.FileNotFoundException: config.properties (The system cannot find the file specified) or java.io.FileNotFoundException: config (The system cannot find the file specified)

Regarding a) where should the file be:
in the current directory
in the user home directory
in the classpath
If you consider using Java's Properties you have to get an InputStream some way. If you're loading the properties from a class in the package, you have to use:
getClass().getResourceAsStream("resource.properties");
and if the class is in another package:
getClass().getResourceAsStream("some/pkg/resource.properties");
You can try loading the properties via the ClassLoader:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
If you have a ServletContext, you can use:
ServletContext.getResourceAsStream(..)
EDIT: you should reference your file by the full name (filename+extension). So your first
try should have been:
Configuration config = new PropertiesConfiguration("config.properties");

Try this:
Properties properties = new Properties();
try
{
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("xyz.properties"));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Can you debug java code in a Bamboo java spec #BambooSpec main method?

I'm using bamboo and bamboo java-spec using the pipeline as java code in a bitbucket hosted project.
I'm trying to use a json file as a configuration file to specify which stages I want to run in my pipeline.
So I've created a configuration.json file. And i've added the following code in my #BambooSpec annotated PlanSpec class.
private static Map<?, ?> getConfiguration(String configurationFile) throws Exception {
System.out.println("Does this work at all?");
Map<?, ?> map = null;
try {
// create Gson instance
Gson gson = new Gson();
// create a reader
Reader reader = Files.newBufferedReader(Paths.get(configurationFile));
// convert JSON file to map
map = gson.fromJson(reader, Map.class);
// print map entries
for (Map.Entry<?, ?> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
// close reader
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
return map;
}
But bamboo only shows logs for what's run as part of the plan spec. The System.out.println's, are not visable.
Is there a way to debug my code at runtime?
Edit: in the mean time I found out I can just run my code locally in the IDE. And then it'll complain about not finding a .credentials file. But that doesn't matter. I can at least test the code, from before it publishes the plan.

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);
}
});
}

Read the contents of a project using an eclipse plugin

I want to create a eclipse plugin which on click of a menu in the menu bar will scan all the project contents and give me idea about the use of a specified function if any such as isBoolean or isInteger etc..
I searched everywhere but not getting a clear idea about how to do it.I heard of IResource and Iproject API's but dint find any implementation of it.Could you please help me getting in the right direction .
I tried putting this in my action...
but got "java.lang.ClassNotFoundException: org.eclipse.jdt.core.search.SearchRequestor"
SearchPattern pattern = SearchPattern.createPattern("isBool",
IJavaSearchConstants.METHOD,
IJavaSearchConstants.REFERENCES,
SearchPattern.R_EXACT_MATCH);
IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
SearchRequestor requestor = new SearchRequestor() {
#Override
public void acceptSearchMatch(SearchMatch searchMatch) throws CoreException {
// TODO Auto-generated method stub
System.out.println( searchMatch.getElement());
}
};
SearchEngine searchEngine = new SearchEngine();
try {
searchEngine.search(
pattern,
new SearchParticipant[]
{SearchEngine.getDefaultSearchParticipant()},
scope, requestor, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Am I proceeding in the right direction? Or is there any changes need to be made..
I am assuming that you mean a Java project. You should have a look at the org.eclipse.jdt.core.search.SearchEngine API.
You need to do something like this:
SearchPattern pattern = SearchPattern.createPattern("isBoolean", IJavaSearchConstants.METHOD, IJavaSearchConstants.REFERENCES, SearchPattern.EXACT_MATCH);
new SearchEngine().search(
SearchEngine.createJavaSearchScope(patter,
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
new IJavaElement[] { iJavaProject }),
requestor,
new NullProgressMonitor());
Where requestor is the thing that asynchronously receives (and processes) your match results.

Best way to extract .zip and put in .jar

I have been trying to find the best way to do this I have thought of extracting the contents of the .jar then moving the files into the directory then putting it back as a jar. Im not sure is the best solution or how I will do it. I have looked at DotNetZip & SharpZipLib but don't know what one to use.
If anyone can give me a link to the code on how to do this it would be appreciated.
For DotNetZip you can find very simple VB.NET examples of both creating a zip archive and extracting a zip archive into a directory here. Just remember to save the compressed file with extension .jar .
For SharpZipLib there are somewhat more comprehensive examples of archive creation and extraction here.
If none of these libraries manage to extract the full JAR archive, you could also consider accessing a more full-fledged compression software such as 7-zip, either starting it as a separate process using Process.Start or using its COM interface to access the relevant methods in the 7za.dll. More information on COM usage can be found here.
I think you are working with Minecraft 1.3.1 no? If you are, there is a file contained in the zip called aux.class, which unfortunately is a reserved filename in windows. I've been trying to automate the process of modding, while manipulating the jar file myself, and have had little success. The only option I have yet to explore is find a way to extract the contents of the jar file to a temporary location, while watching for that exception. When it occurs, rename the file to a temp name, extract and move on. Then while recreating the zip file, give the file the original name in the archive. From my own experience, SharZipLib doesnt do what you need it do nicely, or at least I couldnt figure out how. I suggest using Ionic Zip (Dot Net Zip) instead, and trying the rename route on the offending files. In addition, I also posted a question about this. You can see how far I got at Extract zip entries to another Zip file
Edit - I tested out .net zip more (available from http://dotnetzip.codeplex.com/), and heres what you need. I imagine it will work with any zip file that contains reserved file names. I know its in C#, but hey cant do all the work for ya :P
public static void CopyToZip(string inArchive, string outArchive, string tempPath)
{
ZipFile inZip = null;
ZipFile outZip = null;
try
{
inZip = new ZipFile(inArchive);
outZip = new ZipFile(outArchive);
List<string> tempNames = new List<string>();
List<string> originalNames = new List<string>();
int I = 0;
foreach (ZipEntry entry in inZip)
{
if (!entry.IsDirectory)
{
string tempName = Path.Combine(tempPath, "tmp.tmp");
string oldName = entry.FileName;
byte[] buffer = new byte[4026];
Stream inStream = null;
FileStream stream = null;
try
{
inStream = entry.OpenReader();
stream = new FileStream(tempName, FileMode.Create, FileAccess.ReadWrite);
int size = 0;
while ((size = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, size);
}
inStream.Close();
stream.Flush();
stream.Close();
inStream = new FileStream(tempName, FileMode.Open, FileAccess.Read);
outZip.AddEntry(oldName, inStream);
outZip.Save();
}
catch (Exception exe)
{
throw exe;
}
finally
{
try { inStream.Close(); }
catch (Exception ignore) { }
try { stream.Close(); }
catch (Exception ignore) { }
}
}
}
}
catch (Exception e)
{
throw e;
}
}

Glassfish Custom Properties Resource Not Loading From File

I've deployed a webapp (war) to Glassfish v3 and I am trying to get it to read from properties defined in a custom resource.
In my app, I've defined the properties as:
#Resource(mappedName = "TestServletProperties")
private Properties properties;
and make use of it like this:
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException,
java.io.IOException
{
String propertyOne = properties.getProperty("testServlet.propertyOne");
String propertyTwo = properties.getProperty("propertyTwo");
StringBuffer buffer = new StringBuffer("Properties Retrieved\n");
buffer.append("Property One: " + propertyOne + "\n");
buffer.append("Property Two: " + propertyTwo + "\n");
try
{
response.getWriter().write(buffer.toString());
}
catch (Exception ex)
{
try
{
log.warn("Exception thrown", ex);
response.getWriter().write(ex.getStackTrace().toString());
}
catch (IOException io)
{
log.warn("IOException thrown", io);
}
}
}
In Glassfish, I've created a JNDI Custom Resource called TestServletProperties of type java.util.Properties and using factory class org.glassfish.resources.custom.factory.PropertiesFactory. In the resource there is one property "fileName" with its value set to the absolute path of the properties file:
/Program Files/glassfishv3/glassfish/domains/domain1/applications/Test/WEB-INF/classes/TestServlet_lab.properties
I've also tried
c:\Program Files\glassfishv3\glassfish\domains\domain1\applications\Test\WEB-INF\classes\TestServlet_lab.properties
I have confirmed that the file exists and contains the referenced properties. Unfortunately, I'm getting back "null" for both values in my response.
Any thoughts?
The solution is that you have to use the fully qualified "org.glassfish.resources.custom.factory.PropertiesFactory.fileName" versus just "fileName".
The reason might be that you have a web.xml file with the header of a 2.4 (or older) servlet version.
#Resource and other annotations are only processed if you have at least version 2.5 in the header of web.xml. Be sure that you do not simply change the version but copy and paste the new header from somewhere as the namespace is different.
Hope this helps