How can a user written program be send to library? - java

I tried a code.
Well, the first part is the main method that basically lays down the directory structure. I tried to delete a directory that contains other directories using the rmdirs method I wrote below.
public static void rmdirs(File k)
{
String[] y= k.list();
int i;
File f;
for(i=0;i<y.length;i++)
{
f= new File(k,y[i]);
if(f.isDirectory() && f.list().length>0)
{
rmdirs(f);
}
else
{
f.delete();
}
}
k.delete();
}
The rmdirs method is working and seems to be doing what I expected, but how do I add this program to a library, so that I can repeatedly use it by importing something.
Also, the above program does something like
rmdirs(f2);
to delete a file.
I would like it to be something like
f2.rmdirs();
And I am wondering how I can do it. I tried somehting like
import java.io.*;
public class RFile extends File
{
public RFile(String p)
{
super(p);
}
public RFile(File f1,String p1)
{
super(f1,p1);
}
public void rmdirs()
{
RFile k=this;
String[] y= k.list();
int i;
RFile f;
for(i=0;i<y.length;i++)
{
f= new RFile(k,y[i]);
if(f.isDirectory() && f.list().length>0)
{
f.rmdirs();
}
else
{
f.delete();
}
}
k.delete();
}
}
But then, the tester class or main class becomes one in which I have to use RFile and not File.
This is a problem; Also, like I asked before, how do I add all these to a library so that importing java.io.RFile or something like that will do the job?

You don't extend java.io.File (unless you have a very good reason and this is not such a reason)
One solution is to create a class like "FileUtils" which has a static method "remove" so you can call:
FileUtils.remove(myFile);
It's a general design philosophy that you can find in for example apache libraries (e.g. http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html)
UPDATE
A library is simply a reusable collection of code with a specific purpose.
Apache is a foundation that manages a lot of open source projects (a lot if not all of it java-based). They provide high quality (though in a few cases outdated) software that can be reused. While you're at it you might want to take a peek at "apache maven" which handles the lifecycle of a project and makes library management easy (believe it or not there is a whole repository with more than 600.000 libraries in it for you to use: http://mvnrepository.com/
And this is just one (although the largest) repository...
Design philosophy is an enormous subject with as many opinions as there are coders. However there are some best practices that everyone adheres to.
Apache usually has pretty high quality code so you can check them if not for code, at least for a good way to write libraries. Other than that I can only point you towards books and google to find your way.
Writing maintainable code is more of an art than a science and it takes a lot of reading and practice to master it.

Related

Reading the spss file java

