Eclipse plugin development: how to create default folder on start of eclipse - eclipse-plugin

Creating an eclipse plugin. When I run my plugin, there should be some default folders already in the project explorer.
The idea is those folder are basically libraries which I can share with all the project created in project explorer.

Check out this tutorial here
public static IProject createProject(String projectName, URI location) {
Assert.isNotNull(projectName);
Assert.isTrue(projectName.trim().length() > 0);
IProject project = createBaseProject(projectName, location);
try {
addNature(project);
String[] paths = { "parent/child1-1/child2", "parent/child1-2/child2/child3" }; //$NON-NLS-1$ //$NON-NLS-2$
addToProjectStructure(project, paths);
} catch (CoreException e) {
e.printStackTrace();
project = null;
}
return project;
}
Follow the tutorial in the above link , its quite good for complete project developent
Though you havent asked this , but if there is a need for prewritten files in the project created by plugin. Use this code for achieving that
IFile htaccess=project.getFile("--.htaccess");
String contents = sb.toString();
InputStream sourceone = new ByteArrayInputStream(contents.getBytes());
htaccess.create(sourceone, false, null);
Hope it helps.

Related

Is there any way of getting version from build.gradle of a kotlin project?

I want to get the version of my project inside my project which I have set in build.gradle. Is there any method to get the version inside my project as I need to show the version inside my software and used for compairing update info, so that I don't need to change twice every time I release a update. Is there any way to make it?
group 'ProjectName.group'
version "ProjectVersion"
You typically do that by loading a properties file, and configuring gradle to filter your properties file in the processResources task.
Example:
build.gradle:
version = '1.5.0'
processResources {
def properties = ['version': project.version]
inputs.properties(properties)
filesMatching('version.properties') {
expand(properties)
}
}
version.properties:
version=${version}
App.java:
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(App.class.getResourceAsStream("/version.properties"));
System.out.println(properties.getProperty("version"));
}

Unable to download testng from http://beust.com/eclipse/ due to company policy .

I have created a maven project , with cucumber BDD and testNG . However to use testng i need to install the testng pluggin from eclipse help . The problem is my company has blocked usage of such external connections . Is there an alternative for this .
Following are your options.
See if you can get an approval from your company's IT department to whitelist the eclipse plugin download site so that you can install it via eclipse (or) have them download the eclipse plugin jar separately, and you can drop the jar in the dropins folder so that eclipse is aware of it. For more information, please refer to the answers of this stackoverflow question.
If available, resort to using an alternative IDE such as IntelliJ. IntelliJ unlike eclipse, comes pre-installed with the TestNG plugin and should suffice.
You leverage the build tool such as Maven/Ant/Gradle to run your tests from the command prompt. Both Maven and Gradle lets you run even 1 single test also at a given time. So you should be able to easily run tests without the IDE, from the command prompt (which is eventually how your tests would be run in a Continuous Integration environment such as Jenkins)
You create a main() method housing class, which would use the TestNG APIs directly to create tests. So every-time you want to run a TestNG test class or a suite etc., you would merely go back to your runner class, update it with the details and then run via it [ To me this option should be your last resort]
Here's a full fledged sample for option (4), which you should be able to start tweaking for your own use.
public class Practice {
public static void main(String[] args) {
for (String each : new String[]{"A", "B"}) {
runWith(each);
}
}
private static void runWith(String group) {
TestNG testNG = new TestNG();
XmlSuite xmlSuite = new XmlSuite();
xmlSuite.setName("suite");
XmlTest xmlTest = new XmlTest(xmlSuite);
xmlTest.setName("test");
xmlTest.addIncludedGroup(group);
XmlClass clazz = new XmlClass(Practice.class);
clazz.loadClasses();
xmlTest.getClasses().add(clazz);
testNG.setXmlSuites(Collections.singletonList(xmlSuite));
System.out.println(xmlSuite.toXml());
testNG.run();
}
#Test(dataProvider = "SearchProvider", groups = "A")
public void testMethodA(String author, String searchKey) {
System.out.println("testMethodA :" + author + ", " + searchKey);
}
#Test(dataProvider = "SearchProvider", groups = "B")
public void testMethodB(String searchKey) {
System.out.println("testMethodB :" + searchKey);
}
#DataProvider(name = "SearchProvider")
public Object[][] getDataFromDataprovider(ITestContext c) {
Object[][] groupArray = null;
for (String group : c.getIncludedGroups()) {
if (group.equalsIgnoreCase("A")) {
groupArray = new Object[][]{
{"Guru99", "India"},
{"Krishna", "UK"},
{"Bhupesh", "USA"}
};
break;
} else if (group.equalsIgnoreCase("B")) {
groupArray = new Object[][]{
{"Canada"},
{"Russia"},
{"Japan"}
};
}
break;
}
//return groupArray;
return groupArray;
}
}

