I am using Eclipse with Java. I need to define several very similar classes. It gets tedious typing the same thing automatically each time and wondering whether I could set up a short cut. I read Eclipse key bindings but it looks like something must already be in a plugin. This is what I need to type each time
public class SomeClass extends Token {
WebDriver driver = null;
WindowStack stack = null;
#Override
public void init() throw InitException {
super.init();
driver = TestCont.getWebDriver(); // defined and set elsewhere
stack = TestCont.getWindowStack();
}
#Override
public void exec throws ExecException {
}
}
SomeClass is actually some unique name.
I guess I could just keep the text in a file and copy/paste, but it would be nice to create a short cut. I recently saw an online class where someone was using an IDE (I don't know which one it was). He typed psvm and it automatically changed to
public static void main(String[] argc) {
}
and doing something like new SomeClass(parm1, parm2, parm3).var automatically set to
SomeClass var = new SomeClass(parm1, parm2, parm3);
and similarly anything with ".var" at the end would make such a variable. So I am wondering whether there is a way to do something similar (as above) in Eclipse with Java.
Not sure whether it matters but I have
Eclipse IDE for Enterprise Java Developers.
Version: 2018-12 (4.10.0)
Build id: 20181214-0600
OS: Windows 10, v.10.0, x86_64 / win32
Java version: 1.8.0_144
You can define templates in Preferences -> Java -> Editor -> Templates
The content assist takes these into account for template completion (the name of the template).
For example, two of the predefined templates are called sysout and syserr. If you type sys, then trigger code completion, it suggests these two templates. Selecting sysout results in this code being inserted:
System.out.println();
(the template also defines places where other stuff needs to be inserted, where the cursor goes etc. but for your problem that seems like nice-to-have).
Related
I'm trying to understand a comment that a colleague made. We're using testcontainers to create a fixture:
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;
public class SalesforceFixture extends GenericContainer<SalesforceFixture> {
private static final String APPLICATION_NAME = "salesforce-emulator";
public SalesforceFixture() {
// super(ImageResolver.resolve(APPLICATION_NAME));
super(DockerImageName.parse("gcr.io/ad-selfserve/salesforce-emulator:latest"));
...
}
...
The commented code is what it used to be. The next line is my colleague's suggestion. And on that line he commented:
This is the part I don't know. The [ImageResolver] gets the specific version of the emulator, rather than the latest. You need a docker-info file for that though, which jib doesn't automatically generate (but I think it can).
This is what I know or have figured so far:
SalesforceFixture is a class that will be used by other projects to write tests. It spins up a container in Docker, running a service that emulates the real service's API. It's like a local version of the service that behaves enough like the real thing that if one writes code and tests using the fixture, it should work the same in production. (This is where my knowledge ends.)
I looked into ImageResolver—it seems to be a class we wrote that searches a filesystem for something:
public static String resolve(String applicationName, File... roots) {
Stream<File> searchPaths = Arrays.stream(roots).flatMap((value) -> {
return Stream.of(new File(value, "../" + applicationName), new File(value, applicationName));
});
Optional<File> buildFile = searchPaths.flatMap((searchFile) -> {
if (searchFile.exists()) {
File imageFile = new File(searchFile + File.separator + "/target/docker/image-name");
if (imageFile.exists()) {
return Stream.of(imageFile);
}
}
return Stream.empty();
}).findAny();
InputStream build = (InputStream)buildFile.map(ImageResolver::fileStream).orElseGet(() -> {
return searchClasspath(applicationName);
});
if (build != null) {
try {
return IOUtils.toString(build, Charset.defaultCharset()).trim();
} catch (IOException var6) {
throw new RuntimeException("An exception has occurred while reading build file", var6);
}
} else {
throw new RuntimeException("Could not resolve target image for application: " + applicationName);
}
}
But I'm confused. What filesystem? Like, what is the present working directory? My local computer, wherever I ran the Java program from? Or is this from within some container? (I don't think so.) Or maybe the directory structure inside a .jar file? Or somewhere in gcr.io?
What does he mean about a "specific version number" vs. "latest"? I mean, when I build this project, whatever it built is all I have. Isn't that equivalent to "latest"? In what case would an older version of an image be present? (That's what made me think of gcr.io.)
Or, does he mean, that in the project using this project's image, one will not be able to specify a version via Maven/pom.xml—it will always spin up the latest.
Sorry this is long, just trying to "show my work." Any hints welcome. I'll keep looking.
I can't comment on specifics of your own internal implementations, but ImageResolver seems to work on your local filesystem, e.g. it looks into your target/ directory and also touches the classpath. I can imagine this code was just written for resolving an actual image name (not an image), since it also returns a String.
Regarding latest, using a latest tag for a Docker image is generally considered an anti-pattern, so likely your colleague is commenting about this. Here is a random article from the web explaining some of the issues with latest tag:
https://vsupalov.com/docker-latest-tag/
Besides, I don't understand why you ask these questions which are very specific to your project here on SO rather than asking your colleague.
I have a c code like this
static S16 test_1603b( const S16 *, const S16 * );
I want to edit this code pragmatically to be something like this
static S16 test_1603b( const S16 *varName, const S16 *varName );
So what I did I used Eclipse CDT plugin outside the eclipse, and I have successfully extracted the Abstract syntax tree(AST) and visited all the method parameter declaration, but I can not found any way to rewrite the AST again with the new modification, My Code snippet:
public class RuleChk extends AbstractRule {
public RuleChk(IASTTranslationUnit ast) {
super("RuleChk", false, ast);
shouldVisitDeclarations = true;
shouldVisitParameterDeclarations = true;
}
#Override
public int visit(IASTParameterDeclaration parameterDeclaration) {
if (!parameterDeclaration.getRawSignature().startsWith("void")) {
if (parameterDeclaration.getDeclarator().getName().getRawSignature().equals("")) {
IASTDeclarator oldDec = parameterDeclaration.getDeclarator();
//Create New Declarator Node
INodeFactory factory = ast.getASTNodeFactory();
IASTName name = factory.newName("varName".toCharArray());
IASTDeclarator declarator = factory.newDeclarator(name);
declarator.setParent(oldDec.getParent());
declarator.setInitializer(oldDec.getInitializer());
declarator.setName(name);
declarator.setNestedDeclarator(oldDec.getNestedDeclarator());
declarator.setPropertyInParent(oldDec.getPropertyInParent());
//get the rewriter
final TextEditGroup editGroup = new TextEditGroup("FakeGroup");
ASTRewrite rewriter = ASTRewrite.create(ast);
rewriter.replace(declarator,oldDec,editGroup);
rewriter.rewriteAST();
}
}
return super.visit(parameterDeclaration);
}
}
After Debugging I found the org.eclipse.cdt.internal.formatter.ChangeFormatter#formatChangedCode, when it try to get the
ICProject project = tu.getCProject();
It throws a null pointer exception because the TransionUnit (tu) is being null from the beginning of the whole application,
ANY IDEAS GEEKS!
A lot of the CDT infrastructure, including ASTRewrite, is not designed to run outside of an Eclipse project / workspace.
What you generally need to do in cases like this is:
Create an Eclipse workspace. If you don't otherwise need an Eclipse workspace, you can create a temporary one and delete it when you're done.
Create a CDT C project inside your workspace.
Make sure the code you want to process is part of the project. If the files are contained inside the project's directory tree, then this happens automatically. Otherwise, you can set up a "linked folder" in the project to refer to a location outside of the project's directory tree.
Depending on what your refactoring needs, you may need to run CDT's indexer on the project.
Get an ITranslationUnit representing the file you want to process (similar to what you wrote in your comment).
Get the IASTTranslationUnit from the ITranslationUnit.
The first four steps can be done manually, or automatically using Eclipse APIs.
I got a little project where I have to compute a list. The computation depends on serveal factors.
The point is that these factors change from time to time and the user should be allowed to change this by it's self.
Up to now, the factors are hard-coded and no changes can be done without recompiling the code.
At the moment the code looks like this:
if (someStatement.equals("someString")) {
computedList.remove("something");
}
My idea is to make an editable and human readable textfile, configfile, etc. which is loaded at runtime/ at startup? This file should hold the java code from above.
Any ideas how to do that? Please note: The targeted PCs do not have the JDK installed, only an JRE.
An effective way of going about this is using a static initializer. Static Block in Java A good and concise explanation can be found under this link.
One option here that would allow this would be to use User Input Dialogs from the swing API - then you could store the users answer's in variables and export them to a text file/config file, or just use them right in the program without saving them. You would just have the input dialogs pop up at the very beginning of the program before anything else happens, and then the program would run based off those responses.
You could use Javascript for the configuration file language, instead of java. Java 7 SE and later includes a javascript interpreter that you can call from Java. it's not difficult to use, and you can inject java objects into the javascript environment.
Basically, you'd create a Javascript environment, insert the java objects into it which the config file is expected to configure, and then run the config file as javascript.
Okay, here we go... I found an quite simple solution for my problem.
I am using Janino by Codehaus (Link). This library has an integrated Java compiler and seems to work like the JavaCompiler class in Java 7.
BUT without having the JDK to be installed.
Through Janino you can load and compile *.java files(which are human readable) at runtime, which was exactly what I needed.
I think the examples and code-snippets on their homepage are just painful, so here's my own implementation:
Step one is to implement an interface with the same methods your Java file has which is loaded at runtime:
public interface ZuordnungInterface {
public ArrayList<String> Zuordnung(ArrayList<String> rawList);}
Then you call the Janino classloader when you need the class:
File janinoSourceDir = new File(PATH_TO_JAVAFILE);
File[] srcDir = new File[] { janinoSourceDir };
String encoding = null;
ClassLoader parentClassLoader = this.getClass().getClassLoader();
ClassLoader cl = new JavaSourceClassLoader(parentClassLoader, srcDir,
encoding);
And create an new instance
ZuordnungsInterface myZuordnung = (ZuordnungInterface) cl.loadClass("zuordnung")
.newInstance();
Note: The class which is loaded is named zuordnung.java, so there is no extension needed in the call cl.loadClass("zuordnung").
And finaly the class I want to load and compile at runtime of my program, which can be located wherever you want it to be (PATH_TO_JAVAFILE):
public class zuordnung implements ZuordnungInterface {
public ArrayList<String> Zuordnung(ArrayList<String> rawList){
ArrayList<String> computedList = (ArrayList<String>) rawList.clone();
if (Model.getSomeString().equals("Some other string")) {
computedList.add("Yeah, I loaded an external Java class");
}
return computedList;
}}
That's it. Hope it helps others with similar problems!
I'm working on java application which perform some Runtime sub-process on files, for some files I got error cause the Send error report to Microsoft window to appear ,I need to handle this error programmatically, without showing this window to user. Please can anyone help ?
To Suppress windows error reporting the .exe that is being invoked should not terminate with an unhandled exception. This only works if you have access to the source of the application.
Based on the WER Reference - you should use the Win32 API call WerAddExcludedApplication to add the specific .exe files that you are intending to ignore to the per-user ignore list - you could create a simple stub-application that allows you to add applications by name to the ignore list. Then when you invoke the application it does not trigger the error.
Similarly you could create another application to remove them using the WerRemoveExcludedApplication.
Alternatives are to use JNI/JNA to make a class to encapsulate this functionality rather than using Runtime.exec
Here is a simple example using Java Native Access (JNA), which is a simpler version of JNI (no C++ needed for the most part). Download the jna.jar and make it part of your project.
import com.sun.jna.Native;
import com.sun.jna.WString;
import com.sun.jna.win32.StdCallLibrary;
public class JNATest {
public interface CLibrary extends StdCallLibrary {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("wer.dll",
CLibrary.class);
int WerAddExcludedApplication(WString name, boolean global);
int WerRemoveExcludedApplication(WString name, boolean global);
}
public static void main(String[] args) {
CLibrary.INSTANCE.WerAddExcludedApplication(new WString("C:\\foo.exe"), false);
CLibrary.INSTANCE.WerRemoveExcludedApplication(new WString("C:\\foo.exe"), false);
}
}
Basically, replace the new WString(...) value with the name of the application that you are intending to ignore. It should be ignored for the purposes of windows error reporting at that point.
Bear in mind that the wer.dll is only on Windows Vista and newer, so if this is a problem, then you may need to edit the registry entries manually.
You can always use try-catch-finally statement:
try
{
some code here (the code that is causing the error);
}
catch (Exception x)
{
handle exception here;
}
It works for me...
EDIT Here is the link that can help you a little bit more:
http://www.exampledepot.com/egs/Java%20Language/TryCatch.html
I am trying to grab filesystem events on OS / Kernel level on OS X.
There are 2 requirements i have to follow. The first one is to do this in java as the whole project im developing for is written in java. The second one is that i have to find out when a document is opened.
For Linux I used inotify-java, but I can't find a good equivalent on OS X. Also the JNA doesn't provide a helpful binding. Currently I'm avoiding catching events by frequently calling the lsof program. This, however, is a bad solution.
Thanks for the help.
You can use dtrace on OSX, but since it needs root privileges it's not something you'd want to put into a runtime of a system.
In any case, you won't be able to do this in pure Java (any Java API would be a wrapper around some lower level C introspection, and if you're doing it kernel-wide, would need to be done as root).
If you just want to track when your program is opening files (as opposed to other files on the same system) then you can install your own Security Manager and implement the checkRead() family of methods, which should give you an idea of when accesses are happening.
import java.io.*;
public class Demo {
public static void main(String args[]) throws Exception {
System.setSecurityManager(new Sniffer());
File f = new File("/tmp/file");
new FileInputStream(f);
}
}
class Sniffer extends SecurityManager {
public void checkRead(String name) {
System.out.println("Opening " + name);
}
}