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

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.

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.

How to call Function from an C# dll in Java?

i have a SAP-DLL to enable communication between a Programming interface and the SAP Programm.
I have following example Code for c# in combination with the dll-File:
var loggerService = LoggerService.GetLoggerService("FileLogger");
var itasProxy = SapProxyFactory.CreateSapProxy(SapSystem.Example, loggerService, "Example_User", StringExtension.CreateSecureString("Example_Password"));
var funcResult = sapProxy.SearchSapAddress(clientNo);
if (funcResult.Successfull)
{
funcResult.ReturnValue = withFormatting
? AddressFormatter.SplitStreetHouseNo(funcResult.ReturnValue)
: funcResult.ReturnValue;
}
Now i want the same functionality to be transferred to java. I have absolutely no clue how to do that. I tried the following with Loggerservice as a starter, but it doesn't work:
public class SAPConnector {
public static void main(String[] args) {
// TODO Auto-generated method stub
connectSAP();
}
public void connectSAP()
{
System.load("C://Temp//SapConnector.dll");
Object loggerService = getLoggerService("FileLogger");
}
public native Object getLoggerService(String lcLogger);
}
i just need some kind of information how to call the Functions from the dll or an example how to transfer the C# Code to working Code in Java.
Greetings,
Kevin
DLL is Microsoft format. Java is cross-platform, thus can't acknowledge anything operating-system specific, such as DLL.
One way around that is to use JNI (Java Native Interface), but that's usually not a good solution, as it makes your program platform-dependent.
Instead, I would look for a JAR from SAP, that provides a similar interface.
Maybe something along SAP JCO.
You can see some actual code examples using JCO here, and some technical information on step-by-step download and configure here.

Why sun.swing.AccessibleMethod is gone from JDK 8?

I'm wondering if someone know why sun.swing.AccessibleMethod is gone from JDK 8 and if there is some alternative to this class in JDK 8?
I can't find any information about that anywhere.
I use this class in my own implementation DropHandler. Code snippet where I use sun.swing.AccessibleMethod looks like this:
private DropLocation getDropLocation(DropTargetEvent e)
{
DropLocation dropLocation = null;
if (this.component != null)
{
try
{
Point p = e instanceof DropTargetDragEvent ? ((DropTargetDragEvent)e).getLocation() : ((DropTargetDropEvent) e).getLocation();
AccessibleMethod method = new AccessibleMethod(JComponent.class,
"dropLocationForPoint",
Point.class);
dropLocation = (DropLocation) method.invokeNoChecked(this.component, p);
}
catch (NoSuchMethodException ex)
{
LOGGER.info(ex.getMessage());
}
}
return dropLocation;
}
As explained in this official post from Oracle: Why Developers Should Not Write Programs That Call 'sun' Packages (thanks to #greg-449 for providing this info):
The sun.* packages are not part of the supported, public interface.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.
So, you should not have relied on sun.swing.AccessibleMethod class in the first place.
More info:
It is a bad practice to use Sun's proprietary Java classes?
As a solution for your problem, you can do the following:
Use the source code of sun.swing.AccessibleMethod to create a custom class.
Replace the usage of AccessibleMethod by your own custom class.
What’s the point about this AccessibleMethod class?
The following uses standard Java API which exists since Java 1.2:
try {
Method method = JComponent.class
.getDeclaredMethod("dropLocationForPoint", Point.class);
method.setAccessible(true);
dropLocation = (DropLocation) method.invoke(this.component, p);
} catch(NoSuchMethodException|IllegalAccessException|InvocationTargetException ex) {
Logger.info(ex.getMessage());
}
However, don’t come back and ask why JComponent.dropLocationForPoint has been removed, if that happens in the future. If you are accessing non-standard APIs you may encounter such problems. To be exact, there were always Java implementations not having these features your code relies on...

How can a user written program be send to library?

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.

Formatting JavaScript using Java API

I am generating JavaScript code using velocity in java.
For example: I generated JavaScript and got below string:
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
Is there any java API that takes this String and formats this JavaScript in below manner:
importClass(java.util.ArrayList);
function fun(arg) {
if (true){
return true;
}
else{
return true;
}
}
Closure Compiler
You can use Google's Closure Compiler.
It formats, compresses, optimizes, and looks for mistakes in JavaScript code.
For a quick look what it can do, you can try the web service.
Example
For your example string,
importClass(java.util.ArrayList); function fun(arg) { if (true){ return true;} else{ return true;}}
if you just want to format it, use the compile options "Whitespace only" and "Pretty print", which returns:
importClass(java.util.ArrayList);
function fun(arg) {
if(true) {
return true
}else {
return true
}
}
;
Anyway, with Closure compiler, you have several options to optimize and/or format your input code (either given as string or file URI) and to either return the optimized/formatted JS as string or save it to a file.
I can really recommend to use the "Simple" optimization mode. For longer Javascripts, it really saves you lots of unneeded bytes. Plus, it speeds up script execution!
For your example string, compile options "Simple" (instead of "Whitespace only") and "Pretty print" return
importClass(java.util.ArrayList);
function fun() {
return!0
}
;
As you can see, the result of both fun() functions is the same (Boolean true).
However, the second has removed all useless code (by remaining validity!) and will be executed faster.
Download & Reference
Now, the actual compiler is written in Java and is available as a command-line utility to download (Update 2014-07-10: New Downloadlink).
As a second option, you could implement your own wrapper class to communicate with the REST API (as I did for PHP). Doesn't require too much effort/code.
More info is available here:
Google Code Project Page
Getting Started
FAQ: How do I call Closure Compiler from the Java API?
REST API Reference
Hope that helps.

Categories

Resources