SPSSReader reader = new SPSSReader(args[0], null);
Iterator it = reader.getVariables().iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
I am using this SPSSReader to read the spss file. Here,every string is printed with some junk characters appended with it.
Obtained Result :
StringVariable: nameogr(nulltpc{)(10)
NumericVariable: weightppuo(nullf{nd)
DateVariable: datexsgzj(nulllanck)
DateVariable: timeppzb(null|wt{l)
DateVariable: datetimegulj{(null|ns)
NumericVariable: commissionyrqh(nullohzx)
NumericVariable: priceeub{av(nullvlpl)
Expected Result :
StringVariable: name (10)
NumericVariable: weight
DateVariable: date
DateVariable: time
DateVariable: datetime
NumericVariable: commission
NumericVariable: price
Thanks in advance :)
I tried recreating the issue and found the same thing.
Considering that there is a licensing for that library (see here), I would assume that this might be a way of the developers to ensure that a license is bought as the regular download only contains a demo version as evaluation (see licensing before the download).
As that library is rather old (copyright of the website is 2003-2008, requirement for the library is Java 1.2, no generics, Vectors are used, etc), I would recommend a different library as long as you are not limited to the one used in your question.
After a quick search, it turned out that there is an open source spss reader here which is also available through Maven here.
Using the example on the github page, I put this together:
import com.bedatadriven.spss.SpssDataFileReader;
import com.bedatadriven.spss.SpssVariable;
public class SPSSDemo {
public static void main(String[] args) {
try {
SpssDataFileReader reader = new SpssDataFileReader(args[0]);
for (SpssVariable var : reader.getVariables()) {
System.out.println(var.getVariableName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I wasn't able to find stuff that would print NumericVariable or similar things but as those were the classnames of the library you were using in the question, I will assume that those are not SPSS standardized. If they are, you will either find something like that in the library or you can open an issue on the github page.
Using the employees.sav file from here I got this output from the code above using the open source library:
resp_id
gender
first_name
last_name
date_of_birth
education_type
education_years
job_type
experience_years
monthly_income
job_satisfaction
No additional characters no more!
Edit regarding the comment:
That is correct. I read through some SPSS stuff though and from my understanding there are only string and numeric variables which are then formatted in different ways. The version published in maven only gives you access to the typecode of a variable (to be honest, no idea what that is) but the github version (that does not appear to be published on maven as 1.3-SNAPSHOT unfortunately) does after write- and printformat have been introduced.
You can clone or download the library and run mvn clean package (assuming you have maven installed) and use the generated library (found under target\spss-reader-1.3-SNAPSHOT.jar) in your project to have the methods SpssVariable#getPrintFormat and SpssVariable#getWriteFormat available.
Those return an SpssVariableFormat which you can get more information from. As I have no clue what all that is about, the best I can do is to link you to the source here where references to the stuff that was implemented there should help you further (I assume that this link referenced to in the documentation of SpssVariableFormat#getType is probably the most helpful to determine what kind of format you have there.
If absolutely NOTHING works with that, I guess you could use the demo version of the library in the question to determine the stuff through it.next().getClass().getSimpleName() as well but I would resort to that only if there is no other way to determining the format.
I am not sure, but looking at your code, it.next() is returning a Variable object.
There has to be some method to be chained to the Variable object, something like it.next().getLabel() or it.next().getVariableName(). toString() on an Object is not always meaningful. Check toString() method of Variable class in SPSSReader library.

Java Access a DLL file in finger print attendance reader SDK

I’m trying to build a fingerprint attendance system. I want to directly query attendance records from finger print attendance device to my java application. To do so I want to deal with the SDK of the FP Attendance device. Manufacture of the device has provided the SDK and the documentation which contains a DLL (Riss.Devices.dll) file that has all the necessary entity classes and utility classes.
I googled whole two days to find a way to interact with this dll (Riss.Devices.dll) file through java and I found many options like JNI, JNA, SWIG etc. But Each and every option is new to me.
If someone can help me to find most suitable way to do this, is very helpful to me because I don’t have much time to hang on.
Documentation
I think JNA is the easiest option. Your code would look something like:
import com.sun.jna.*;
public class Foo {
public interface RissDevices extends Library {
public int BitCheck(int num, int index);
public int SetBit(int num, int index);
// TODO: list the other functions you want
}
public static void main(String[] args) {
RissDevices library = (RissDevices) Native.loadLibrary("c:/path/to/Riss.Devices.dll", RissDevices.class);
System.out.println(library.BitCheck(0, 0));
}

c# And/Or vb.net equivalent of apache commons Validate

In Java, if Apache Commons Lang jar is in the classpath, we can do one line Validates, like
Validate.isTrue(someBoolean, "This should be true");
In effect the above is the same as:
if (! someBoolean) {
throw new RuntimeException("This should be true");
}
Is there something in the .net world that will do the same?
I know I have seen code somewhere that did something similar but I can't remember where or the systax.
Any help is much appreciated.
You can, of course, write your own:
public static class Validate
{
public static void IsTrue(bool value)
{
if (!value) throw new InvalidOperationException(message)
}
}
Also, in C# or VB you can use code contracts:
Contract.Requires(someBoolean, "This should be true")
This requires downloading the code contracts extension from the Visual Studio extensions site. You can turn on code contracts and have them verified at compile time, and it allows specifying fairly arbitrary contract conditions.

Writing java program to recursively test file naming standards

I want to write a Java application that validate files and directories according to certain naming standards. The program would let you pick a directory and would recursively analyze -- giving a list of files/directories that do not match the given rules.
Eventually I want the user to be able to input rules, but for now they would be hard coded. Oh, and this would need to be cross-platform.
I'm have a working knowledge of basic Java constructs but have no experience with libraries and have not had much luck finding demos/code samples for this type of thing.
I would love suggestions for what trees to start barking up, pseudo-code -- whatever you feel would be helpful.
EDIT: I'm not trying to remove anything here, just get a recursive listing of any names that break certain rules (e.g. no spaces or special characters, no directories that start with uppercase) in the chosen directory.
I would like to use Commons IO, I think DirectoryWalker will help you.
Here is the sample for checking and removing ".svn" dir
public class FileCleaner extends DirectoryWalker {
public FileCleaner() {
super();
}
public List clean(File startDirectory) {
List results = new ArrayList();
walk(startDirectory, results);
return results;
}
protected boolean handleDirectory(File directory, int depth, Collection results) {
// delete svn directories and then skip
if (".svn".equals(directory.getName())) {
directory.delete();
return false;
} else {
return true;
}
}
protected void handleFile(File file, int depth, Collection results) {
// delete file and add to list of deleted
file.delete();
results.add(file);
}
}

How can I control the usage of a custom jar library?

I need a way to essentially secure my jar library to allow registered apps to use it in their projects and deny usage to apps that weren't approved by me.
It is fine if I hard code things in the lib for each distribution. I currently have this jar obfuscated.
What are good approaches to restrict the usage of a jar?
One idea was to lock the lib to a specific package so if the developer tries to use it in another project they can't. But I'm not sure if they can easily provide a custom fake Context to make it work...
To me the best approach if you would like your library to stay standalone (without involving the network for checking or downloading pieces of the library, I mean) would be to make mandatory the use of an initializer class that would receive a token from the client application.
This would be crackable as the token validity test would be performed by your lib: one may modify the lib in a way is would just skip that test, but this would be made harder by the obfuscation. But this is probably sufficient, unless using your lib without having registered it is a really critical issue.
So you would have something like:
boolean Initializer.initLib(String passcode)
That would prevent the lib to work unless passcode is correct.
You can make the obfuscation more efficient by avoiding checking that way:
public void initLib(String passcode) {
if (passcode == A_GIVEN_PUBLIC_STATIC_THAT_STORESTHE_CODE) {
// do the proper initializations
}
else {
throw new RuntimeException("Bad passcode, sorry!");
}
}
But doing that way instead:
public void initLib(String passcode) {
final char[] PASS_ENCRYPTED = "f5uhjgf56ik8kv214d5".toCharArray();
final char[] PASS_MINUSMASK = "bc".toCharArray();
final int PASS_SHIFT = 11;
final int PASS_MASK_MINUS = 2;
for (int ctr = 0; ctr < PASS_MINUSMASK.length; ++ctr) {
final char next = PASS_ENCRYPTED[PASS_SHIFT + ctr - PASS_MASK_MINUS];
if (passcode.charAt(ctr) != next - (PASS_MINUSMASK[ctr] - 'a')) {
// make the lib unusable by some inits. But it should look as a proper initialization
return;
}
}
// make the lib usable by some inits.
}
This looks stupid, but if you have a look at the obfuscated code, you will see a big difference. This code is just an example (it accepts "hi" as a valid passcode), any algorithm would be fine as long as its obfuscated version is not too straightforward to reverse.
Now the question is: what passcode?
As the library's protection concerns the developpers of the client apps that will use it, and not the final users of these apps, you cannot rely on any piece of data specific to the devices on which the applications will run. So no IMEI or anything like that.
If these developpers are trustworthy that's fine. A fixed passcode is sufficient.
But if they are subject to give this passcode to other people to allow them using your library, this is more difficult. In this case I don't think you can solve it without a real "industrial" process such as registering the client apps and their code checksums, for example. Such a process needs a specific design and cannot be solved "just by the code", but as it also has a cost (time, resources, involvment of the client...) you can only consider this if the use of library is very critical.
Can't you make your jar call your server with a specific code and the application name, to check if they are registered ?
When you build an Android app with a jar, that jar is compiled into the app and becomes a part of it. You can't just copy the jar out of the package and use it elsewhere. Unless I'm not understanding the question, this shouldn't be an issue you need to worry about.

Categories

Resources