Arquillian ShrinkWrap how to add an asset to the file system path

I am importing a library that reads from the file system instead of my web archive's resource folder. I want to be able to essentially mock that file by adding an asset with that path using ShrinkWrap, so I can run tests on my build server without guaranteeing the file system has all these files. I tried to add a String Asset in the appropriate path, but the code can't find that asset. Here's an example of what I'm trying to achieve.
Rest Resource
#Path("/hello-world")
public class HelloWorldResource {
#GET
public Response getHelloWorld(){
return Response.ok(getFileContent()).build();
}
private String getFileContent() {
StringBuilder builder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(
"/usr/myFile.txt"));
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line);
line = bufferedReader.readLine();
}
}
catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
}
Test
#RunWith(Arquillian.class)
public class HelloWorldResourceTest {
#Deployment
public static WebArchive createDeployment()
{
WebArchive webArchive = ShrinkWrap
.create(WebArchive.class)
.addPackages(true,
HelloWorldApplication.class.getPackage(),
HelloWorldResource.class.getPackage(),
Hello.class.getPackage())
.add(new StringAsset("Blah"),"/usr/myFile.txt")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
System.out.println("WebArchive: " + webArchive.toString(true));
return webArchive;
}
#Test
#RunAsClient
public void testHello(
#ArquillianResteasyResource("hello-world") final WebTarget webTarget)
{
final Response response = webTarget
.request(MediaType.APPLICATION_JSON)
.get();
String hello = response.readEntity(String.class);
System.err.println("Hello: " + hello);
Assert.assertEquals("Status is not OK", response.getStatus(), 200);
}
}
Web Archive toString
/WEB-INF/
/WEB-INF/classes/
/WEB-INF/classes/com/
/WEB-INF/classes/com/
/WEB-INF/classes/com/
/WEB-INF/classes/com/helloworld/
/WEB-INF/classes/com/helloworld/application/
/WEB-INF/classes/com/helloworld/application/HelloWorldApplication.class
/WEB-INF/classes/com/helloworld/resource/
/WEB-INF/classes/com/helloworld/resource/HelloWorldResourceTest.class
/WEB-INF/classes/com/helloworld/resource/HelloWorldResource.class
/WEB-INF/classes/com/helloworld/dataobjects/
/WEB-INF/classes/com/helloworld/dataobjects/Hello.class
/WEB-INF/beans.xml
/usr/
/usr/myFile.txt
I get the following error:
java.io.FileNotFoundException: /usr/myFile.txt (No such file or
directory)
Seems like ShrinkWrap is adding /usr/myFile.txt as a relative path within the archive instead of making it seem like /usr/myFile.txt is at the root directory of my file system. Is there any way I can get ShrinkWrap to do what I want?
Shrinkwrap is intended to create archives, so the API is scoped to create assets within the archive you are creating. If you want to have resources created in the regular filesystem simply use JDK, there is nothing Shrinkwrap could help you with.
Alternatively, if possible, change your resource to read resources from the classpath, not filesystem path. With this approach, you can easily swap content for the test using Shrinkwrap as you are trying now with your example.

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