How can I convert the code below from Jython to Java?
The code will be used to run the Junit test to set the proxy details to make JUnits more usable.
Jyhon code:
from java.lang import *;
from com.parasoft.preferences import *;
from com.parasoft.proxy import *;
def SetupProxy(item, context):
preferences = AppPreferenceProvider.getProxyPreferenceProvider();
preferences.setProxyConfiguration("bisn.parasoft.com", "3128", "", "", "", "")
preferences.setUseProxy(1)
preferences.setUseProxyAutoConfig(0);
preferences.setUseSameProxySettings(1)
preferences.setUseProxyAuthentication(1)
preferences.setProxyUserId("devtest")
preferences.setProxyPasswd("dev%pass")
preferences.setSystemProxy(Boolean(0));
Since jython compiles into a .jar, there is no reason to convert the source code into java. However, if you really need to this, it is almost straightforward:
Add the package .... line to the top
Change all from a import b into import a.b (in your case, b is *, though you should avoid that)
The function must be inside a class and probably static. You could for example call the class SetupProxy, too.
The variables (item, context and preferences) must have a type declaration.
Of course, you can also decompile the .jar generated via jython to get some inspiration...
Related
I know that import example.* will import all the classes and interfaces in the package example. So is it necessary to use the * only when there are 2 or more classes in the example package?
Because in my program there was only 1 class, xyz, in the package example, and when I tried to use it in other program by import example.*;, the xyz class was not accessible.
Instead if I used it like - import example.xyz, then only it was accessible in other programs. But the usual import java.util.* and other commands work just fine. So is it because they have multiple classes and interfaces in those packages and only then should the * be used?
edit:package code
package myPackage;
public class abcd
{
public void show()
{
System.out.println("this is from package");
}
}
program
import myPackage.*;
class ghg
{
public static void main(String args[])
{
abcd x=new abcd();
x.show();
}
}
error
ghg.java:7: cannot access abcd
bad class file: .\abcd.class
class file contains wrong class: myPackage.abcd
Please remove or make sure it appears in the correct subdirectory of the classpath
EDIT: So i was keeping ghg.java in bin folder of jdk..I moved them out both package and ghg.java and put them in different directory and it worked.
Those import statements are just an indication for the compiler to know where to lookup classes you are using within your source code.
In that sense, this is only about style. There are no good technical reasons to use one or the other style.
But many people consider using "import x.y.*" to be bad practice; they recommend to have "import x.y.Class1", "import x.y.Class2", ...
Reasoning behind that: you, as the human reader are very much interested in understanding the dependencies into other packages. When the wild-card import is used; you have no mean to understand how many classes are really used. As in: if your class needs 50, 100 imports ... that alone would tell you that something is wrong (because your class has way too many dependencies when it is importing 50, 100 other classes). If wildcards are used, you wouldn't know.
As a consequence, tools such as eclipse will by default "roll out" wildcard imports and turn them into specific class imports instead.
Lets be precise: using "import *" is never required. It just seems convenient at times! And when "import x.y.*" does not work; but "import x.y.z" works; then well, you must have done something wrong!
I'm starting to get more into Clojure-Java interop. If I create a Java class in Clojure, I need to import it, but if I merely use fields or methods of a class, I don't have to import it. For example:
(ns students.Student
(:import [sim.util Double2D])
(defn -step
[this students] ; students is a students.Students, extends sim.engine.SimState
(let [yard (.-yard students) ; a sim.field.continuous.Continuous2D
yard-width (.-width yard)
yard-height (.-height yard)]
(.setObjectLocation yard this (Double2D. (/ yard-height 2) (/ yard-width 2)))))
This won't compile without importing Double2D, because the code creates a Double2D instance.
However, the fact that I access the yard field and setObjectLocation() method of a Students instance, and the width and height fields of a Continuous2D instance causes no problems, even though I don't import the Students or Continuous2D classes.
Does this mean that Clojure is using reflection at runtime to access Java fields and methods? Is that inefficient? If I need speed in a function, could it be advantageous to add type declarations for the Java classes, along the missing import statements? Would that prevent reflection?
[EDIT: As my second comment on Arthur Ulfeldt's answer suggests, I now think that any inefficiencies that come from not knowing classes at compile time are likely to be not very different from inefficiencies that come from the fact that functions are contained in variables. If I was worried about that, I'd forget about Clojure and program in pure Java (maybe), instead of trying to use Java libs from Clojure. For me, a world in which I can use Clojure instead of Java is a better one.]
Import is only used to make it so you don't have to type the full name of the class, including it's package name, each time you want to use it. if a class is on the classpath you can call it by it's full name from anywhere. If you as an import statement you can call it by just the class name, though only from within the namespace where that import exists.
I'll start with a new project and add a dependency that is clearly not used anywhere in the default project, in this case the Riemann client for monitoring stuff (it's a great program check it out)
lein new hello
and add the dep
(defproject hello "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:aot :all
:main hello.core
:profiles {:uberjar {:aot :all}}
:dependencies [[org.clojure/clojure "1.6.0"]
[com.aphyr/riemann-java-client "0.3.1"]])
then first thing, I'll look at that class by it's full name without any import
hello.core> com.aphyr.riemann.client.RiemannClient
com.aphyr.riemann.client.RiemannClient
then try the short name:
hello.core> RiemannClient
CompilerException java.lang.RuntimeException: Unable to resolve symbol: RiemannClient in this context, compiling:(/tmp/form-init3055907211270530213.clj:1:5933)
which does not work:
hello.core> (import '[com.aphyr.riemann.client RiemannClient])
com.aphyr.riemann.client.RiemannClient
Then if we add the import and try again:
hello.core> RiemannClient
com.aphyr.riemann.client.RiemannClient
the name resolves from within the user namespace.
If I change namespaces:
hello.core> (in-ns 'foo)
and then look at the class again:
foo> RiemannClient
CompilerException java.lang.RuntimeException: Unable to resolve symbol: RiemannClient in this context, compiling:(/tmp/form-init3055907211270530213.clj:1:5933)
foo> com.aphyr.riemann.client.RiemannClient
com.aphyr.riemann.client.RiemannClient
we can see that imports are per-namespace, though classes on the classpath are available everywhere.
I would like to reference a class Bag in a JAR file, but Eclipse is telling me that Bag cannot be resolved to a type. I have added the JAR in which Bag is defined to the classpath for the project, but the error is still there. What am I doing wrong?
I think you can't do that, because the Bag class in algs4.jar is inside the default package.
Before J2SE 1.4, we still can import classes from the default package using a syntax like this:
import Unfinished;
But from J2SE 1.5, that's no longer allowed. So if we want to access a default package class from within a packaged class requires moving the default package class into a package of its own. Read here for more detail explanation :
How to access java-classes in the default-package?
Some options you can choose :
Access the class via reflection or some other indirect method. But it is a little bit hard, something like this :
Class fooClass = Class.forName("FooBar");
Method fooMethod = fooClass.getMethod("fooMethod", new Class[] { String.class });
String fooReturned = fooMethod.invoke(fooClass.newInstance(), new String("I did it"));
If you own the source code of that jar library, you need to put it in properly package and wrap it again as a new jar library.
You may need to either fully qualify the Bag class, or import it.
Consider the following simple example of code:
public class TestStaticImport {
static enum Branches {
APPLE,
IBM
}
public static void doSomething(Branches branch) {
if (branch == APPLE) {
System.out.println("Apple");
}
}
}
If we will try to compile this code, we will get the error message:
java: cannot find symbol
symbol: variable APPLE
location: class TestStaticImport
This could be solved by introducing static import of this enum:
import static ... TestStaticImport.Branches.*
But in this moment incomprehensible things (for me) begin:
this solution works fine, everything is well compiled, until class TestStaticImport will be moved into empty root package, i.e. there isn't any
package blablabla; in the top of this java file;
Code line: import static TestStaticImport.Branches.*; is highlighted as valid code in my Intellij IDEA (name of IDE doesn't matter, just for information), but when I try to compile such code following error appears:
java: package TestStaticImport does not exist
So, there are actually two questions:
1) Main question: why is it impossible to import static from empty directory?
2) What is another way (if it exists) for allowing in code references to enum's fields using just their names (i.e. APPLE instead of Branches.APPLE), except static import?
P.S. Please, don't tell me, that empty packages is ugly style and so on. This question is just theoretical problem.
The Java language specification forbids any imports from the unnamed package:
A type in an unnamed package (§7.4.2) has no canonical name, so the
requirement for a canonical name in every kind of import declaration
implies that (a) types in an unnamed package cannot be imported, and
(b) static members of types in an unnamed package cannot be imported.
As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time
error on any attempt to import a type (or static member thereof) in an
unnamed package.
In ancient times, the Java inventors had to map Java types to files so the compiler could do some real work. They decided to map packages to folders and types to files. That worked pretty well. It especially set the emotional background for newcomers: "I hate you. Don't mess with me." But I digress.
The default package is a problem, though, since it doesn't have a well defined folder. If you have package com, you know that there is a folder com somewhere but what's the name of the folder for the default package?
So the designers decided that import and default package don't mix. In fact, you get an error when you try to import anything that has no package (i.e. import TestStaticImport without the static and * would also fail). See How to import a class from default package
So the problem isn't the static import but that you try to import from the default package.
Like some other corner cases in Java, there is no solution.
see also: In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement?
In Java- "Static Members of the default package cannot be imported"- Can some one explain this statement? It would be better if its with an example. I am not sure if it has a really simple answer but then I tried to understand but couldn't figure it out.
It means that if a class is defined in the default package (meaning it doesn't have any package definition), then you can't import it's static methods in another class. So the following code wouldn't work:
// Example1.java
public class Example1 {
public static void example1() {
System.out.println("Example1");
}
}
// Example2.java
import static Example1.*; // THIS IMPORT FAILS
public class Example2 {
public static void main(String... args) {
example1();
}
}
The import fails because you can't import static methods from a class that's in the default package, which is the case for Example1. In fact, you can't even use a non-static import.
This bug report has some discussion about why Java acts this way, and it was eventually closed as "not a defect" -- it's the way Java was designed to behave. Default package just has some unexpected behavior, and this is one of the reasons why programmers are encouraged to never used the default package.
as #kageb Brasee mentions : It is true that you cannot do the static import or non-static import of the class which is in a default package.
but there is a case where you can use the class (of default package) in another class: -> And this can only be done if and only if the class (in which you want to use the class of default package) is also present in a default package
if both the classes are in default packages (no matter at what location they are present) then you can use them (note : we are not import them just using them)
eg. if i want to import a class temp.class (which is in a default package) located at Home/files/temp.class into my program use.java
then just set the CLASSPATH while compiling it
you can do that in two ways : permanent set OR temporary set (Not using technical terms )
permanent set : by setting the CLASSPATH (which is an environment variable) variable (different methods to do that for different OS's) -> for mac - - > export CLASSPATH=Home/files/
in this method the CLASSPATH environment variable is set till your terminal is open
so in this case :
export CLASSPATH=Home/files/
javac use.java
java use
temporary set : in this method we use either of two option provided for both java and javac (java compiler) tool and they are -classpath and -cp (both these do the same job, its just -cp is short for the -classpath), in this method of setting classpath for the other files the main difference is that in this type the address(path) of the file is set only for the time period while that command (operation) is executing
as soon as the statement execution complete the value of CLASSPATH(the environment) -> again reaches to the same path as it was earlier,
Note: by default the CLASSPATH is . (i.e. representing the same directory)
And in this case :
java -cp .:Home/files use.java // Note: don't forget . and : is for separating the different paths
java use
Hope it helped :)
Create a new package under the default package such as sample>utils, then transfer that Java file whose Static Methods are not imported, to new created utils package, such as sample>utils>ResizeHelper.java :
And you are good to Go.