How to execute inline refactoring programmatically using JDT/LTK? - eclipse

I could use Refactor->Inine when I need to inline a method.
This the code skeleton that I tried, I used the code in this post - Is there any eclipse refactoring API that I can call programmatically?.
// 1. Get ICompiationUnit for type "smcho.Hello"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("Hello");
project.open(null /* IProgressMonitor */);
IJavaProject javaProject = JavaCore.create(project);
IType itype = javaProject.findType("smcho.Hello");
org.eclipse.jdt.core.ICompilationUnit icu = itype.getCompilationUnit();
// 2. Contribution and Description creation
RefactoringContribution contribution = RefactoringCore.getRefactoringContribution(IJavaRefactorings.INLINE_METHOD);
InlineMethodDescriptor descriptor = (InlineMethodDescriptor) contribution.createDescriptor();
descriptor.setProject(icu.getResource().getProject().getName( ));
// 3. executing the refactoring
RefactoringStatus status = new RefactoringStatus();
try {
Refactoring refactoring = descriptor.createRefactoring(status);
IProgressMonitor monitor = new NullProgressMonitor();
refactoring.checkInitialConditions(monitor);
refactoring.checkFinalConditions(monitor);
Change change = refactoring.createChange(monitor);
change.perform(monitor);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute the code, I got this error
org.eclipse.core.runtime.CoreException: The refactoring script argument 'input' is missing
in the refactoring script.
I think I need to give the refactored method name to the API. What might be wrong in the code?

You never supply the method to the refactoring operation in the above code, you only give it the project context. But I don't know the necessary API for that.
If you look at this source code, you will notice the use of JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, which is probably the one you also need to set. Maybe you can search the refactoring.ui plugin sources for references to that attribute.

This is the code that works with inline refactoring JDT API.
It requires start position and length to be inlined.
int[] selection= {start, length}; // getSelection();
InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(this.icu, new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(this.icu, true), selection[0], selection[1]);
refactoring.setDeleteSource(true);
refactoring.setCurrentMode(Mode.INLINE_ALL); // or INLINE SINGLE based on the user's intervention
IProgressMonitor pm= new NullProgressMonitor();
RefactoringStatus res = refactoring.checkInitialConditions(pm);
res = refactoring.checkFinalConditions(pm);
final PerformRefactoringOperation op= new PerformRefactoringOperation(
refactoring, getCheckingStyle());
op.run(new NullProgressMonitor());
When you know the name of the method that is going to be inlined, you can use the code in - Getting startPosition and length of a method invocation using JDT

Related

Error During Creating XACML3 policy using Balana Code

I just want to create a simple policy using Balana code in very simple and basic steps ! This policy contain only one resource and one rule just to see how policies can be created in Balana!.
and this is my code
MatchElementDTO medto = new MatchElementDTO();
medto.setMatchId("urn:oasis:names:tc:xacml:1.0:function:string-equal");
AttributeValueElementDTO avdto = new AttributeValueElementDTO();
avdto.setAttributeValue("file");
avdto.setAttributeDataType("http://www.w3.org/2001/XMLSchema#string");
AttributeDesignatorDTO addto = new AttributeDesignatorDTO();
addto.setAttributeId("urn:oasis:names:tc:xacml:1.0:resource:resource-id");
addto.setCategory("urn:oasis:names:tc:xacml:3.0:attribute-category:resource");
addto.setDataType("http://www.w3.org/2001/XMLSchema#string");
addto.setMustBePresent("true");
medto.setAttributeValueElementDTO(avdto);
medto.setAttributeDesignatorDTO(addto);
AllOfElementDTO aodto = new AllOfElementDTO();
aodto.addMatchElementDTO(medto);
List<AllOfElementDTO> allOfElementDTOs = new ArrayList<AllOfElementDTO>();
allOfElementDTOs.add(aodto);
AnyOfElementDTO aydto = new AnyOfElementDTO();
aydto.setAllOfElementDTOs(allOfElementDTOs);
List<AnyOfElementDTO> anyOfElementDTOs = new ArrayList<AnyOfElementDTO>();
anyOfElementDTOs.add(aydto);
TargetElementDTO tedto = new TargetElementDTO();
tedto.setAnyOfElementDTOs(anyOfElementDTOs);
RuleElementDTO redto = new RuleElementDTO();
redto.setRuleId("ruleForFile");
redto.setRuleEffect("Permit");
redto.setTargetElementDTO(tedto);
List<RuleElementDTO> ruleElementDTOs = new ArrayList<RuleElementDTO>();
ruleElementDTOs.add(redto);
// Creating Policy by PolicyElementDTO
PolicyElementDTO pedto = new PolicyElementDTO();
pedto.setPolicyName("amirPolicy");
pedto.setPolicyDescription("simple having one element policy");
pedto.setRuleCombiningAlgorithms("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
pedto.setRuleElementDTOs(ruleElementDTOs);
pedto.setTargetElementDTO(tedto);
pedto.setVersion("1.0");
try {
pb.build(pedto);
} catch (PolicyBuilderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I call build(PolicyElementDTO) .. then there I got error that Exception in thread "main" java.lang.NullPointerException. Where is the problem in my code
Actually, I want to create policy by giving some parameters only.. (i.e. Subject, Action, Resource).
Anyone can guide me. I am newbie in Balana. So plz help me step by step.

CQ Jcr node how to resolve Sling:OrderedFolder jcr:primarytype and get children nodes

the path for above structure's parent: pdf folder, is -> /content/dam/example/corporate/pdf
and pdf folder's value of jcr:primarytype is Sling:OrderedFolder ,so does the other two folder '2013' '2014'...
if the parent 'pdf' is a page type, i know exactly how to iterate through a page structure and retrieve children node's property information by using jcr node api.
but unfortunately 'pdf' is an orderedfolder type...
what i need now is, to iterate through the structure and retrieve ALL PDFs path and store into a ArrayList, for example, the path of '2013exampleOne.pdf' node is /content/dam/example/corporate/pdf/2013exampleOne.pdf ,
and path of '2014examplePDFTwo.pdf' is /content/dam/example/corporate/pdf/2014examplePDFTwo.pdf ...etc... (this list may server other part of the application to download pdf later, but this has nothing to do with my current question...)
here is my own code for attemping (please notice, this is only part of my servlet, ):
#Override
protected void doGet(final SlingHttpServletRequest request,
final SlingHttpServletResponse response) throws ServletException,
IOException {
....//some more code
....
....
....
final ResourceResolver resourceResolver = request.getResourceResolver();
Node pdfJcrNode = resourceResolver.resolve("/content/dam/example/corporate/pdf").adaptTo(Node.class);
NodeIterator yearChildrenNodes;
try {
yearChildrenNodes = pdfJcrNode.getNodes();
while(yearChildrenNodes.hasNext()){
Node yearItemNode = yearChildrenNodes.nextNode();
while(yearItemNode.getNodes().hasNext()){
String pdfNodeAssetString = yearItemNode.getNodes().nextNode().getProperty("jcr:primaryType").getString();
if(pdfNodeAssetString.equals("dam:Asset")){
pdfPathList.add(yearItemNode.getNodes().nextNode().getPath().toString());
}
}
}
} catch (RepositoryException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
....
....
....
....//some more code
}
once again, the path of the parent folder 'pdf' is /content/dam/example/corporate/pdf
any suggestions to help me? thanks
ps: please provide code example to help, cheers
Why not use a query?
XPATH:
/jcr:root/content/dam/example/corporate/pdf//*[jcr:primaryType='dam:Asset']
You can use the QueryManager like this:
Session session = resourceResolver.adaptTo(Session.class)
QueryManager qm = session.getWorkspace().getQueryManager();
Query q = qm.createQuery("/jcr:root/content/dam/example/corporate/pdf//*[jcr:primaryType='dam:Asset']", "xpath");
QueryResult result = q.execute();
NodeIterator nIt = result.getNodes();
With this you can iterate over the Nodes.
Also small side note to your code, you are using nextNode() twice. So you are iterating further without checking if there is a nextNode.

Xtend Code Generator How to Copy Files

I am implementing my own DSL and using Xtend to generate codes. I need some static resources to be copied to my generate code. I was trying to use commons-io, but I couldn't get anywhere with that! What is the best way to do so? I am trying to avoid reading each file and writing to the corresponding file in output path...
This should do (taken from this web site, slightly modified, not tested)
def static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}

FOP/ikvm: error "Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl not found"

I have produced a fop.dll from fop-1.0 with ikvm:
ikvmc -target:library -reference:IKVM.OpenJDK.Core.dll -recurse:{myPathToJars}\*.jar -version:1.0 -out:{myPathToJars}\fop.dll
If I use my fop.dll in a Windows Application, everything works perfect.
If I use it in a Class Library, I get the following error:
"Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl not found" at javax.xml.transform.TransformerFactory.newInstance()
The code line is: TransformerFactory factory = TransformerFactory.newInstance();
Here is the code of method:
public static void xmlToPDF(String xmlPath, String xslPath, SortedList arguments, String destPdfPath)
{
java.io.File xmlfile = new java.io.File(xmlPath);
java.io.File pdffile = new java.io.File(destPdfPath);
try
{
// configure fopFactory as desired
FopFactory fopFactory = FopFactory.newInstance();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// configure foUserAgent as desired
// Setup output
OutputStream outputStream = new java.io.FileOutputStream(pdffile);
outputStream = new java.io.BufferedOutputStream(outputStream);
try
{
// Construct fop with desired output format
Fop fop = fopFactory.newFop("application/pdf" /*MimeConstants.MIME_PDF*/, foUserAgent, outputStream);
// Setup XSLT
TransformerFactory factory = TransformerFactory.newInstance();
java.io.File xsltfile = new java.io.File(xslPath);
Transformer transformer = factory.newTransformer(new StreamSource(xsltfile.getAbsoluteFile()));
// Set the value of a in the stylesheet
if (arguments != null)
{
IList keys = arguments.GetKeyList();
foreach (var key in keys)
{
Object value = arguments[key];
transformer.setParameter(key.ToString(), value);
}
}
// Setup input for XSLT transformation
Source src = new StreamSource(xmlfile);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
}
catch (Exception e1)
{
System.Console.WriteLine(e1.Message);
}
finally
{
outputStream.close();
}
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
I used ikvm-0.46.0.1 to make my fop.dll (based on fop 1.0). I included the following jars:
avalon-framework-4.2.0.jar
batik-all-1.7.jar
commons-io-1.3.1.jar
commons-logging-1.0.4.jar
fop.jar
serializer-2.7.0.jar
xalan-2.7.0.jar
xercesImpl-2.7.1.jar
xml-apis-1.3.04.jar
xml-apis-ext-1.3.04.jar
xmlgraphics-commons-1.4.jar
Any idea why this error occurs? Why is the behaviour different between Windows Application and Class Library?
Addition 10/19/11:
I managed to get working the following:
MyMainPrg (a Windows Forms Application)
MyFopWrapper (a Class Library that calls fop.dll)
But for my case this is not the solution, because in my target project, I have the following structure:
MainCmdLinePrg (a Console Application; calls DLL_1)
DLL_1 (calls DLLsharedFop) {there are several DLLs that can call DLLsharedFop}
DLLsharedFop (calls directly fop.dll; or - I don't care - might call MyFopWrapper)
Unfortunately this construct results in the error.
You can shorten to a pair (ACmdLinePrg,MyFopWrapper): already this does not work! But (MyMainPrg,MyFopWrapper) does...
Here is how I got that error and how I resolved:
My solultion looks like this:
ClientApp (references)--> ClassLibrary1
My ClassLibrary1 public functions are using, but not exposing any IKVM related objects, therefore the caller (ClientApp) did not have to add IKVM references. All is good in compile time.
However in runtime, the situation is different. I got the same exception and realized that ClientApp also needed to reference the correct IKVM dll (IKVM.OpenJDK.XML.Transform.dll) that contains "com.sun.org.apache.xalan.#internal.xsltc.trax" namespace.
I resolved a similar problem by adding the following before the problematic line:
var s = new com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl();
var t = new com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl();
As described here
Do you have the dll with the missing class in your working directory?
If you have the dll then it is a classloader problem. Look in the IKVM wiki. Often the BootClassPathAssemby help.
I was using NuGet Packages of FOP.dll v1.1.0 and IKVM pacakges of v7.1.45 in C#.NET app. I got this issue on Windows 2016 x64 server with error messages like:
------------------------------ Fop.cs (111): Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl
not found - at javax.xml.transform.TransformerFactory.newInstance()
Fop.cs (125): Provider
com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl not found
- at javax.xml.parsers.SAXParserFactory.newInstance()\r\n at org.apache.avalon.framework.configuration.DefaultConfigurationBuilder..ctor(Boolean
enableNamespaces)\r\n at
org.apache.avalon.framework.configuration.DefaultConfigurationBuilder..ctor()\r\n
I resolved the problem by adding those two lines at begins of procedure
com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl s = new com.sun.org.apache.xerces.#internal.jaxp.SAXParserFactoryImpl();
com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl t = new com.sun.org.apache.xalan.#internal.xsltc.trax.TransformerFactoryImpl();
helpful link:
https://github.com/KevM/tikaondotnet/issues/21

Eclipse plugin - how to run external class

I want to make a plugin for Eclipse. The thing is that I looked into the API, and examples, and I managed to make a button on main bar, with a specific icon, and when I click it, open up an InputDialog.
The hard part, is that I want to start an aplication from this button, but not with Runtime as it was a new process. I simply want to start a class inside plugin, which will log in to a server and get some output from it. I want it to be opened in a console, like launching a normal application, or a separate console.
The best example of this kind is a Tomcat plugin which starts Tomcat, and then outputs the console to the Eclipse console. I want to do that too. I've looked at the Tomcat source plugin, but I got stuck there too. They use their own launcher.
I am not sure what you mean by "I want to simply start a class". I assume there is a command line tool that you want to execute and redirect its output to the console window.
To be able to do that without spawning a new process, you have to be able to control the output stream of the tool. If it cannot be controlled, then you have no choice but to start a new process to properly capture the tool's output.
It is technically possible to call System.setOut instead, but it will redirect output from all threads to your console which is not what you want.
Nevertheless you start by creating a console:
// function findConsole copied from:
// http://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F
private MessageConsole findConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName()))
return (MessageConsole) existing[i];
//No console found, so create a new one.
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[]{myConsole});
return myConsole;
}
// Find my console
MessageConsole cons = findConsole("MyTool Console");
MessageConsoleStream out = cons.newMessageStream();
// Optionally get it's input stream so user can interact with my tool
IOConsoleInputStream in = cons.getInputStream();
// Optionally make a differently coloured error stream
MessageConsoleStream err = cons.newMessageStream();
err.setColor(display.getSystemColor(SWT.COLOR_RED));
// Display the console.
// Obtain the active page. See: http://wiki.eclipse.org/FAQ_How_do_I_find_the_active_workbench_page%3F
IWorkbenchPage page = ...;
String id = IConsoleConstants.ID_CONSOLE_VIEW;
IConsoleView view = (IConsoleView) page.showView(id);
view.display(cons);
Then set the input and output streams of my tool and start processing in a different thread so the UI will not block.
// Create my tool and redirect its output
final MyTool myTool = new MyTool();
myTool.setOutputStream(out);
myTool.setErrorStream(err);
myTool.setInputStream(in);
// Start it in another thread
Thread t = new Thread(new Runnable() {
public void run() {
myTool.startExecuting();
}
});
t.start();
If your tool does not support I/O redirection, you have no choice but to start it in another process with the ProcessBuilder and use a number of threads to move data between console and process streams See: Process.getInputStream(), Process.getOutputStream() and Process.getErrorStream().
The following links have additional useful details:
Executing a Java application in a separate process
FAQ How do I write to the console from a plug-in?
FAQ How do I find the active workbench page?
This is the code for running a new console with controls, like stop delete, and deleteAll! This is what I asked for in the beginning, but the message console is good to know!
ILaunchConfigurationType launchType = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType("org.eclipse.jdt.launching.localJavaApplication");
ILaunchConfigurationWorkingCopy config = null;
try {
config = launchType.newInstance(null, "My Plugin working");
} catch (CoreException e) {
System.err.println(e.getMessage());
}
config.setAttribute(ILaunchConfiguration.ATTR_SOURCE_LOCATOR_ID, "org.eclipse.jdt.launching.sourceLocator.JavaSourceLookupDirector");
String[] classpath = new String[] { "C:\\Users\\Administrator\\Documents\\myjr.jar" };
ArrayList classpathMementos = new ArrayList();
for (int i = 0; i < classpath.length; i++) {
IRuntimeClasspathEntry cpEntry = JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(classpath[i]));
cpEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
try {
classpathMementos.add(cpEntry.getMemento());
} catch (CoreException e) {
System.err.println(e.getMessage());
}
}
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpathMementos);
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "collectorlog.handlers.MyClass");
try {
ILAUNCH = config.launch(ILaunchManager.RUN_MODE, null);
} catch (CoreException e) {
System.err.println(e.getMessage());
}