diff --git a/.project b/.project
index 29ad569d7..47341d5ba 100644
--- a/.project
+++ b/.project
@@ -10,8 +10,14 @@
+
+ de.cognicrypt.crysl.handler.cryslbuilder
+
+
+ org.eclipse.jdt.core.javanature
+ de.cognicrypt.crysl.handler.cryslnature
diff --git a/plugins/de.cognicrypt.integrator.task/src/test/CryslTemplates/.project b/features/de.cognicrypt.integrator.task.feature/.project
similarity index 62%
rename from plugins/de.cognicrypt.integrator.task/src/test/CryslTemplates/.project
rename to features/de.cognicrypt.integrator.task.feature/.project
index 1b616b797..e5a8b4d44 100644
--- a/plugins/de.cognicrypt.integrator.task/src/test/CryslTemplates/.project
+++ b/features/de.cognicrypt.integrator.task.feature/.project
@@ -1,17 +1,17 @@
- CryslTemplates
+ de.cognicrypt.integrator.task.feature
- org.eclipse.jdt.core.javabuilder
+ org.eclipse.pde.FeatureBuilder
- org.eclipse.jdt.core.javanature
+ org.eclipse.pde.FeatureNature
diff --git a/features/de.cognicrypt.integrator.task.feature/build.properties b/features/de.cognicrypt.integrator.task.feature/build.properties
new file mode 100644
index 000000000..cc2efe007
--- /dev/null
+++ b/features/de.cognicrypt.integrator.task.feature/build.properties
@@ -0,0 +1,2 @@
+bin.includes = feature.xml
+src.includes = feature.xml
diff --git a/features/de.cognicrypt.integrator.task.feature/feature.xml b/features/de.cognicrypt.integrator.task.feature/feature.xml
new file mode 100644
index 000000000..4244412b2
--- /dev/null
+++ b/features/de.cognicrypt.integrator.task.feature/feature.xml
@@ -0,0 +1,117 @@
+
+
+
+
+ CogniCrypt is an Eclipse plugin that supports Java developers in using cryptographic APIs. It supports developers in two ways. First, it may generate code snippets for a number of programming tasks that involve cryptography, e.g., communication over a secure channel, data encryption, and long-term archiving. Second, it continuously runs a suite of static analyses in the background that check the developer's code for misuses of cryptographic APIs.
+
+
+
+ Copyrights reserved.
+
+
+
+ Eclipse Public License - v 2.0
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
+1. DEFINITIONS
+
+“Contribution” means:
+
+ a) in the case of the initial Contributor, the initial content Distributed under this Agreement, and
+ b) in the case of each subsequent Contributor:
+ i) changes to the Program, and
+ ii) additions to the Program;
+ where such changes and/or additions to the Program originate from and are Distributed by that particular Contributor. A Contribution “originates” from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include changes or additions to the Program that are not Modified Works.
+
+“Contributor” means any person or entity that Distributes the Program.
+
+“Licensed Patents” mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
+
+“Program” means the Contributions Distributed in accordance with this Agreement.
+
+“Recipient” means anyone who receives the Program under this Agreement or any Secondary License (as applicable), including Contributors.
+
+“Derivative Works” shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship.
+
+“Modified Works” shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof.
+
+“Distribute” means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy.
+
+“Source Code” means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+“Secondary License” means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor.
+2. GRANT OF RIGHTS
+
+ a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, Distribute and sublicense the Contribution of such Contributor, if any, and such Derivative Works.
+ b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in Source Code or other form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
+ c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to Distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
+ d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
+ e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3).
+
+3. REQUIREMENTS
+
+3.1 If a Contributor Distributes the Program in any form, then:
+
+ a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and
+ b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license:
+ i) effectively disclaims on behalf of all other Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
+ ii) effectively excludes on behalf of all other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
+ iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and
+ iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3.
+
+3.2 When the Program is Distributed as Source Code:
+
+ a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and
+ b) a copy of this Agreement must be included with each copy of the Program.
+
+3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability (‘notices’) contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices.
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (“Commercial Contributor”) hereby agrees to defend and indemnify every other Contributor (“Indemnified Contributor”) against any losses, damages and costs (collectively “Losses”) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be Distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to Distribute the Program (including its Contributions) under the new version.
+
+Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/features/de.cognicrypt.integrator.task.feature/pom.xml b/features/de.cognicrypt.integrator.task.feature/pom.xml
new file mode 100644
index 000000000..fada20f57
--- /dev/null
+++ b/features/de.cognicrypt.integrator.task.feature/pom.xml
@@ -0,0 +1,12 @@
+
+ 4.0.0
+ de.cognicrypt.integrator.task.feature
+ eclipse-feature
+
+ de.cognicrypt
+ de.cognicrypt.parent
+ 1.0.0-SNAPSHOT
+ ../../pom.xml
+
+
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/generator/CrySLBasedCodeGenerator.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/generator/CrySLBasedCodeGenerator.java
index a8f71b874..c433eb6f4 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/generator/CrySLBasedCodeGenerator.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/generator/CrySLBasedCodeGenerator.java
@@ -1412,4 +1412,4 @@ public boolean visit(ImportDeclaration node) {
return templateClass;
}
-}
+}
\ No newline at end of file
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/question/QuestionsJSONReader.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/question/QuestionsJSONReader.java
index cf0746ad9..724a64c27 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/question/QuestionsJSONReader.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/question/QuestionsJSONReader.java
@@ -13,6 +13,7 @@
package de.cognicrypt.codegenerator.question;
import java.io.BufferedReader;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
@@ -26,13 +27,13 @@
import de.cognicrypt.codegenerator.Activator;
import de.cognicrypt.codegenerator.tasks.Task;
import de.cognicrypt.codegenerator.utilities.CodeGenUtils;
+import de.cognicrypt.core.Constants;
/**
* This class reads all questions and answers of one task.
*
* @author Sarah Nadi
* @author Stefan Krueger
- *
*/
public class QuestionsJSONReader {
@@ -67,6 +68,7 @@ public List getQuestions(final String filePath) {
public List getPages(final String filePath) {
List pages = new ArrayList<>();
try {
+ Activator.getDefault().logError("JSON File " + filePath);
final BufferedReader reader = new BufferedReader(new FileReader(CodeGenUtils.getResourceFromWithin(filePath)));
final Gson gson = new Gson();
@@ -81,6 +83,54 @@ public List getPages(final String filePath) {
}
return pages;
}
+
+ /**
+ * This method reads all questions of one task using the file path to the question file.
+ *
+ * @param filePath
+ * path to the file that contains all questions for one task.
+ * @return questions
+ */
+ public List getCustomQuestions(final String filePath) {
+ List questions = new ArrayList<>();
+ try {
+ final BufferedReader reader = new BufferedReader(new FileReader(new File(Constants.ECLIPSE_CogniCrypt_RESOURCE_DIR + Constants.innerFileSeparator + filePath)));
+ final Gson gson = new Gson();
+ questions = gson.fromJson(reader, new TypeToken>() {}.getType());
+ checkReadQuestions(questions);
+ } catch (final FileNotFoundException e) {
+ Activator.getDefault().logError(e);
+ return null;
+ }
+ return questions;
+ }
+
+ /**
+ * This method reads all pages of one task using the file path to the JSON file.
+ *
+ * @param filePath
+ * Path to the file that contains all questions for one task.
+ * @return pages Return a list of all the pages in the JSON file.
+ */
+ public List getCustomPages(final String filePath) {
+ List pages = new ArrayList<>();
+ try {
+ Activator.getDefault().logError("JSON File " + filePath);
+ final BufferedReader reader = new BufferedReader(new FileReader(new File(Constants.ECLIPSE_CogniCrypt_RESOURCE_DIR + Constants.innerFileSeparator + filePath)));
+ final Gson gson = new Gson();
+
+ pages = gson.fromJson(reader, new TypeToken>() {}.getType());
+ // For some tasks, we don't have questions. So, we don't need to check them.
+ if (pages.size() > 0) {
+ checkReadPages(pages);
+ checkNextIDs(pages);
+ }
+ } catch (final FileNotFoundException e) {
+ Activator.getDefault().logError(e);
+ }
+ return pages;
+ }
+
/**
* This method reads all questions of one task.
@@ -92,6 +142,18 @@ public List getPages(final String filePath) {
public List getQuestions(final Task task) {
return getQuestions(task.getQuestionsJSONFile());
}
+
+ /**
+ * This method reads all custom questions of one task.
+ *
+ * @param task
+ * task whose questions should be read
+ * @return Questions
+ */
+ public List getCustomQuestions(final Task task) {
+ return getCustomQuestions(task.getQuestionsJSONFile());
+ }
+
/**
* This method reads all pages of one task.
@@ -103,6 +165,17 @@ public List getQuestions(final Task task) {
public List getPages(final Task task) {
return getPages(task.getQuestionsJSONFile());
}
+
+ /**
+ * This method reads all custom pages of one task.
+ *
+ * @param task
+ * task whose questions should be read
+ * @return Pages
+ */
+ public List getCustomPages(final Task task) {
+ return getCustomPages(task.getQuestionsJSONFile());
+ }
/**
* Check the validity of the pages and the questions contained in them.
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/tasks/TaskJSONReader.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/tasks/TaskJSONReader.java
index 67110aafe..43a55299f 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/tasks/TaskJSONReader.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/tasks/TaskJSONReader.java
@@ -13,6 +13,7 @@
package de.cognicrypt.codegenerator.tasks;
import java.io.BufferedReader;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
@@ -55,7 +56,29 @@ public static List getTasks() {
t.setCodeTemplate(Constants.codeTemplateFolder + t.getName().toLowerCase());
}
}
+
+ File customTasksFile = new File(Constants.customjsonTaskFile);
+
+ if(customTasksFile.exists()) {
+ final BufferedReader reader1 = new BufferedReader(new FileReader(customTasksFile));
+
+ List customTasks = gson.fromJson(reader1, new TypeToken>() {}.getType());
+ TaskJSONReader.tasks.addAll(customTasks);
+ reader1.close();
+ for (Task t : customTasks) {
+ t.setQuestionsJSONFile(Constants.localrsrcPath + "TaskDesc" + Constants.innerFileSeparator + t.getName() + ".json");
+ t.setAdditionalResources(Constants.localrsrcPath + "AdditionalResources" + Constants.innerFileSeparator + t.getName());
+
+ if (t.getCodeGen() == CodeGenerators.XSL) {
+ t.setCodeTemplate(Constants.ECLIPSE_LOC_TEMP_DIR + Constants.innerFileSeparator + "Tasks" + Constants.innerFileSeparator + "XSLTemplates" + Constants.innerFileSeparator + t.getName() + ".xsl");
+ t.setModelFile(Constants.ECLIPSE_LOC_TEMP_DIR + Constants.innerFileSeparator + "ClaferModel" + Constants.innerFileSeparator + t.getName() + ".js");
+ } else if (t.getCodeGen() == CodeGenerators.CrySL) {
+ t.setCodeTemplate(Constants.ECLIPSE_LOC_TEMP_DIR + Constants.innerFileSeparator + t.getName());
+ }
+ }
+ }
+
} catch (final FileNotFoundException e) {
Activator.getDefault().logError(e);
} catch (final IOException e) {
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/AltConfigWizard.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/AltConfigWizard.java
index e71ec04f5..cfa3effa2 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/AltConfigWizard.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/AltConfigWizard.java
@@ -1,309 +1,317 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v. 2.0 which is available at
- * http://www.eclipse.org/legal/epl-2.0.
- *
- * SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.codegenerator.wizard;
-
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map.Entry;
-
-import javax.swing.JDialog;
-import javax.swing.JOptionPane;
-import javax.swing.UIManager;
-import javax.swing.UnsupportedLookAndFeelException;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-
-import de.cognicrypt.codegenerator.Activator;
-import de.cognicrypt.codegenerator.featuremodel.clafer.InstanceGenerator;
-import de.cognicrypt.codegenerator.generator.CodeGenerator;
-import de.cognicrypt.codegenerator.generator.CrySLBasedCodeGenerator;
-import de.cognicrypt.codegenerator.generator.XSLBasedGenerator;
-import de.cognicrypt.codegenerator.question.Answer;
-import de.cognicrypt.codegenerator.question.Question;
-import de.cognicrypt.codegenerator.tasks.Task;
-import de.cognicrypt.codegenerator.utilities.CodeGenUtils;
-import de.cognicrypt.codegenerator.wizard.beginner.BeginnerModeQuestionnaire;
-import de.cognicrypt.codegenerator.wizard.beginner.BeginnerTaskQuestionPage;
-import de.cognicrypt.core.Constants;
-import de.cognicrypt.core.Constants.CodeGenerators;
-
-public class AltConfigWizard extends Wizard {
-
- private Task selectedTask;
- private HashMap constraints;
- private BeginnerModeQuestionnaire beginnerQuestions;
-
- public AltConfigWizard() {
- super();
- // Set the Look and Feel of the application to the operating
- // system's look and feel.
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
- Activator.getDefault().logError(e);
- }
- setWindowTitle("CogniCrypt");
-
- final ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin("de.cognicrypt.codegenerator", "platform:/plugin/de.cognicrypt.core/icons/cognicrypt-medium.png ");
- setDefaultPageImageDescriptor(image);
- this.constraints = new LinkedHashMap<>();
- }
-
- @Override
- public void addPages() {
- setForcePreviousAndNextButtons(true);
- addPage(new TaskSelectionPage());
- }
-
- @Override
- public boolean canFinish() {
- final IWizardPage page = getContainer().getCurrentPage();
- return page instanceof LocatorPage && page.isPageComplete();
-
- }
-
- private boolean checkifInUpdateRound() {
- boolean updateRound = false;
- final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
- for (final StackTraceElement el : stack) {
- if (el.getMethodName().contains("updateButtons")) {
- updateRound = true;
- break;
- }
- }
- return updateRound;
- }
-
- /**
- * This method returns the next page. If current page is task list or any but the last question page, the first/next question page is returned. If the current page is the last
- * question page, the instance list page is returned.
- *
- * @param currentPage
- * current page
- * @return either next question page or instance list page
- */
- @Override
- public IWizardPage getNextPage(final IWizardPage currentPage) {
- if (checkifInUpdateRound()) {
- return currentPage;
- }
- if (currentPage instanceof TaskSelectionPage) {
- selectedTask = ((TaskSelectionPage) currentPage).getSelectedTask();
- this.beginnerQuestions = new BeginnerModeQuestionnaire(selectedTask, selectedTask.getQuestionsJSONFile());
- // It is possible that now questions are within a BeginnerModeQuestionnaire
-
- if (this.beginnerQuestions.hasPages()) {
- final BeginnerTaskQuestionPage questionPage = new BeginnerTaskQuestionPage(this.beginnerQuestions.nextPage(), this.beginnerQuestions.getTask(), null);
- addPage(questionPage);
- return questionPage;
- } else {
- return addLocatorPage();
- }
- }
-
- //Only case that is left: BeginnerTaskQuestionPage
- final BeginnerTaskQuestionPage curQuestionPage = (BeginnerTaskQuestionPage) currentPage;
- final HashMap curQuestionAnswerMap = curQuestionPage.getMap();
-
- for (final Entry entry : curQuestionAnswerMap.entrySet()) {
- this.constraints.put(entry.getKey(), entry.getValue());
- }
-
- final int nextPageid = curQuestionPage.getPageNextID();
- if (this.beginnerQuestions.hasMorePages() && nextPageid > -1) {
- final BeginnerTaskQuestionPage questionPage = new BeginnerTaskQuestionPage(this.beginnerQuestions.getPageByID(nextPageid), this.beginnerQuestions.getTask(), null);
- addPage(questionPage);
- return questionPage;
- } else {
- CodeGenerators generator = selectedTask.getCodeGen();
- if (generator == CodeGenerators.CrySL) {
- String selectedTemplate = constructTemplateName();
- selectedTask.setCodeTemplate(selectedTemplate);
- return addLocatorPage();
- } else if (generator == CodeGenerators.XSL) {
- final InstanceGenerator instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
- .getAbsolutePath(), "c0_" + selectedTask.getName(), selectedTask.getDescription());
-
- instanceGenerator.generateInstances(this.constraints);
-
- if (instanceGenerator.getNoOfInstances() > 0) {
- return addLocatorPage();
- } else {
- MessageDialog.openError(new Shell(), "Error", Constants.NO_POSSIBLE_COMBINATIONS_BEGINNER);
- }
- }
- }
- return currentPage;
- }
-
- public String constructTemplateName() {
- String selectedTemplate = selectedTask.getCodeTemplate();
- for (Answer resp : this.constraints.values()) {
- if (resp.getOption() != null) {
- selectedTemplate += resp.getOption();
- }
- }
- return selectedTemplate;
- }
-
- public void addConstraints(HashMap constraint) {
- this.constraints.putAll(constraint);
- }
-
- public void setSelectedTask(Task selectedTask) {
- this.selectedTask = selectedTask;
- }
-
- private IWizardPage addLocatorPage() {
- final LocatorPage locatorPage = new LocatorPage("Locator");
- addPage(locatorPage);
- return locatorPage;
- }
-
- /**
- * This method returns previous page. If currentPage is the first question, the task list page is returned. If it is any other question page or the instance list page, the
- * previous question page is returned.
- *
- * @param currentPage
- * current page, either instance list page or question page
- * @return either previous question or task selection page
- */
- @Override
- public IWizardPage getPreviousPage(final IWizardPage currentPage) {
- if (!checkifInUpdateRound()) {
- final IWizardPage[] pages = getPages();
- for (int i = 0; i < pages.length; i++) {
- if (currentPage.equals(pages[i])) {
- if (currentPage instanceof BeginnerTaskQuestionPage) {
- ((BeginnerTaskQuestionPage) currentPage).setPageInactive();
- }
- final BeginnerTaskQuestionPage prevPage = (BeginnerTaskQuestionPage) pages[i - 1];
- for (final Entry quesAns : prevPage.getSelection().entrySet()) {
- this.constraints.remove(quesAns.getKey());
- }
- return prevPage;
- }
- }
- }
- if (currentPage instanceof LocatorPage && selectedTask.getCodeGen() == CodeGenerators.CrySL) {
- resetAnswers();
- }
-
- return super.getPreviousPage(currentPage);
- }
-
- public void resetAnswers() {
- int substringLength = 0;
- for (Answer response : this.constraints.values()) {
- if (response.getOption() != null) {
- substringLength += response.getOption().length();
- }
- }
- String oldCodeTemplate = selectedTask.getCodeTemplate();
- selectedTask.setCodeTemplate(oldCodeTemplate.substring(0, oldCodeTemplate.length() - substringLength));
- }
-
- /**
- * This method is called once the user selects an instance. It writes the instance to an xml file and calls the code generation.
- *
- * @return true/false if writing instance file and code generation are (un)successful
- */
- @Override
- public boolean performFinish() {
- boolean ret = false;
- final CodeGenerators genKind = selectedTask.getCodeGen();
- CodeGenerator codeGenerator = null;
- String additionalResources = selectedTask.getAdditionalResources();
- final LocatorPage currentPage = (LocatorPage) getContainer().getCurrentPage();
- IResource targetFile = (IResource) currentPage.getSelectedResource().getFirstElement();
-
- String taskName = selectedTask.getName();
- JOptionPane optionPane = new JOptionPane("CogniCrypt is now generating code that implements " + selectedTask.getDescription() + "\ninto file " + ((targetFile != null)
- ? targetFile.getName()
- : "Output.java") + ". This should take no longer than a few seconds.", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
- JDialog waitingDialog = optionPane.createDialog("Generating Code");
- waitingDialog.setModal(false);
- waitingDialog.setVisible(true);
- Configuration chosenConfig = null;
- try {
- String codeTemplate = selectedTask.getCodeTemplate();
- switch (genKind) {
- case CrySL:
- CrySLBasedCodeGenerator.clearParameterCache();
- File templateFile = CodeGenUtils.getResourceFromWithin(codeTemplate).listFiles()[0];
- codeGenerator = new CrySLBasedCodeGenerator(targetFile);
- String projectRelDir = Constants.outerFileSeparator + codeGenerator.getDeveloperProject()
- .getSourcePath() + Constants.outerFileSeparator + Constants.PackageName + Constants.outerFileSeparator;
- String pathToTemplateFile = projectRelDir + templateFile.getName();
- String resFileOSPath = "";
-
- IPath projectPath = targetFile.getProject().getRawLocation();
- if (projectPath == null) {
- projectPath = targetFile.getProject().getLocation();
- }
- resFileOSPath = projectPath.toOSString() + pathToTemplateFile;
-
- Files.createDirectories(Paths.get(projectPath.toOSString() + projectRelDir));
- Files.copy(templateFile.toPath(), Paths.get(resFileOSPath), StandardCopyOption.REPLACE_EXISTING);
- codeGenerator.getDeveloperProject().refresh();
-
- resetAnswers();
- chosenConfig = new CrySLConfiguration(resFileOSPath, ((CrySLBasedCodeGenerator) codeGenerator).setUpTemplateClass(pathToTemplateFile, templateFile), this.constraints, selectedTask.getName(), codeGenerator.getDeveloperProject());
- break;
- case XSL:
- this.constraints = (this.constraints != null) ? this.constraints : new HashMap<>();
- final InstanceGenerator instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
- .getAbsolutePath(), "c0_" + taskName, selectedTask.getDescription());
- instanceGenerator.generateInstances(this.constraints);
-
- // Initialize Code Generation
- codeGenerator = new XSLBasedGenerator(targetFile, codeTemplate);
- chosenConfig = new XSLConfiguration(instanceGenerator.getInstances().values().iterator()
- .next(), this.constraints, codeGenerator.getDeveloperProject().getProjectPath() + Constants.innerFileSeparator + Constants.pathToClaferInstanceFile, selectedTask.getName(), codeGenerator.getDeveloperProject());
- break;
- default:
- return false;
- }
- ret = codeGenerator.generateCodeTemplates(chosenConfig, additionalResources);
-
- try {
- codeGenerator.getDeveloperProject().refresh();
- } catch (CoreException e1) {
- Activator.getDefault().logError(e1, Constants.CodeGenerationErrorMessage);
- }
-
- } catch (Exception ex) {
- Activator.getDefault().logError(ex, Constants.CodeGenerationErrorMessage);
- } finally {
- waitingDialog.setVisible(false);
- }
-
- waitingDialog.setVisible(false);
- return ret;
- }
-
- public HashMap getConstraints() {
- return this.constraints;
- }
-
-}
+/********************************************************************************
+ * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v. 2.0 which is available at
+ * http://www.eclipse.org/legal/epl-2.0.
+ *
+ * SPDX-License-Identifier: EPL-2.0
+ ********************************************************************************/
+
+package de.cognicrypt.codegenerator.wizard;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map.Entry;
+
+import javax.swing.JDialog;
+import javax.swing.JOptionPane;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
+
+import org.eclipse.core.resources.IResource;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.wizard.IWizardPage;
+import org.eclipse.jface.wizard.Wizard;
+import org.eclipse.swt.widgets.Shell;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+
+import de.cognicrypt.codegenerator.Activator;
+import de.cognicrypt.codegenerator.featuremodel.clafer.InstanceGenerator;
+import de.cognicrypt.codegenerator.generator.CodeGenerator;
+import de.cognicrypt.codegenerator.generator.CrySLBasedCodeGenerator;
+import de.cognicrypt.codegenerator.generator.XSLBasedGenerator;
+import de.cognicrypt.codegenerator.question.Answer;
+import de.cognicrypt.codegenerator.question.Question;
+import de.cognicrypt.codegenerator.tasks.Task;
+import de.cognicrypt.codegenerator.utilities.CodeGenUtils;
+import de.cognicrypt.codegenerator.wizard.beginner.BeginnerModeQuestionnaire;
+import de.cognicrypt.codegenerator.wizard.beginner.BeginnerTaskQuestionPage;
+import de.cognicrypt.core.Constants;
+import de.cognicrypt.core.Constants.CodeGenerators;
+
+public class AltConfigWizard extends Wizard {
+
+ private Task selectedTask;
+ private HashMap constraints;
+ private BeginnerModeQuestionnaire beginnerQuestions;
+
+ public AltConfigWizard() {
+ super();
+ // Set the Look and Feel of the application to the operating
+ // system's look and feel.
+ try {
+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
+ Activator.getDefault().logError(e);
+ }
+ setWindowTitle("CogniCrypt");
+
+ final ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin("de.cognicrypt.codegenerator", "platform:/plugin/de.cognicrypt.core/icons/cognicrypt-medium.png ");
+ setDefaultPageImageDescriptor(image);
+ this.constraints = new LinkedHashMap<>();
+ }
+
+ @Override
+ public void addPages() {
+ setForcePreviousAndNextButtons(true);
+ addPage(new TaskSelectionPage());
+ }
+
+ @Override
+ public boolean canFinish() {
+ final IWizardPage page = getContainer().getCurrentPage();
+ return page instanceof LocatorPage && page.isPageComplete();
+
+ }
+
+ private boolean checkifInUpdateRound() {
+ boolean updateRound = false;
+ final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
+ for (final StackTraceElement el : stack) {
+ if (el.getMethodName().contains("updateButtons")) {
+ updateRound = true;
+ break;
+ }
+ }
+ return updateRound;
+ }
+
+ /**
+ * This method returns the next page. If current page is task list or any but the last question page, the first/next question page is returned. If the current page is the last
+ * question page, the instance list page is returned.
+ *
+ * @param currentPage
+ * current page
+ * @return either next question page or instance list page
+ */
+ @Override
+ public IWizardPage getNextPage(final IWizardPage currentPage) {
+ if (checkifInUpdateRound()) {
+ return currentPage;
+ }
+ if (currentPage instanceof TaskSelectionPage) {
+ selectedTask = ((TaskSelectionPage) currentPage).getSelectedTask();
+ this.beginnerQuestions = new BeginnerModeQuestionnaire(selectedTask, selectedTask.getQuestionsJSONFile());
+ // It is possible that now questions are within a BeginnerModeQuestionnaire
+
+ if (this.beginnerQuestions.hasPages()) {
+ final BeginnerTaskQuestionPage questionPage = new BeginnerTaskQuestionPage(this.beginnerQuestions.nextPage(), this.beginnerQuestions.getTask(), null);
+ addPage(questionPage);
+ return questionPage;
+ } else {
+ return addLocatorPage();
+ }
+ }
+
+ //Only case that is left: BeginnerTaskQuestionPage
+ final BeginnerTaskQuestionPage curQuestionPage = (BeginnerTaskQuestionPage) currentPage;
+ final HashMap curQuestionAnswerMap = curQuestionPage.getMap();
+
+ for (final Entry entry : curQuestionAnswerMap.entrySet()) {
+ this.constraints.put(entry.getKey(), entry.getValue());
+ }
+
+ final int nextPageid = curQuestionPage.getPageNextID();
+ if (this.beginnerQuestions.hasMorePages() && nextPageid > -1) {
+ final BeginnerTaskQuestionPage questionPage = new BeginnerTaskQuestionPage(this.beginnerQuestions.getPageByID(nextPageid), this.beginnerQuestions.getTask(), null);
+ addPage(questionPage);
+ return questionPage;
+ } else {
+ CodeGenerators generator = selectedTask.getCodeGen();
+ if (generator == CodeGenerators.CrySL) {
+ String selectedTemplate = constructTemplateName();
+ selectedTask.setCodeTemplate(selectedTemplate);
+ return addLocatorPage();
+ } else if (generator == CodeGenerators.XSL) {
+ final InstanceGenerator instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
+ .getAbsolutePath(), "c0_" + selectedTask.getName(), selectedTask.getDescription());
+
+ instanceGenerator.generateInstances(this.constraints);
+
+ if (instanceGenerator.getNoOfInstances() > 0) {
+ return addLocatorPage();
+ } else {
+ MessageDialog.openError(new Shell(), "Error", Constants.NO_POSSIBLE_COMBINATIONS_BEGINNER);
+ }
+ }
+ }
+ return currentPage;
+ }
+
+ public String constructTemplateName() {
+ String selectedTemplate = selectedTask.getCodeTemplate();
+ for (Answer resp : this.constraints.values()) {
+ if (resp.getOption() != null) {
+ selectedTemplate += resp.getOption();
+ }
+ }
+ return selectedTemplate;
+ }
+
+ public void addConstraints(HashMap constraint) {
+ this.constraints.putAll(constraint);
+ }
+
+ public void setSelectedTask(Task selectedTask) {
+ this.selectedTask = selectedTask;
+ }
+
+ private IWizardPage addLocatorPage() {
+ final LocatorPage locatorPage = new LocatorPage("Locator");
+ addPage(locatorPage);
+ return locatorPage;
+ }
+
+ /**
+ * This method returns previous page. If currentPage is the first question, the task list page is returned. If it is any other question page or the instance list page, the
+ * previous question page is returned.
+ *
+ * @param currentPage
+ * current page, either instance list page or question page
+ * @return either previous question or task selection page
+ */
+ @Override
+ public IWizardPage getPreviousPage(final IWizardPage currentPage) {
+ if (!checkifInUpdateRound()) {
+ final IWizardPage[] pages = getPages();
+ for (int i = 0; i < pages.length; i++) {
+ if (currentPage.equals(pages[i])) {
+ if (currentPage instanceof BeginnerTaskQuestionPage) {
+ ((BeginnerTaskQuestionPage) currentPage).setPageInactive();
+ }
+ final BeginnerTaskQuestionPage prevPage = (BeginnerTaskQuestionPage) pages[i - 1];
+ for (final Entry quesAns : prevPage.getSelection().entrySet()) {
+ this.constraints.remove(quesAns.getKey());
+ }
+ return prevPage;
+ }
+ }
+ }
+ if (currentPage instanceof LocatorPage && selectedTask.getCodeGen() == CodeGenerators.CrySL) {
+ resetAnswers();
+ }
+
+ return super.getPreviousPage(currentPage);
+ }
+
+ public void resetAnswers() {
+ int substringLength = 0;
+ for (Answer response : this.constraints.values()) {
+ if (response.getOption() != null) {
+ substringLength += response.getOption().length();
+ }
+ }
+ String oldCodeTemplate = selectedTask.getCodeTemplate();
+ selectedTask.setCodeTemplate(oldCodeTemplate.substring(0, oldCodeTemplate.length() - substringLength));
+ }
+
+ /**
+ * This method is called once the user selects an instance. It writes the instance to an xml file and calls the code generation.
+ *
+ * @return true/false if writing instance file and code generation are (un)successful
+ */
+ @Override
+ public boolean performFinish() {
+ boolean ret = false;
+ final CodeGenerators genKind = selectedTask.getCodeGen();
+ CodeGenerator codeGenerator = null;
+ String additionalResources = selectedTask.getAdditionalResources();
+ final LocatorPage currentPage = (LocatorPage) getContainer().getCurrentPage();
+ IResource targetFile = (IResource) currentPage.getSelectedResource().getFirstElement();
+
+ String taskName = selectedTask.getName();
+ JOptionPane optionPane = new JOptionPane("CogniCrypt is now generating code that implements " + selectedTask.getDescription() + "\ninto file " + ((targetFile != null)
+ ? targetFile.getName()
+ : "Output.java") + ". This should take no longer than a few seconds.", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION, null, new Object[] {}, null);
+ JDialog waitingDialog = optionPane.createDialog("Generating Code");
+ waitingDialog.setModal(false);
+ waitingDialog.setVisible(true);
+ Configuration chosenConfig = null;
+ try {
+ String codeTemplate = selectedTask.getCodeTemplate();
+ switch (genKind) {
+ case CrySL:
+ CrySLBasedCodeGenerator.clearParameterCache();
+ File templateFile;
+ if(codeTemplate.startsWith(Constants.ECLIPSE_LOC_TEMP_DIR)) {
+ templateFile = new File(codeTemplate).listFiles()[0];
+ }else {
+ templateFile = CodeGenUtils.getResourceFromWithin(codeTemplate).listFiles()[0];
+ }
+ codeGenerator = new CrySLBasedCodeGenerator(targetFile);
+ String projectRelDir = Constants.outerFileSeparator + codeGenerator.getDeveloperProject()
+ .getSourcePath() + Constants.outerFileSeparator + Constants.PackageName + Constants.outerFileSeparator;
+ String pathToTemplateFile = projectRelDir + templateFile.getName();
+ String resFileOSPath = "";
+
+ IPath projectPath = targetFile.getProject().getRawLocation();
+ if (projectPath == null) {
+ projectPath = targetFile.getProject().getLocation();
+ }
+ resFileOSPath = projectPath.toOSString() + pathToTemplateFile;
+
+ Files.createDirectories(Paths.get(projectPath.toOSString() + projectRelDir));
+ Files.copy(templateFile.toPath(), Paths.get(resFileOSPath), StandardCopyOption.REPLACE_EXISTING);
+ codeGenerator.getDeveloperProject().refresh();
+
+ resetAnswers();
+ chosenConfig = new CrySLConfiguration(resFileOSPath, ((CrySLBasedCodeGenerator) codeGenerator).setUpTemplateClass(pathToTemplateFile, templateFile), this.constraints, selectedTask.getName(), codeGenerator.getDeveloperProject()); break;
+ case XSL:
+ this.constraints = (this.constraints != null) ? this.constraints : new HashMap<>();
+ InstanceGenerator instanceGenerator;
+ if(codeTemplate.startsWith(Constants.ECLIPSE_LOC_TEMP_DIR)) {
+ instanceGenerator = new InstanceGenerator(selectedTask.getModelFile(), "c0_" + taskName, selectedTask.getDescription());
+ }else {
+ instanceGenerator = new InstanceGenerator(CodeGenUtils.getResourceFromWithin(selectedTask.getModelFile())
+ .getAbsolutePath(), "c0_" + taskName, selectedTask.getDescription());
+ }
+ instanceGenerator.generateInstances(this.constraints);
+
+ // Initialize Code Generation
+ codeGenerator = new XSLBasedGenerator(targetFile, codeTemplate);
+ chosenConfig = new XSLConfiguration(instanceGenerator.getInstances().values().iterator()
+ .next(), this.constraints, codeGenerator.getDeveloperProject().getProjectPath() + Constants.innerFileSeparator + Constants.pathToClaferInstanceFile, selectedTask.getName(), codeGenerator.getDeveloperProject());
+ break;
+ default:
+ return false;
+ }
+ ret = codeGenerator.generateCodeTemplates(chosenConfig, additionalResources);
+
+ try {
+ codeGenerator.getDeveloperProject().refresh();
+ } catch (CoreException e1) {
+ Activator.getDefault().logError(e1, Constants.CodeGenerationErrorMessage);
+ }
+
+ } catch (Exception ex) {
+ Activator.getDefault().logError(ex, Constants.CodeGenerationErrorMessage);
+ } finally {
+ waitingDialog.setVisible(false);
+ }
+
+ return ret;
+ }
+
+ public HashMap getConstraints() {
+ return this.constraints;
+ }
+
+}
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/TaskSelectionPage.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/TaskSelectionPage.java
index 3875937a4..e51fd6e1c 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/TaskSelectionPage.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/TaskSelectionPage.java
@@ -73,7 +73,7 @@ public void createControl(final Composite parent) {
gl.verticalSpacing = -6;
this.container.setLayout(gl);
- new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
+ //new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
new Label(this.container, SWT.NONE);
final Label useCaseDescriptionLabel = new Label(this.container, SWT.WRAP);
final GridData gd_selectProjectLabel = new GridData(SWT.FILL, SWT.FILL, false, false, 1, tasks.size() + 1);
@@ -141,7 +141,8 @@ private Image loadImage(final String image) {
if (resolvedURL != null) {
resolvedURI = new URI(resolvedURL.getProtocol(), resolvedURL.getPath(), null);
} else {
- resolvedURI = FileLocator.resolve(entry).toURI();
+ //resolvedURI = FileLocator.resolve(entry).toURI();
+ return new Image(PlatformUI.getWorkbench().getDisplay(), new FileInputStream(new File(Constants.ECLIPSE_LOC_IMG_DIR + "/" + image + ".png")));
}
return new Image(PlatformUI.getWorkbench().getDisplay(), new FileInputStream(new File(resolvedURI)));
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/beginner/BeginnerModeQuestionnaire.java b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/beginner/BeginnerModeQuestionnaire.java
index 3b82226b4..4f383507f 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/beginner/BeginnerModeQuestionnaire.java
+++ b/plugins/de.cognicrypt.codegenerator/src/main/java/de/cognicrypt/codegenerator/wizard/beginner/BeginnerModeQuestionnaire.java
@@ -18,6 +18,7 @@
import de.cognicrypt.codegenerator.question.Question;
import de.cognicrypt.codegenerator.question.QuestionsJSONReader;
import de.cognicrypt.codegenerator.tasks.Task;
+import de.cognicrypt.core.Constants;
public class BeginnerModeQuestionnaire {
@@ -33,7 +34,11 @@ public class BeginnerModeQuestionnaire {
*/
public BeginnerModeQuestionnaire(final Task task, final String filePath) {
this.task = task;
- this.pageList = (new QuestionsJSONReader()).getPages(filePath);
+ if(filePath.startsWith(Constants.LOCAL_JSON_FILE_DIRECTORY_PATH)) {
+ this.pageList = (new QuestionsJSONReader()).getCustomPages(filePath);
+ }else {
+ this.pageList = (new QuestionsJSONReader()).getPages(filePath);
+ }
this.pageID = 0;
this.questionList = null;
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/TaskDesc/ABYQuestions.json b/plugins/de.cognicrypt.codegenerator/src/main/resources/TaskDesc/ABYQuestions.json
deleted file mode 100644
index b6f2aaf8d..000000000
--- a/plugins/de.cognicrypt.codegenerator/src/main/resources/TaskDesc/ABYQuestions.json
+++ /dev/null
@@ -1,175 +0,0 @@
-[{
- "id": "0",
- "helpID": "MultiPartyComputation_Page0",
- "content": [{
- "id": "0",
- "note": "",
- "element": "combo",
- "questionText": "Where are you implementing?",
- "answers": [{
- "value": "Server-side",
- "codeDependencies": [{
- "option": "server",
- "value": "true"
- }],
- "nextID": "2"
- },
- {
- "value": "Client-side",
- "codeDependencies": [{
- "option": "server",
- "value": "false"
- }],
- "defaultAnswer": true,
- "nextID": "1"
- }
- ]
- }]
- },
- {
- "id": "1",
- "helpID": "MultiPartyComputation_Page1",
- "content": [{
- "id": "1",
- "note": "",
- "element": "radio",
- "questionText": "Do you know ip and port of the server?",
- "answers": [{
- "value": "Yes",
- "codeDependencies": [],
- "nextID": "2"
- },
- {
- "value": "No",
- "codeDependencies": [],
- "defaultAnswer": true,
- "nextID": "3"
- }
- ]
- }]
- },
- {
- "id": "2",
- "helpID": "MultiPartyComputation_Page2",
- "content": [{
- "id": "2",
- "note": "",
- "tooltip": "Example : 216.3.128.12",
- "element": "text",
- "textType":"Ip address",
- "questionText": "Please enter the server's ip",
- "answers": [{
- "value": "",
- "codeDependencies": [{
- "option": "host",
- "value": ""
- }],
- "defaultAnswer": true
- }]
- },
- {
- "id": "3",
- "note": "",
- "tooltip": "Example : 65534",
- "element": "text",
- "textType":"Port number",
- "questionText": "Please enter the port of the server",
- "answers": [{
- "value": "",
- "codeDependencies": [{
- "option": "port",
- "value": ""
- }],
- "defaultAnswer": true
- }]
- }],
- "nextID": "3"
- },
- {
- "id": "3",
- "helpID": "MultiPartyComputation_Page3",
- "content": [{
- "id": "4",
- "note": "\u2022 Euclidean Distance: The distance between the two parties is identified without disclosing each other's data.\n\u2022 Millionaire's Comparison: The two parties enter a number and receive the name of the party who entered the bigger one, without revealing each other's inputs. ",
- "element": "combo",
- "questionText": "Which Multi-Party Computation scenario do you want to implement?",
- "answers": [{
- "value": "Millionaire's Comparison",
- "claferDependencies": [{
- "algorithm": "aby",
- "value": "Millionaire",
- "operator": "="
- }],
- "nextID": "-1"
- },
- {
- "value": "Euclidean Distance",
- "claferDependencies": [{
- "algorithm": "aby",
- "value": "Euclid",
- "operator": "="
- }],
- "defaultAnswer": true,
- "nextID": "4"
- }
- ]
- }]
- },
- {
- "id": "4",
- "helpID": "MultiPartyComputation_Page4",
- "content": [{
- "id": "5",
- "note": "",
- "element": "scale",
- "questionText": "What is the preferred security level",
- "answers": [{
- "value": "Less Secure",
- "claferDependencies": [{
- "algorithm": "security",
- "value": "80",
- "operator": "="
- }],
- "nextID": "-1"
- },
- {
- "value": "Medium",
- "claferDependencies": [{
- "algorithm": "security",
- "value": "112",
- "operator": "="
- }],
- "nextID": "-1"
- },
- {
- "value": "Secure",
- "claferDependencies": [{
- "algorithm": "security",
- "value": "128",
- "operator": "="
- }],
- "defaultAnswer": true,
- "nextID": "-1"
- },
- {
- "value": "Very Secure",
- "claferDependencies": [{
- "algorithm": "security",
- "value": "192",
- "operator": "="
- }],
- "nextID": "-1"
- },
- {
- "value": "Very Very Secure",
- "claferDependencies": [{
- "algorithm": "security",
- "value": "256",
- "operator": "="
- }],
- "nextID": "-1"
- }
- ]
- }]
- }
-]
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/LongTermArchiving.xsl b/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/LongTermArchiving.xsl
similarity index 100%
rename from plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/LongTermArchiving.xsl
rename to plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/LongTermArchiving.xsl
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/SECMUPACOMP.xsl b/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/SECMUPACOMP.xsl
similarity index 100%
rename from plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/SECMUPACOMP.xsl
rename to plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/SECMUPACOMP.xsl
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/SecureCommunication.xsl b/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/SecureCommunication.xsl
similarity index 100%
rename from plugins/de.cognicrypt.codegenerator/src/main/resources/XSLTemplates/SecureCommunication.xsl
rename to plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/XSLTemplates/SecureCommunication.xsl
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/tasks.json b/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/tasks.json
index 8a12df622..f3d807bef 100644
--- a/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/tasks.json
+++ b/plugins/de.cognicrypt.codegenerator/src/main/resources/Tasks/tasks.json
@@ -38,17 +38,5 @@
"image": "mpc",
"codeGen": "XSL",
"isSelected": false
- },
- {
- "name": "TestCryslTask",
- "description": "TestCryslTask",
- "taskDescription": "description of task",
- "image": "TestCryslTask",
- "codeGen": "CrySL",
- "additionalResources": "",
- "questionsJSONFile": "src/main/resources/TaskDesc/TestCryslTask.json",
- "modelFile": "",
- "codeTemplate": "src/main/resources/XSLTemplates/TestCryslTask.xsl",
- "isSelected": false
}
]
\ No newline at end of file
diff --git a/plugins/de.cognicrypt.codegenerator/src/main/resources/images/TestCryslTask.png b/plugins/de.cognicrypt.core/icons/task-default-icon.png
similarity index 100%
rename from plugins/de.cognicrypt.codegenerator/src/main/resources/images/TestCryslTask.png
rename to plugins/de.cognicrypt.core/icons/task-default-icon.png
diff --git a/plugins/de.cognicrypt.core/src/de/cognicrypt/core/Constants.java b/plugins/de.cognicrypt.core/src/de/cognicrypt/core/Constants.java
index d42da8fbc..91102a736 100644
--- a/plugins/de.cognicrypt.core/src/de/cognicrypt/core/Constants.java
+++ b/plugins/de.cognicrypt.core/src/de/cognicrypt/core/Constants.java
@@ -7,7 +7,12 @@
package de.cognicrypt.core;
+import java.io.File;
+
+import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
+import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
+import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
@@ -58,6 +63,7 @@ public static enum CG {
public static final String MavenNatureID = "org.eclipse.m2e.core.maven2Nature";
public static final String rsrcPath = "src" + Constants.innerFileSeparator + "main" + Constants.innerFileSeparator + "resources" + Constants.innerFileSeparator;
+ public static final String localrsrcPath = "res" + Constants.innerFileSeparator;
public static final String providerPath = Constants.rsrcPath + "AdditionalResources" + Constants.innerFileSeparator + "Provider";
// JSON task file
@@ -181,13 +187,6 @@ public static enum CG {
public static final String ERROR_MESSAGE_NO_PROJECT = "There is no Java project in your workspace. Please create one and restart CogniCrypt.";
public static final String ERROR_MESSAGE_NO_ADDITIONAL_RES_DIRECTORY = "No directory for additional resources found.";
public static final String ERROR_MESSAGE_NO_FILE = "No file found";
- public static final String ERROR = "ERROR: ";
- public static final String ERROR_MESSAGE_BLANK_FILE_NAME = "Please choose a valid file.";
- public static final String ERROR_MESSAGE_UNABLE_TO_READ_FILE = "There is a problem with the selected file. Please choose a valid one.";
- public static final String ERROR_MESSAGE_DUPLICATE_TASK_NAME = "A task with this name already exists.";
- public static final String MESSAGE_REQUIRED_FIELD = "This is a required field.";
- public static final String ERROR_MESSAGE_BLANK_TASK_NAME = "The Task name cannot be empty. Please enter a valid name for the Task.";
- public static final String ERROR_CANNOT_REMOVE_PACKAGE = "The package could not be removed.";
public static final String ERROR_CANNOT_FIND_NODE = "The requested node could not be found";
public static final String ERROR_CANNOT_FILE_TO_BYTEARRAY = "Error occured when passing a Java file into a byte array.";
@@ -269,226 +268,140 @@ public static enum CG {
public static final String PASSWORD = "Password";
public static final String PORT_NUMBER = "Port number";
public static final String IP_ADDRESS = "Ip address";
+
// Flags for default project selection
public static boolean WizardActionFromContextMenuFlag = false;
- // Constants for the Task Integrator Wizard.
- // Page constants
-
- public static final String PAGE_NAME_FOR_MODE_OF_WIZARD = "pageForChoiceOfModeOfWizard";
- public static final String PAGE_TITLE_FOR_MODE_OF_WIZARD = "Please select the mode for the wizard";
- public static final String PAGE_DESCRIPTION_FOR_MODE_OF_WIZARD = "Here you can update the basic details of the task, and the mode in which the wizard will run.";
-
- public static final String PAGE_NAME_FOR_CLAFER_FILE_CREATION = "pageForClaferFileCreation";
- public static final String PAGE_TITLE_FOR_CLAFER_FILE_CREATION = "Add the variablity modelling here";
- public static final String PAGE_DESCRIPTION_FOR_CLAFER_FILE_CREATION = "Here you can add features to the variability model here.";
-
- public static final String PAGE_NAME_FOR_XSL_FILE_CREATION = "pageForXSLFileCreation";
- public static final String PAGE_TITLE_FOR_XSL_FILE_CREATION = "Add data for the code generation";
- public static final String PAGE_DESCRIPTION_FOR_XSL_FILE_CREATION = "Here you can details for the code generation.";
+ // Task Integrator Wizard
+ public static final String PLUGIN_ID = "de.cognicrypt.integrator.task";
+
+ public static final String PAGE_TASK_INFORMATION = "pageForTaskInformation";
+ public static final String PAGE_TITLE_FOR_MODE_OF_WIZARD = "New task";
+ public static final String PAGE_DESCRIPTION_FOR_MODE_OF_WIZARD = "Provide the basic details about the task and add templates.";
+ public static final String TASK_DESCRIPTION_MESSAGE = "Describe the task";
+ public static final String TEMPLATES = "Templates";
+
+ public static final String ICON_DESCRIPTION = "Select PNG file that contains the task icon";
+ public static final String DEFAULT_ICON_PATH = "icons/task-default-icon.png";
+
+ public static final String GUIDED_MODE_DESCRIPTION = "Guided Mode";
+ public static final String JSON_DESCRIPTION = "Select JSON file that contains the high-level questions";
+
+ public static final String ZIP_DESCRIPTION = "Select ZIP file that contains the task information";
+
public static final String PAGE_NAME_FOR_HIGH_LEVEL_QUESTIONS = "pageForHighLevelQuestions";
- public static final String PAGE_TITLE_FOR_HIGH_LEVEL_QUESTIONS = "Add the high level questions and their dependencies here";
+ public static final String PAGE_TITLE_FOR_HIGH_LEVEL_QUESTIONS = "Questions catalog";
public static final String PAGE_DESCRIPTION_FOR_HIGH_LEVEL_QUESTIONS =
- "Here you can add the questions that will be asked to the end user, and the dependencies to the " + "variability modelling and the code generation.";
+ "Add questions and possible answers with their associated templates for the code generation wizard";
- public static final String PAGE_NAME_FOR_LINK_ANSWERS = "pageForLinkAnswers";
- public static final String PAGE_TITLE_FOR_LINK_ANSWERS = "Select the question that needs to be linked to another question";
- public static final String PAGE_DESCIPTION_FOR_LINK_ANSWERS =
- "Here you can configure which question should be displayed next upon selection of a particular answer of the current question" + "by clicking the Link Answer button.";
+ public static final String QUESTION_LABEL = "Question";
+ public static final String DELTETE_BTN_TOOLTIP = "Click to delete the question";
+
+ public static final String REMOVE_QUESTION = "Remove Question";
+ public static final String DELETE_CONFIRMATION = "Are you sure that you want to remove this question?";
+
+ public static final String QUESTION_DESCRIPTION = "Describe the question";
+ public static final String ANSWERS_LABEL = "Answers";
+
+ public static final String ADD_ANSWER_TOOLTIP = "Click to add an answer";
+
+ public static final String TASK_SUCCESFULLY_IMPORTED = "Task succesfully imported";
+
+ // Buttons
+ public static final String ADD_QUESTION = "Add Question";
+ public static final String ADD_ANSWER = "Add Answer";
+ public static final String GENERATE_BUTTON = "Generate";
+
+ // Images
+ public static final Image DEC_INFORMATION = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage();
+ public static final Image DEC_ERROR = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage();
+ public static final Image DEC_REQUIRED = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_REQUIRED).getImage();
+ public static final Image DEC_WARNING = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage();
+
+ // define custom Code Generation Template/Resource Directory
+ public final static String RELATIVE_CogniCrypt_RESOURCE_DIR = "resources/CogniCrypt";
+ public final static String ECLIPSE_CogniCrypt_RESOURCE_DIR = Platform.getInstallLocation().getURL().getPath() + RELATIVE_CogniCrypt_RESOURCE_DIR;
+ public final static String RELATIVE_LOC_TEMP_DIR = RELATIVE_CogniCrypt_RESOURCE_DIR + "/templates";
+ public final static String ECLIPSE_LOC_TEMP_DIR = Platform.getInstallLocation().getURL().getPath() + RELATIVE_LOC_TEMP_DIR;
+ public final static String ECLIPSE_LOC_RES_DIR = ECLIPSE_CogniCrypt_RESOURCE_DIR + "/res";
+ public final static String ECLIPSE_LOC_ADDRES_DIR = ECLIPSE_LOC_RES_DIR + "/AdditionalResources";
+ public final static String ECLIPSE_LOC_CLA_DIR = ECLIPSE_LOC_RES_DIR + "/ClaferModel";
+ public final static String ECLIPSE_LOC_IMG_DIR = ECLIPSE_LOC_RES_DIR + "/images";
+ public final static String ECLIPSE_LOC_TASKDESC_DIR = ECLIPSE_LOC_RES_DIR + "/TaskDesc";
+ public final static String ECLIPSE_LOC_TASKS_DIR = ECLIPSE_LOC_RES_DIR + "/Tasks";
+ public final static String ECLIPSE_LOC_XSL_DIR = ECLIPSE_LOC_TASKS_DIR + "/XSLTemplates";
+ public final static String ECLIPSE_LOC_EXPORT_DIR = ECLIPSE_CogniCrypt_RESOURCE_DIR + "/ExportableTasks";
+
+ public final static String customjsonTaskFile = ECLIPSE_LOC_TASKS_DIR + "/tasks.json";
- // Widget constants
- // Labels
- public static final String LABEL_BROWSE_BUTTON = "Browse";
+ public static final String IMPORT_SUCCESSFUL = "The task has been succesfully imported and can be used after restarting Eclipse.";
+ public static final String EXPORT_SUCCESSFUL = "The task has been succesfully generated. You can use it after restarting Eclipse. An exportable ZIP File for this task has been copied to:" + ECLIPSE_LOC_EXPORT_DIR;
+
+ public static final String DEFAULT_ANSWER = "Default Answer";
+ public static final String DEFAULT_ANSWER_TOOLTIP = "The answer that will be automatically selected when question appears for the first time";
+
+ // Warning
+ public static final String WARNING_TEMPLATE_NOT_USED_TITLE = "Unused Template";
+ public static final String WARNING_TEMPLATE_NOT_USED = "A template was added but is not used. Do you want to generate the task anyway?";
+
+ // Errors
+ public static final String ERROR = "ERROR: ";
+ public static final String ERROR_MESSAGE_BLANK_FILE_NAME = "Please choose a valid file.";
+ public static final String ERROR_MESSAGE_UNABLE_TO_READ_FILE = "There is a problem with the selected file.";
+ public static final String MESSAGE_REQUIRED_FIELD = "This is a required field.";
+ public static final String ERROR_CANNOT_REMOVE_PACKAGE = "The package could not be removed.";
+ public static final String ERROR_BLANK_TEMPLATE_LIST = "The template list cannot be empty. Please add a template.";
+ public static final String ERROR_SINGLE_TEMPLATE_ID = "The template's identifier does not match the task name and can therefor not be used to generate a single template task. Please add another template.";
+ public static final String ERROR_MESSAGE_BLANK_QUESTION_NAME = "The question name cannot be empty. Please enter a valid name for the question.";
+ public static final String ERROR_BLANK_ANSWERS_LIST = "The answers list cannot be empty. Please add an answer.";
+ public static final String ERROR_EMPTY_ANSWER_TEXT = "The text of an answer cannot be empty.";
+
+ public static final String ERROR_TASK_ALREADY_INTEGRATED = "The chosen template's associated task has already been integrated.";
+ public static final String ERROR_DIFFERENT_TASK_NAME = "The chosen template's file name does not match the task name of previously added templates and can therefor not be added.";
+ public static final String ERROR_FILE_NOT_FOUND = "The chosen template file could not be found.";
+ public static final String ERROR_NO_PACKAGE = "The chosen template's source code contains no package and can therefor not be added.";
+
+ public static final String ERROR_TEMPLATE_IS_USED_IN_ANSWER = "The chosen template is used in an answer and can therefor not be removed.";
+
+ public static final String ERROR_MULTIPLE_QUESTIONS_NOT_SUPPORTED = "Multiple questions are currently not supported.";
+
+ public static final String ERROR_PROBLEMS_WITH_ZIP = "Problems with the provided ZIP (Most likly has a wrong stucture).";
+ public static final String ERROR_PROBLEMS_WITH_FILES = "Problems with the provided files.";
+ public static final String ERROR_ICON_FILE_NOT_FOUND = "ZIP invalid (Icon File not found) \n";
+ public static final String ERROR_JSON_FILE_NOT_FOUND = "ZIP invalid (Question JSON File not found) \n";
+ public static final String ERROR_TEMPLATE_FILE_NOT_FOUND = "ZIP invalid (Template Files not found) \n";
+
+ public static final String ERROR_FILE_COPY = "There was a problem copying file ";
+ public static final String ERROR_UNKNOWN_FILE_TYPE = "Unknown file type.";
+ public static final String ERROR_TASK_UPDATE = "There was a problem updating the task file.\n";
+ public static final String ERROR_DIRECTORY_CREATION = "Failed to create directory ";
+ public static final String ERROR_ENTRY_OUTSIDE_TARGETDIR = "Entry is outside of the target dir: ";
+
+ // Labels
+ public static final String LABEL_BROWSE_BUTTON = "Choose File";
+ public static final String QUESTION = "Question";
+ public static final String DESCRIBE_QUESTION = "Description";
// Dimensions
public static final int UI_WIDGET_HEIGHT_NORMAL = 29;
// Constants for the composites
public static final String WIDGET_DATA_NAME_OF_THE_TASK = "NameOfTheTask";
- public static final String WIDGET_DATA_LIBRARY_LOCATION_OF_THE_TASK = "Location of the Library";
- public static final String WIDGET_DATA_LIBRARY_LOCATION_OF_THE_HELP_FILE = "Location of the Help file";
- public static final String WIDGET_DATA_LOCATION_OF_CLAFER_FILE = "Location of the Clafer file";
- public static final String WIDGET_DATA_LOCATION_OF_CRYSLTEMPLATE_FILE = "Location of the Crysl Template file";
- public static final String WIDGET_DATA_LOCATION_OF_XSL_FILE = "Location of the XSL file";
- public static final String WIDGET_DATA_LOCATION_OF_JSON_FILE = "Location of the JSON file";
- public static final String WIDGET_DATA_LOCATION_OF_PNG_FILE = "Location of the PNG file";
- public static final String WIDGET_DATA_LOCATION_OF_HELP_FILE = "Location of the Help file";
- public static final String WIDGET_DATA_IS_CUSTOM_LIBRARY_REQUIRED = "isCustomLibraryRequired";
+ public static final String WIDGET_DATA_LOCATION_OF_CRYSLTEMPLATE_FILE = "Select code template";
+ public static final String WIDGET_DATA_LOCATION_OF_JSON_FILE = "Questions";
+ public static final String WIDGET_DATA_LOCATION_OF_PNG_FILE = "Icon";
public static final String WIDGET_DATA_IS_GUIDED_MODE_CHOSEN = "isGuidedModeChosen";
- public static final String WIDGET_DATA_IS_GUIDED_MODE_FORCED = "isGuidedModeForced";
-
- // Constants for the drop down for the library type on the mode selection page
- public static final String WIDGET_CONTENT_EXISTING_LIBRARY = "No custom Library";
- public static final String WIDGET_CONTENT_CUSTOM_LIBRARY = "Custom Library";
-
- // Constants for the drop down for the xsl tag on the xsl code page
- public static final String XSL_VARIABLE_TAG = "xslVariable";
- public static final String XSL_SELECT_TAG = "select";
- public static final String XSL_IF_TAG = "if";
- public static final String XSL_RESULT_DOCUMENT = "result-document";
- public static final String XSL_APPLY_TEMPLATES = "apply-templates";
- public static final String XSL_CHOOSE_TAG = "choose";
- public static final String XSL_WHEN_TAG = "when";
- public static final String XSL_OTHERWISE_TAG = "otherwise";
-
- // Default bounds for the composites
- public static final Point DEFAULT_SIZE_FOR_TI_WIZARD = new Point(1050, 600);
- public static final Rectangle RECTANGLE_FOR_COMPOSITES = new Rectangle(0, 0, 887, 500 - 10 - 10); // 897 - 10
- public static final Rectangle RECTANGLE_FOR_FIRST_BUTTON_FOR_NON_MODE_SELECTION_PAGES = new Rectangle(897, 10, 100, 29); // 1000 - 83 - 10 -10
- public static final Rectangle RECTANGLE_FOR_SECOND_BUTTON_FOR_NON_MODE_SELECTION_PAGES = new Rectangle(897, 49, 100, 29); // 1000 - 83 - 10 -10
- // public static final Rectangle RECTANGLE_FOR_GRANULAR_CLAFER_UI_ELEMENT = new
- // Rectangle(10, 10, 744, 280);
- public static final int WIDTH_FOR_GRANULAR_CLAFER_UI_ELEMENT = 744;
- public static final int HEIGHT_FOR_GRANULAR_CLAFER_UI_ELEMENT = 280;
-
- public static final int SINGLE_LINE_TEXT_BOX_LIMIT = 256;
- public static final int MULTI_LINE_TEXT_BOX_LIMIT = 2560;
-
- // Form data for CompositeGranularUIForClaferFeature
- public static final int RIGHT_VALUE_FOR_GRANULAR_CLAFER_UI_SUB_ELEMENT = 736;
+ public static final String WIDGET_DATA_LOCATION_OF_IMPORT_FILE = "Import File";
public static final int PADDING_BETWEEN_GRANULAR_UI_ELEMENTS = 10;
- public static final int PADDING_BETWEEN_SMALLER_UI_ELEMENTS = 3;
-
- public static final int WIDTH_FOR_CLAFER_FEATURE_PROPERTY_UI_ELEMENT = 409;
- public static final int HEIGHT_FOR_CLAFER_FEATURE_PROPERTY_UI_ELEMENT = 37;
-
- // TypeOfTargetDataForSmallUIElements int values. Add the type of data that
- // needs to be shown on the composite here.
- public static final int FEATURE_PROPERTY = 0;
- public static final int FEATURE_CONSTRAINT = 1;
-
- // source for the contents of this enum : https://www.w3.org/TR/xslt20/
- public static enum XSLTags {
- XSL_VARIABLE_TAG("Variable", "", "", new String[] {"name", "select", "as"
- /*
- * , "static", "visibility"
- */
- }), XSL_VALUE_OF_TAG("Value of", "", "", new String[] {"select", "separator", "disable-output-escaping"}), XSL_IF_TAG("If", "", "",
- new String[] {"test"}), XSL_RESULT_DOCUMENT("Result Document", "", "",
- new String[] {"href", "format", "validation", "type", "method", "byte-order-mark", "cdata-section-elements", "doctype-public", "doctype-system", "encoding",
- "escape-uri-attributes", "include-content-type", "indent", "media-type", "normalization-form", "omit-xml-declaration", "standalone", "undeclare-prefixes",
- "use-character-maps", "output-version"
- /*
- * , "allow-duplicate-names", "build-tree", "html-version", "item-separator", "json-node-output-method", "parameter-document", "suppress-indentation",
- */
- }), XSL_APPLY_TEMPLATES("Apply Templates", "", "", new String[] {"select", "mode"}), XSL_CHOOSE_TAG("Choose", "", "",
- new String[] {}), XSL_WHEN_TAG("When", "", "",
- new String[] {"test"}), XSL_OTHERWISE_TAG("Otherwise", "", "", new String[] {});
-
- private final String XSLTagFaceName;
- private final String XSLBeginTag;
- private final String XSLEndTag;
- private final String[] XSLAttributes;
-
- /**
- * @param XSLTagFaceNameParam
- * @param XSLBeginTagParam
- * @param XSLEndTagParam
- */
- private XSLTags(final String XSLTagFaceNameParam, final String XSLBeginTagParam, final String XSLEndTagParam, final String[] XSLAttributesParam) {
- this.XSLTagFaceName = XSLTagFaceNameParam;
- this.XSLBeginTag = XSLBeginTagParam;
- this.XSLEndTag = XSLEndTagParam;
- this.XSLAttributes = XSLAttributesParam;
- }
-
- /**
- * @return the xSLTagFaceName
- */
- public String getXSLTagFaceName() {
- return this.XSLTagFaceName;
- }
-
- /**
- * @return the xSLBeginTag
- */
- public String getXSLBeginTag() {
- return this.XSLBeginTag;
- }
-
- /**
- * @return the xSLEndTag
- */
- public String getXSLEndTag() {
- return this.XSLEndTag;
- }
-
- /**
- * @return the xSLAttributes
- */
- public String[] getXSLAttributes() {
- return this.XSLAttributes;
- }
-
- }
-
- public static enum FeatureConstraintRelationship {
- EQUAL("="), NOTEQUAL("!="), LESSTHAN("<"), GREATERTHAN(">"), LESSTHANEQUALTO("<="), GREATERTHANEQUALTO(">="), AND("and"), OR("or");
-
- private final String operatorValue;
-
- FeatureConstraintRelationship(final String operatorValue) {
- this.operatorValue = operatorValue;
- }
-
- /**
- * @return the operatorValue
- */
- public String getOperatorValue() {
- return this.operatorValue;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Enum#toString() Just return the operator value instead of the name.
- */
- @Override
- public String toString() {
- return this.operatorValue;
- }
-
- }
-
- public static enum FeatureType {
- CONCRETE, ABSTRACT;
-
- /*
- * Although "concrete" is never used in the actual cfr file, "abstract" is used. Hence the toString() returns lower case.
- */
- @Override
- public String toString() {
- return name().toLowerCase();
- }
-
- }
-
- public static final String SLASH = "/";
- public static final String ATTRIBUTE_BEGIN = "[@";
- public static final String ATTRIBUTE_END = "=\'\']";
- public static final String DOT = ".";
// for the file utils for the task integrator.
- public static final String JAR_FILE_DIRECTORY_PATH = rsrcPath + "AdditionalResources" + innerFileSeparator;
- public static final String CFR_FILE_DIRECTORY_PATH = rsrcPath + "ClaferModel" + innerFileSeparator;
- public static final String CFR_BIN_FILE_DIRECTORY_PATH = rsrcPath + "ClaferModelBin" + innerFileSeparator;
- public static final String JSON_FILE_DIRECTORY_PATH = rsrcPath + "TaskDesc" + innerFileSeparator;
- public static final String IMAGE_FILE_DIRECTORY_PATH = rsrcPath + "images" + innerFileSeparator;
- public static final String XML_FILE_DIRECTORY_PATH = rsrcPath + "Help" + innerFileSeparator;
- public static final String pluginXmlFile = "plugin.xml";
- public static final String XSL_FILE_DIRECTORY_PATH = rsrcPath + "XSLTemplates" + innerFileSeparator;
- public static final String HELP_FILE_DIRECTORY_PATH = rsrcPath + "Help" + innerFileSeparator;
- public static final String CFR_EXTENSION = ".cfr";
+ public static final String LOCAL_JSON_FILE_DIRECTORY_PATH = localrsrcPath + "TaskDesc" + innerFileSeparator;
public static final String JAVA_EXTENSION = ".java";
public static final String PNG_EXTENSION = ".png";
- public static final String CFR_BIN_EXTENSION = ".dat";
- public static final String JS_EXTENSION = ".js";
- public static final String JAR_EXTENSION = ".jar";
public static final String JSON_EXTENSION = ".json";
public static final String XML_EXTENSION = ".xml";
- public static final String XSL_EXTENSION = ".xsl";
- public static final String PLUGIN_XML_FILE = innerFileSeparator + "plugin.xml";
-
+ public static final String ZIP_EXTENSION = ".zip";
+
public static final String DEFAULT_FEATURE_SET_FILE = "DefaultFeatureSet";
public static final String PREDICATEENSURER_GROUPID = "de.upb.cognicrypt.predicateensurer";
@@ -506,10 +419,6 @@ public String toString() {
public static final String MVN_SKIPTESTS_COMMAND = "-DskipTests=true";
public static final String MVN_ECLIPSE_COMMAND = "eclipse:eclipse";
- // for the list of items to be included inside the combo of the questionTab
- public static final String dropDown = "Drop down";
- public static final String textBox = "Text box";
- public static final String radioButton = "Radio button";
// for creating SuppressWarnings.xml
public static final String SUPPRESSWARNING_FILE = "SuppressWarnings" + XML_EXTENSION;
@@ -594,7 +503,7 @@ public String toString() {
public static final String cryslEditorID = "de.darmstadt.tu.crossing.CrySL";
public static final String HEALTHY = "Secure";
public static final String UNHEALTHY = "Insecure";
-
+
// define the max java version before which plugin works.
public static final String CC_JAVA_VERSION = "1.8";
diff --git a/plugins/de.cognicrypt.core/src/de/cognicrypt/utils/Utils.java b/plugins/de.cognicrypt.core/src/de/cognicrypt/utils/Utils.java
index d297005c9..03a5e8566 100644
--- a/plugins/de.cognicrypt.core/src/de/cognicrypt/utils/Utils.java
+++ b/plugins/de.cognicrypt.core/src/de/cognicrypt/utils/Utils.java
@@ -230,6 +230,8 @@ public static File getResourceFromWithin(final String inputPath) {
* @return absolute path
*/
public static File getResourceFromWithin(final String inputPath, final String pluginID) {
+ // Activator.getDefault().logError(inputPath);
+
try {
final Bundle bundle = Platform.getBundle(pluginID);
if (bundle == null) {
@@ -248,8 +250,7 @@ public static File getResourceFromWithin(final String inputPath, final String pl
}
return new File(resolvedURI);
}
- }
- catch (final IOException ex) {
+ } catch (final IOException ex) {
Activator.getDefault().logError(ex, Constants.ERROR_MESSAGE_NO_FILE);
} catch (URISyntaxException ex) {
Activator.getDefault().logError(ex);
diff --git a/plugins/de.cognicrypt.integrator.task/.classpath b/plugins/de.cognicrypt.integrator.task/.classpath
index d1fee4446..fc9248eb0 100644
--- a/plugins/de.cognicrypt.integrator.task/.classpath
+++ b/plugins/de.cognicrypt.integrator.task/.classpath
@@ -1,6 +1,11 @@
-
+
+
+
+
+
+
diff --git a/plugins/de.cognicrypt.integrator.task/META-INF/MANIFEST.MF b/plugins/de.cognicrypt.integrator.task/META-INF/MANIFEST.MF
index 5c514a22a..7601fcdba 100644
--- a/plugins/de.cognicrypt.integrator.task/META-INF/MANIFEST.MF
+++ b/plugins/de.cognicrypt.integrator.task/META-INF/MANIFEST.MF
@@ -18,4 +18,11 @@ Automatic-Module-Name: de.cognicrypt.integrator.task
Bundle-ActivationPolicy: lazy
Bundle-ClassPath: lib/claferchocoig.jar,
lib/dom4j-2.0.0.jar,
- .
+ .,
+ src/main/
+Export-Package: de.cognicrypt.integrator.task,
+ de.cognicrypt.integrator.task.actions,
+ de.cognicrypt.integrator.task.controllers,
+ de.cognicrypt.integrator.task.models,
+ de.cognicrypt.integrator.task.widgets,
+ de.cognicrypt.integrator.task.wizard
diff --git a/plugins/de.cognicrypt.integrator.task/build.properties b/plugins/de.cognicrypt.integrator.task/build.properties
index aaf867404..3c7434086 100644
--- a/plugins/de.cognicrypt.integrator.task/build.properties
+++ b/plugins/de.cognicrypt.integrator.task/build.properties
@@ -4,4 +4,8 @@ output.. = bin/
bin.includes = META-INF/,\
.,\
lib/claferchocoig.jar,\
- lib/dom4j-2.0.0.jar
+ lib/dom4j-2.0.0.jar,\
+ src/main/,\
+ plugin.xml,\
+ pom.xml,\
+ build.properties
diff --git a/plugins/de.cognicrypt.integrator.task/pom.xml b/plugins/de.cognicrypt.integrator.task/pom.xml
index 5184d6d2b..d4c2c8796 100644
--- a/plugins/de.cognicrypt.integrator.task/pom.xml
+++ b/plugins/de.cognicrypt.integrator.task/pom.xml
@@ -19,6 +19,14 @@
${tycho-version}true
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 7
+ 7
+
+
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/Activator.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/Activator.java
index bfe5c99ec..6b9a7570b 100644
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/Activator.java
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/Activator.java
@@ -15,22 +15,19 @@
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
+import de.cognicrypt.core.Constants;
+
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
- public static final String PLUGIN_ID = "de.cognicrypt.integrator.task"; //$NON-NLS-1$
+ public static final String PLUGIN_ID = Constants.PLUGIN_ID;
// The shared instance
private static Activator plugin;
- /**
- * The constructor
- */
- public Activator() {}
-
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
@@ -57,7 +54,7 @@ private void log(final int severity, final String message, final Exception ex) {
}
public void logError(final Exception ex) {
- logError(ex, ex.getMessage());
+ log(IStatus.ERROR, ex.getMessage(), ex);
}
public void logError(final Exception ex, final String message) {
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/UIConstants.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/UIConstants.java
deleted file mode 100644
index 1943ef02c..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/UIConstants.java
+++ /dev/null
@@ -1,20 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task;
-
-import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
-import org.eclipse.swt.graphics.Image;
-
-public class UIConstants {
-
- public static final Image DEC_INFORMATION = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage();
- public static final Image DEC_ERROR = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage();
- public static final Image DEC_REQUIRED = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_REQUIRED).getImage();
- public static final Image DEC_WARNING = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage();
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/RunTaskIntegratorHandler.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/RunTaskIntegratorHandler.java
index 427e4c8ef..925719c3b 100644
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/RunTaskIntegratorHandler.java
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/RunTaskIntegratorHandler.java
@@ -16,7 +16,7 @@
import org.eclipse.ui.PlatformUI;
import de.cognicrypt.core.Constants;
-import de.cognicrypt.integrator.task.wizard.TaskIntegrationWizard;
+import de.cognicrypt.integrator.task.wizard.TaskIntegratorWizard;
import de.cognicrypt.integrator.task.wizard.TaskIntegratorWizardDialog;
public class RunTaskIntegratorHandler extends AbstractHandler {
@@ -24,7 +24,8 @@ public class RunTaskIntegratorHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Constants.WizardActionFromContextMenuFlag = true;
- final TaskIntegratorWizardDialog dialog = new TaskIntegratorWizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), new TaskIntegrationWizard());
+ final TaskIntegratorWizardDialog dialog = new TaskIntegratorWizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), new TaskIntegratorWizard());
+ dialog.setMinimumPageSize(1000, 700);
dialog.setHelpAvailable(false);
return dialog.open();
}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/WizardAction.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/WizardAction.java
deleted file mode 100644
index edc784cc0..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/actions/WizardAction.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task.actions;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import de.cognicrypt.core.Constants;
-import de.cognicrypt.integrator.task.wizard.TaskIntegrationWizard;
-
-public class WizardAction implements IWorkbenchWindowActionDelegate {
-
- @Override
- public void run(final IAction arg0) {
- Constants.WizardActionFromContextMenuFlag = false;
- final WizardDialog dialog = new WizardDialog(new Shell(), new TaskIntegrationWizard());
- // dialog.setPageSize(Constants.DEFAULT_SIZE_FOR_TI_WIZARD);
- // dialog.setMinimumPageSize(Constants.DEFAULT_SIZE_FOR_COMPOSITES);
- dialog.open();
- }
-
- @Override
- public void selectionChanged(final IAction arg0, final ISelection arg1) {}
-
- @Override
- public void dispose() {}
-
- @Override
- public void init(final IWorkbenchWindow arg0) {}
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/CreateAndModifyXmlfile.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/CreateAndModifyXmlfile.java
deleted file mode 100644
index 9e60dc928..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/CreateAndModifyXmlfile.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task.controllers;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.ArrayList;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-import de.cognicrypt.codegenerator.question.Page;
-import de.cognicrypt.codegenerator.question.Question;
-import de.cognicrypt.codegenerator.utilities.CodeGenUtils;
-import de.cognicrypt.core.Constants;
-import de.cognicrypt.utils.Utils;
-
-public class CreateAndModifyXmlfile {
-
- private String taskName;
- private ArrayList pages;
- private String filePath;
-
- /**
- * The class creates the xml file containing the help content of the task, adds the location of the xml file in the plugin.xml file and sets the page help id. The class needs to
- * be initialized with the list of pages and task name
- *
- * @param pages list of pages
- * @param taskName the name of the task
- * @throws IOException
- * @throws ParserConfigurationException
- * @throws SAXException
- * @throws TransformerException
- */
-
- public CreateAndModifyXmlfile(final ArrayList pages, final String taskName, final boolean taskHasPageHelpContent)
- throws IOException, ParserConfigurationException, SAXException, TransformerException {
- setTaskName(taskName);
- setPages(pages);
- // creates the template xml file
- createXmlFile();
- setFilePath(Constants.XML_FILE_DIRECTORY_PATH + getTaskName() + Constants.XML_EXTENSION);
-
- if (taskHasPageHelpContent) {
- /**
- * For each page this loop creates a list of questions which has help content, then adds the content to the xml file and then sets the page help id
- */
- for (final Page page : pages) {
- final ArrayList questionWithHelpContent = new ArrayList<>();
- String pageHelpContent = "";
- for (final Question question : page.getContent()) {
- if (!question.getHelpText().isEmpty()) {
- questionWithHelpContent.add(question);
- }
- }
- if (questionWithHelpContent.size() > 0) {
- for (final Question qstn : questionWithHelpContent) {
- pageHelpContent = pageHelpContent + qstn.getHelpText() + "\n";
- }
- addHelpContentToXmlFile(pageHelpContent, page.getId());
- // sets the page help id field
- page.setHelpID(getTaskName() + "_Page" + page.getId());
- }
- }
- } else if (!taskHasPageHelpContent) {
- addHelpContentToXmlFile(Constants.helpContentNotAvailable, pages.get(0).getId());
- pages.get(0).setHelpID(getTaskName() + "_Page" + pages.get(0).getId());
- }
-
- /**
- * Calls the following method to add the path to the new xml file in the plugin.xml
- */
- updatePluginXmlFile(CodeGenUtils.getResourceFromWithin(Constants.pluginXmlFile));
-
- }
-
- /**
- * This method creates the template xml file for the task and places the xml file in target Help folder
- *
- * @throws IOException
- */
- private void createXmlFile() throws IOException {
-
- final File xmlFileTargetDirectory = new File(Utils.getResourceFromWithin(Constants.XML_FILE_DIRECTORY_PATH), getTaskName() + Constants.XML_EXTENSION);
- // creates the xml file
- xmlFileTargetDirectory.createNewFile();
-
- // writer to write contents at target location
- final FileWriter xmlWriter = new FileWriter(xmlFileTargetDirectory);
- final StringBuilder sb = new StringBuilder();
- sb.append(Constants.Xml_Declaration + System.lineSeparator());
- sb.append(Constants.NLS_Tag + System.lineSeparator());
- sb.append(Constants.contextsOpeningTag + System.lineSeparator() + Constants.contextsClosingTag);
- final String xmlContent = sb + "";
- try {
- xmlWriter.write(xmlContent);
- }
- finally {
- xmlWriter.flush();
- xmlWriter.close();
- }
- }
-
- /**
- * This method adds the page help content in the template xml file created by createXmlFile() method of this class
- *
- * @param pageHelpContent help content of the page
- * @param pageId the page id
- * @throws ParserConfigurationException
- * @throws SAXException
- * @throws IOException
- * @throws TransformerException
- */
- public void addHelpContentToXmlFile(final String pageHelpContent, final int pageId) throws ParserConfigurationException, SAXException, IOException, TransformerException {
-
- final File xmlFile = Utils.getResourceFromWithin(getFilePath());
- final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- final Document doc = docBuilder.parse(xmlFile);
-
- // gets the root element contexts
- final Node contexts = doc.getElementsByTagName(Constants.contextsElement).item(0);
- final Element context = doc.createElement(Constants.contextElement);
- contexts.appendChild(context);
-
- // value of id attribute
- final String idValue = getTaskName() + "_Page" + pageId;
-
- // creates the id attribute of context element
- final Attr idAttribute = doc.createAttribute(Constants.idAttribute);
- idAttribute.setValue(idValue);
- context.setAttributeNode(idAttribute);
-
- // creates the title attribute of context element
- final Attr titleAttribute = doc.createAttribute(Constants.titleAttribute);
- titleAttribute.setValue(Constants.titleAttributeValue);
- context.setAttributeNode(titleAttribute);
-
- // Creates the description element which will contain the help content of the page
- final Element description = doc.createElement(Constants.descriptionAttribute);
- description.appendChild(doc.createTextNode(pageHelpContent));
- context.appendChild(description);
-
- // writes the content in to xml file
- final TransformerFactory transformerFactory = TransformerFactory.newInstance();
- final Transformer transformer = transformerFactory.newTransformer();
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- final DOMSource source = new DOMSource(doc);
- final StreamResult result = new StreamResult(xmlFile);
- transformer.transform(source, result);
-
- }
-
- /**
- * This method parses the plugin.xml file to add the path of the new xml file in it
- *
- * @param pluginXmlFile the plugin.xml file
- * @throws ParserConfigurationException
- * @throws SAXException
- * @throws IOException
- * @throws TransformerException
- */
- private void updatePluginXmlFile(final File pluginXmlFile) throws ParserConfigurationException, SAXException, IOException, TransformerException {
-
- final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- final Document doc = docBuilder.parse(pluginXmlFile);
-
- // gets the plugin element of the file
- final Node plugin = doc.getElementsByTagName(Constants.pluginElement).item(0);
- final NodeList extensions = plugin.getChildNodes();
-
- /**
- * Following loop adds the path to the xml file of the task at the target location
- */
-
- for (int i = 0; i < extensions.getLength(); i++) {
- final Node extension = extensions.item(i);
- if (Constants.extensionElement.equals(extension.getNodeName())) {
- final NamedNodeMap attr = extension.getAttributes();
- if (attr.getLength() == 1) {
- final Node point = attr.getNamedItem(Constants.pointAttribute);
- if (point.getTextContent().equals(Constants.pointAttributeValue)) {
- final Element contexts = doc.createElement(Constants.contextsElement);
- extension.appendChild(contexts);
-
- final Attr file = doc.createAttribute(Constants.fileAttribute);
- String filePath = Utils.getResourceFromWithin(getFilePath()).toString();
- filePath = filePath.replace("\\", "/");
- file.setValue(filePath.substring(filePath.indexOf(Constants.startingFrom)));
- contexts.setAttributeNode(file);
-
- }
- }
- }
-
- }
-
- final TransformerFactory transformerFactory = TransformerFactory.newInstance();
- final Transformer transformer = transformerFactory.newTransformer();
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
- transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- final DOMSource source = new DOMSource(doc);
- final StreamResult result = new StreamResult(pluginXmlFile);
- transformer.transform(source, result);
-
- }
-
- /**
- * @return the task name
- */
- public String getTaskName() {
- return this.taskName;
- }
-
- /**
- * Sets the task name
- *
- * @param taskName
- */
- public void setTaskName(final String taskName) {
- this.taskName = taskName;
- }
-
- /**
- * @return the list of pages
- */
- public ArrayList getPages() {
- return this.pages;
- }
-
- /**
- * Sets the list of pages
- *
- * @param pages
- */
- public void setPages(final ArrayList pages) {
- this.pages = pages;
- }
-
- /**
- * @return the path of the file
- */
- public String getFilePath() {
- return this.filePath;
- }
-
- /**
- * sets the file path
- *
- * @param filePath the path of the file
- */
- public void setFilePath(final String filePath) {
- this.filePath = filePath;
- }
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilities.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilities.java
index 232d02407..10a7e0a00 100644
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilities.java
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilities.java
@@ -13,33 +13,20 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
-import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
-import java.util.zip.ZipFile;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.stream.StreamSource;
-import org.clafer.ast.AstClafer;
-import org.dom4j.Attribute;
-import org.dom4j.Document;
-import org.dom4j.DocumentException;
-import org.dom4j.Element;
-import org.dom4j.io.OutputFormat;
-import org.dom4j.io.SAXReader;
-import org.dom4j.io.XMLWriter;
-import org.xml.sax.SAXException;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@@ -48,295 +35,213 @@
import de.cognicrypt.codegenerator.tasks.Task;
import de.cognicrypt.core.Constants;
import de.cognicrypt.integrator.task.Activator;
-import de.cognicrypt.utils.Utils;
+import de.cognicrypt.integrator.task.models.IntegratorModel;
+/**
+ * This class is used to copy the necessary files for Task Integration to the correct destinations
+ * where the Code Generator can use them
+ *
+ */
public class FileUtilities {
- private String taskName;
- private StringBuilder errors; // Maintain all the errors to display them on the wizard.
-
+ private StringBuilder errors; // Maintain all the errors to display them on the wizard
+ IntegratorModel integratorModel;
+
/**
- * The class needs to be initialized with a task name, as it is used extensively
- * in the methods.
- *
- * @param taskName
+ * Set local attributes and build Directory Structure for custom tasks if it doesn't exist
*/
- public FileUtilities(final String taskName) {
+ public FileUtilities() {
super();
- setTaskName(taskName);
- setErrors(new StringBuilder());
+ errors = new StringBuilder();
+ integratorModel = IntegratorModel.getInstance();
+
+ File ressourceFolder = new File(Constants.ECLIPSE_CogniCrypt_RESOURCE_DIR);
+
+ if (!ressourceFolder.exists()) {
+ // make resource directory for Code Generation Templates if it doesn't exist
+ ressourceFolder.mkdirs();
+ initLocalResourceDir(); // initialize needed sub-directories
+ }
}
-
-
-
-
- private void writeHelpFile(final String helpFileContents) {
- final File xmlFile = new File(Utils.getResourceFromWithin(Constants.HELP_FILE_DIRECTORY_PATH),
- getTrimmedTaskName() + Constants.XML_EXTENSION);
-
+ /**
+ * Creates the local resource directory for custom tasks and its subdirectories
+ */
+ public void initLocalResourceDir() {
+ File resourceCCTemp = new File(Constants.ECLIPSE_LOC_TEMP_DIR);
+ File resourceCCres = new File(Constants.ECLIPSE_LOC_RES_DIR);
+
+ resourceCCTemp.mkdir(); // make local directory for Code Generation Templates
+ resourceCCres.mkdir(); //// make local directory for Resources for Code Generation Templates
+
+ File resourceCCaddres = new File(Constants.ECLIPSE_LOC_ADDRES_DIR);
+ File resourceCCcla = new File(Constants.ECLIPSE_LOC_CLA_DIR);
+ File resourceCCimg = new File(Constants.ECLIPSE_LOC_IMG_DIR);
+ File resourceCCtaskdesc = new File(Constants.ECLIPSE_LOC_TASKDESC_DIR);
+ File resourceCCtasks = new File(Constants.ECLIPSE_LOC_TASKS_DIR);
+ File resourceCCXSL = new File(Constants.ECLIPSE_LOC_XSL_DIR);
+ File resourceCCtasksjson = new File(Constants.customjsonTaskFile);
+ File resourceExport = new File(Constants.ECLIPSE_LOC_EXPORT_DIR);
+
+ resourceCCaddres.mkdir();
+ resourceCCcla.mkdir();
+ resourceCCimg.mkdir();
+ resourceCCtaskdesc.mkdir();
+ resourceCCtasks.mkdir();
+ resourceCCXSL.mkdir();
+ resourceExport.mkdir();
try {
- final PrintWriter writer = new PrintWriter(xmlFile);
- writer.println(helpFileContents);
- writer.flush();
+ resourceCCtasksjson.createNewFile();
+ FileWriter fileWriter = new FileWriter(resourceCCtasksjson);
+ BufferedWriter writer = new BufferedWriter(fileWriter);
+ writer.write("[]");
writer.close();
- } catch (final FileNotFoundException e) {
- Activator.getDefault().logError(e);
- getErrors().append("There was a problem wrting the Help data.\n");
- }
-
- if (!validateXMLFile(xmlFile)) {
- xmlFile.delete();
- getErrors().append("The XML data is invalid.\n");
+ fileWriter.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
-
}
-
-
- public String writeCryslTemplate(final File cryslTemplateFile, final File jsonFileLocation, final File iconFile) {
- copyFileFromPath(cryslTemplateFile);
- copyFileFromPath(jsonFileLocation);
- copyFileFromPath(iconFile);
- return getErrors().toString();
- }
-
- public String writeCryslTemplate(final HashMap cryslTemplateFile, final File jsonFileLocation,
- final File iconFile) {
+ /**
+ * copy given Template Files and given Image File to local resource directory for custom tasks
+ * (only used in Guided Mode Integration)
+ * @return String with the error messages ("" if no errors happend)
+ */
+ public String writeData() {
+
+ final Map cryslTemplateFile = integratorModel.getCryslTemplateFiles();
+
+ copyImage(integratorModel.getIconFile());
for (String key : cryslTemplateFile.keySet()) {
try {
- copyFileFromPath(cryslTemplateFile.get(key), key);
+ copyTemplate(cryslTemplateFile.get(key), key);
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ errors.append("There was a problem copying file " + cryslTemplateFile.get(key).toString() + "\n");
}
}
- copyFileFromPath(jsonFileLocation);
- copyFileFromPath(iconFile);
- return getErrors().toString();
+ return errors.toString();
}
- public String writeCryslTemplate(final File cryslTemplateFile, final File iconFile) {
- copyFileFromPath(cryslTemplateFile);
- copyFileFromPath(iconFile);
- return getErrors().toString();
- }
-
- public String writeCryslTemplate(final HashMap cryslTemplateFile, final File iconFile) {
+ /**
+ * copy given Template Files, given Image File and given QuestionJSONFile to local resource directory for custom tasks
+ * (only used in Non-Guided Mode Integration)
+ * @return String with the error messages ("" if no erros happend)
+ */
+ public String writeDataNonGuidedMode() {
+
+ final Map cryslTemplateFile = integratorModel.getCryslTemplateFiles();
+
+ copyImage(integratorModel.getIconFile());
+ copyJSON(integratorModel.getJSONFile());
for (String key : cryslTemplateFile.keySet()) {
try {
- copyFileFromPath(cryslTemplateFile.get(key), key);
+ copyTemplate(cryslTemplateFile.get(key), key);
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ errors.append(Constants.ERROR_FILE_COPY + cryslTemplateFile.get(key).toString() + "\n");
}
}
- copyFileFromPath(iconFile);
- return getErrors().toString();
- }
-
- /**
- * Validate an XML file.
- *
- * @param helpLocation
- * @return
- */
- private boolean validateXMLFile(final File helpLocation) {
- final SAXReader reader = new SAXReader();
- reader.setValidation(false);
- try {
- reader.read(helpLocation);
- } catch (final DocumentException e) {
- Activator.getDefault().logError(e);
- appendFileErrors(helpLocation.getName());
- return false;
- }
- return true;
- }
-
- /**
- * For the sake of reusability.
- *
- * @param fileName
- */
- private void appendFileErrors(final String fileName) {
- getErrors().append("The contents of the file ");
- getErrors().append(fileName);
- getErrors().append(" are invalid.");
- getErrors().append("\n");
+ return errors.toString();
}
+
+
/**
- * Validate the provided JAR file before copying it to the target location.
- *
- * @param customLibLocation
- * @return a boolean value for the validity of the file.
+ * Copy the template file to the appropriate location for code generator + exportable zip.
+ * @param existingFileLocation one of the existing template files choosen by the user
+ * @param option identifier for given template file
+ * @throws IOException
*/
- private boolean validateJARFile(final File customLibLocation) {
- final boolean validFile = true;
- // Loop through the files, since the custom library is a directory.
- if (customLibLocation.isDirectory()) {
- for (final File tmpLibLocation : customLibLocation.listFiles()) {
- if (tmpLibLocation.getPath().endsWith(Constants.JAR_EXTENSION)) {
- ZipFile customLib;
- try {
- customLib = new ZipFile(tmpLibLocation);
- customLib.entries();
- customLib.close();
- } catch (final IOException ex) {
- Activator.getDefault().logError(ex);
- appendFileErrors(tmpLibLocation.getName());
- return false;
- }
- }
- }
+ private void copyTemplate(final File existingFileLocation, String option) throws IOException {
+ File parentFolder1 = new File(Constants.ECLIPSE_LOC_TEMP_DIR);
+ File parentFolder2 = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/template");
+ File templateFolder1 = new File(parentFolder1, integratorModel.getTrimmedTaskName() + option);
+ File templateFolder2 = new File(parentFolder2, integratorModel.getTrimmedTaskName() + option);
+
+ if (!templateFolder1.isDirectory()) {
+ templateFolder1.mkdir();
}
- return validFile;
- }
-
- /**
- * Validate the provided XSL file before copying it to the target location.
- *
- * @param xslFileLocation
- * @return a boolean value for the validity of the file.
- */
- private boolean validateXSLFile(final File xslFileLocation) {
- try {
- TransformerFactory.newInstance().newTransformer(new StreamSource(xslFileLocation));
- } catch (final TransformerConfigurationException e) {
- Activator.getDefault().logError(e);
- appendFileErrors(xslFileLocation.getName());
- return false;
+ if (!templateFolder2.isDirectory()) {
+ templateFolder2.mkdir();
}
- return true;
- }
- /**
- * Validate the provided JSON file before copying it to the target location.
- *
- * @param jsonFileLocation
- * @return a boolean value for the validity of the file.
- */
- private boolean validateJSONFile(final File jsonFileLocation) {
- try {
- final Gson gson = new Gson();
- final BufferedReader reader = new BufferedReader(new FileReader(jsonFileLocation));
- gson.fromJson(reader, Object.class);
- reader.close();
- return true;
- } catch (IOException e) {
- Activator.getDefault().logError(e);
- appendFileErrors(jsonFileLocation.getName());
- return false;
- }
+ File targetDirectory1 = new File(templateFolder1, integratorModel.getTrimmedTaskName() + Constants.JAVA_EXTENSION);
+ File targetDirectory2 = new File(templateFolder2, integratorModel.getTrimmedTaskName() + Constants.JAVA_EXTENSION);
+
+
+ Path path1 = existingFileLocation.toPath();
+ Path path2 = targetDirectory1.toPath();
+ Path path3 = targetDirectory2.toPath();
+
+ Activator.getDefault().logError("Copy " + existingFileLocation.getAbsolutePath() + " to " + targetDirectory1.getAbsolutePath());
+
+ Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used by the code generator
+
+ Files.copy(path1, path3, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used to make the exportable ZIP
}
-
-
- public void copyFileFromPath(final File existingFileLocation, String option) throws IOException {
- File parentFolder = Utils.getResourceFromWithin(Constants.codeTemplateFolder, "de.cognicrypt.codegenerator");
- File templateFolder = new File(parentFolder, getTrimmedTaskName() + option);
- if (!templateFolder.isDirectory()) {
- templateFolder.mkdir();
- }
- File resourceFromWithin = Utils.getResourceFromWithin(Constants.codeTemplateFolder + getTrimmedTaskName()
- + option + Constants.innerFileSeparator, "de.cognicrypt.codegenerator");
- File targetDirectory = new File(resourceFromWithin, getTrimmedTaskName() + Constants.JAVA_EXTENSION);
- if (targetDirectory != null) {
- Path path = existingFileLocation.toPath();
- Path path2 = targetDirectory.toPath();
- Files.copy(path, path2, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
- }
- }
-
/**
- * Copy the given file to the appropriate location.
- *
- * @param existingFileLocation
+ * Copy the image file to the appropriate location for code generator + exportable zip.
+ * @param existingFileLocation the existing image file choosen by the user
*/
- public void copyFileFromPath(final File existingFileLocation) {
- if (existingFileLocation.exists() && !existingFileLocation.isDirectory()) {
+ private void copyImage(final File existingFileLocation) {
File targetDirectory = null;
+ File targetDirectory2 = null;
try {
-
- if (existingFileLocation.getPath().endsWith(Constants.CFR_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.CFR_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.CFR_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.JS_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.CFR_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.JS_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.JSON_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.JSON_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.JSON_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.PNG_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.IMAGE_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.PNG_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.XSL_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.XSL_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.XSL_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.XML_EXTENSION)) {
- targetDirectory = new File(Utils.getResourceFromWithin(Constants.HELP_FILE_DIRECTORY_PATH,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.XML_EXTENSION);
- } else if (existingFileLocation.getPath().endsWith(Constants.JAVA_EXTENSION)) {
- File parentFolder = Utils.getResourceFromWithin(Constants.codeTemplateFolder,
- "de.cognicrypt.codegenerator");
- File templateFolder = new File(parentFolder, getTrimmedTaskName());
- if (!templateFolder.isDirectory()) {
- templateFolder.mkdir();
- }
- targetDirectory = new File(Utils.getResourceFromWithin(
- Constants.codeTemplateFolder + getTrimmedTaskName() + Constants.innerFileSeparator,
- "de.cognicrypt.codegenerator"), getTrimmedTaskName() + Constants.JAVA_EXTENSION);
+ if (existingFileLocation.getPath().endsWith(Constants.PNG_EXTENSION)) {
+ targetDirectory = new File(Constants.ECLIPSE_LOC_IMG_DIR, integratorModel.getTrimmedTaskName() + Constants.PNG_EXTENSION);
+ targetDirectory2 = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/res", integratorModel.getTrimmedTaskName() + Constants.PNG_EXTENSION);
} else {
- throw new Exception("Unknown file type.");
- }
-
- if (targetDirectory != null) {
- Files.copy(existingFileLocation.toPath(), targetDirectory.toPath(),
- StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
+ throw new Exception(Constants.ERROR_UNKNOWN_FILE_TYPE);
}
+ Activator.getDefault().logError("CopyNonCustom " + existingFileLocation.getAbsolutePath() + " to " + targetDirectory.getAbsolutePath());
+ Files.copy(existingFileLocation.toPath(), targetDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used by the code generator
+ Files.copy(existingFileLocation.toPath(), targetDirectory2.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used to make the exportable ZIP
} catch (final Exception e) {
Activator.getDefault().logError(e);
- getErrors().append("There was a problem copying file ");
- getErrors().append(existingFileLocation.getName());
- getErrors().append("\n");
+ errors.append(Constants.ERROR_FILE_COPY + existingFileLocation.getName() + "\n");
}
- // If we are dealing with a custom library location.
- } else if (existingFileLocation.exists() && existingFileLocation.isDirectory()) {
- final File tempDirectory = new File(Utils.getResourceFromWithin(Constants.JAR_FILE_DIRECTORY_PATH),
- getTrimmedTaskName() + Constants.innerFileSeparator);
- tempDirectory.mkdir();
- // Loop through all the containing files.
- for (final File customLibFile : existingFileLocation.listFiles()) {
- final File tmpFile = new File(
- tempDirectory.toString() + Constants.innerFileSeparator + customLibFile.getName());
- try {
- Files.copy(customLibFile.toPath(), tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING,
- StandardCopyOption.COPY_ATTRIBUTES);
- } catch (final IOException e) {
- Activator.getDefault().logError(e);
- getErrors().append("There was a problem copying file ");
- getErrors().append(existingFileLocation.getName());
- getErrors().append("\n");
- }
+ }
+
+ /**
+ * Copy the questionJSON file to the appropriate location for code generator + exportable zip.
+ * @param existingFileLocation the existing questionJSON file choosen by the user (only Non-Guided Mode)
+ */
+ private void copyJSON(final File existingFileLocation) {
+ File targetDirectory = null;
+ File targetDirectory2 = null;
+ try {
+ if (existingFileLocation.getPath().endsWith(Constants.JSON_EXTENSION)) {
+ targetDirectory = new File(Constants.ECLIPSE_LOC_TASKDESC_DIR, integratorModel.getTrimmedTaskName() + Constants.JSON_EXTENSION);
+ targetDirectory2 = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/res", integratorModel.getTrimmedTaskName() + Constants.JSON_EXTENSION);
+ } else {
+ throw new Exception(Constants.ERROR_UNKNOWN_FILE_TYPE);
}
+ Activator.getDefault().logError("CopyNonCustom " + existingFileLocation.getAbsolutePath() + " to " + targetDirectory.getAbsolutePath());
+ Files.copy(existingFileLocation.toPath(), targetDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used by the code generator
+ Files.copy(existingFileLocation.toPath(), targetDirectory2.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used to make the exportable ZIP
+
+ } catch (final Exception e) {
+ Activator.getDefault().logError(e);
+ errors.append(Constants.ERROR_FILE_COPY + existingFileLocation.getName() + "\n");
}
}
+
+
/**
- * Update the task.json file with the new Task.
+ * Update the task.json file with the new Task in the local resource directory for custom tasks and
+ * write it to appropriate location for the exportable ZIP
*
* @param task the Task to be added.
*/
public void writeTaskToJSONFile(final Task task) {
-
- BufferedReader reader = null;
- BufferedWriter writer = null;
+ BufferedReader reader;
+ BufferedWriter writer;
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
try {
reader = new BufferedReader(
- new FileReader(Utils.getResourceFromWithin(Constants.jsonTaskFile, "de.cognicrypt.codegenerator")));
+ new FileReader(new File(Constants.customjsonTaskFile)));
final List tasks = gson.fromJson(reader, new TypeToken>() {
}.getType());
// Add the new task to the list.
@@ -344,53 +249,39 @@ public void writeTaskToJSONFile(final Task task) {
reader.close();
writer = new BufferedWriter(
- new FileWriter(Utils.getResourceFromWithin(Constants.jsonTaskFile, "de.cognicrypt.codegenerator")));
+ new FileWriter(new File(Constants.customjsonTaskFile)));
+ gson.toJson(tasks, new TypeToken>() {
+ }.getType(), writer);
+ writer.close();
+
+ writer = new BufferedWriter(
+ new FileWriter(new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/res/task.json")));
gson.toJson(tasks, new TypeToken>() {
}.getType(), writer);
writer.close();
} catch (final IOException e) {
Activator.getDefault().logError(e);
- getErrors().append("There was a problem updating the task file.\n");
+ errors.append(Constants.ERROR_TASK_UPDATE);
}
}
-
-
/**
- * @param questions listOfAllQuestions
- * @throws IOException
- * @throws SAXException
- * @throws ParserConfigurationException
- * @throws TransformerException
+ * Build the questionJSON file to the appropriate location for code generator + exportable zip.
+ * @param questions
*/
- public void writeJSONFile(final ArrayList questions) {
-
- final SegregatesQuestionsIntoPages pageContent = new SegregatesQuestionsIntoPages(questions);
- final ArrayList pages = pageContent.getPages();
- boolean taskHasPageHelpContent = false;
- for (final Page page : pages) {
- for (final Question question : page.getContent()) {
- if (!question.getHelpText().isEmpty()) {
- taskHasPageHelpContent = true;
- break;
- }
- }
- }
+ public void writeJSONFile(final List questions) {
- /**
- * creates the xml file containing the help content of the task, adds the
- * location of the xml file in the plugin.xml file and sets the page help id
- */
- /*
- * try { new CreateAndModifyXmlfile(pages, getTaskName(),
- * taskHasPageHelpContent); } catch (IOException | ParserConfigurationException
- * | SAXException | TransformerException e) { e.printStackTrace(); }
- */
+ final SegregatesQuestionsIntoPages pageContent = new SegregatesQuestionsIntoPages();
+ final List pages = pageContent.getPages();
final File jsonFile = new File(
- Utils.getResourceFromWithin(Constants.JSON_FILE_DIRECTORY_PATH, "de.cognicrypt.codegenerator"),
- getTrimmedTaskName() + Constants.JSON_EXTENSION);
+ Constants.ECLIPSE_LOC_TASKDESC_DIR,
+ integratorModel.getTrimmedTaskName() + Constants.JSON_EXTENSION);
+
+ final File jsonFile2 = new File(
+ Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/res",
+ integratorModel.getTrimmedTaskName() + Constants.JSON_EXTENSION);
try {
final Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();
@@ -403,129 +294,165 @@ public void writeJSONFile(final ArrayList questions) {
// write the data into the .json file
writerForJsonFile.write(gson.toJson(pages));
writerForJsonFile.close();
+
+ final FileWriter writerForJsonFile2 = new FileWriter(jsonFile2);
+
+ // write the data into the .json file
+ writerForJsonFile2.write(gson.toJson(pages));
+ writerForJsonFile2.close();
} catch (final IOException e) {
e.printStackTrace();
}
+
if (!validateJSONFile(jsonFile)) {
jsonFile.delete();
}
}
+
+
/**
- * @param xslFileContents
+ * Validate the provided JSON file before copying it to the target location.
+ *
+ * @param jsonFileLocation
+ * @return a boolean value for the validity of the file.
*/
- private void writeXSLFile(final String xslFileContents) {
- final File xslFile = new File(Utils.getResourceFromWithin(Constants.XSL_FILE_DIRECTORY_PATH),
- getTrimmedTaskName() + Constants.XSL_EXTENSION);
-
+ private boolean validateJSONFile(final File jsonFileLocation) {
try {
- final PrintWriter writer = new PrintWriter(xslFile);
- writer.println(xslFileContents);
- writer.flush();
- writer.close();
- } catch (final FileNotFoundException e) {
+ final Gson gson = new Gson();
+ FileReader fileReader = new FileReader(jsonFileLocation);
+ final BufferedReader reader = new BufferedReader(fileReader);
+ gson.fromJson(reader, Object.class);
+ reader.close();
+ fileReader.close();
+ return true;
+ } catch (IOException e) {
Activator.getDefault().logError(e);
- getErrors().append("There was a problem wrting the XSL data.\n");
- }
-
- if (!validateXSLFile(xslFile)) {
- xslFile.delete();
- getErrors().append("The XSL data is invalid.\n");
+ appendFileErrors(jsonFileLocation.getName());
+ return false;
}
}
-
- private void writeCryslTemplateFile(final String cryslTemplateFile) {
- final File cryslDestFile = new File(Utils.getResourceFromWithin(Constants.codeTemplateFolder),
- getTrimmedTaskName() + ".java");
- try {
- final PrintWriter writer = new PrintWriter(cryslDestFile);
- writer.println(cryslTemplateFile);
- writer.flush();
- writer.close();
- } catch (final FileNotFoundException e) {
- Activator.getDefault().logError(e);
- getErrors().append("There was a problem wrting the Crysl Template data.\n");
- }
+
+ /**
+ * For the sake of reusability.
+ *
+ * @param fileName
+ */
+ private void appendFileErrors(final String fileName) {
+ errors.append("The contents of the file ");
+ errors.append(fileName);
+ errors.append(" are invalid.");
+ errors.append("\n");
}
-
- public void updateThePluginXMLFileWithHelpData(final String machineReadableTaskName) {
- File pluginXMLFile = Utils.getResourceFromWithin(Constants.PLUGIN_XML_FILE);
- if (!pluginXMLFile.exists()) {
- pluginXMLFile = Utils.getResourceFromWithin("src" + Constants.innerFileSeparator + ".."
- + Constants.innerFileSeparator + Constants.PLUGIN_XML_FILE);
- }
- final SAXReader reader = new SAXReader();
- Document pluginXMLDocument = null;
- reader.setValidation(false);
- try {
- pluginXMLDocument = reader.read(pluginXMLFile);
- } catch (final DocumentException e) {
- Activator.getDefault().logError(e);
+
+ /**
+ * convert a given File/Directory to a ZIP File (Used for creating the exportable ZIP in (Non-)Guided Mode)
+ * @param fileToZip
+ * @param fileName
+ * @param zipOut
+ * @throws IOException
+ */
+ public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
+ if (fileToZip.isHidden()) {
+ return;
}
- if (pluginXMLDocument != null) {
-
- final Element root = pluginXMLDocument.getRootElement();
- for (final Iterator extensionElement = root.elementIterator("extension"); extensionElement
- .hasNext();) {
- final Element currentExtensionElement = extensionElement.next();
- final Attribute point = currentExtensionElement.attribute("point");
- if (point != null && point.getValue().equals("org.eclipse.help.contexts")) {
- currentExtensionElement.addElement("contexts").addAttribute("file",
- Constants.HELP_FILE_DIRECTORY_PATH + machineReadableTaskName + Constants.XML_EXTENSION);
- }
+ if (fileToZip.isDirectory()) {
+ if (fileName.endsWith("/")) {
+ zipOut.putNextEntry(new ZipEntry(fileName));
+ zipOut.closeEntry();
+ } else {
+ zipOut.putNextEntry(new ZipEntry(fileName + "/"));
+ zipOut.closeEntry();
}
-
- try (FileWriter fileWriter = new FileWriter(pluginXMLFile)) {
- final OutputFormat format = OutputFormat.createPrettyPrint();
- final XMLWriter writer = new XMLWriter(fileWriter, format);
- writer.write(pluginXMLDocument);
- writer.close();
- } catch (final IOException e) {
- Activator.getDefault().logError(e);
+ File[] children = fileToZip.listFiles();
+ for (File childFile : children) {
+ zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
+ return;
+ }
+ FileInputStream fis = new FileInputStream(fileToZip);
+ ZipEntry zipEntry = new ZipEntry(fileName);
+ zipOut.putNextEntry(zipEntry);
+ byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
}
+ fis.close();
}
/**
- * Return the name of that task that is set for the file writes..
- *
- * @return
+ * unzip the exportable ZIP file choosen by the user
*/
- private String getTaskName() {
- return this.taskName;
- }
+ public static void unzipFile(String zipFile, File destDir) {
+ byte[] buffer = new byte[1024];
+ try {
+ ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
+ ZipEntry zipEntry = zis.getNextEntry();
+ while (zipEntry != null) {
+ File newFile = newFile(destDir, zipEntry);
+ if (zipEntry.isDirectory()) {
+ if (!newFile.isDirectory() && !newFile.mkdirs()) {
+ throw new IOException(Constants.ERROR_DIRECTORY_CREATION + newFile);
+ }
+ } else {
+ // fix for Windows-created archives
+ File parent = newFile.getParentFile();
+ if (!parent.isDirectory() && !parent.mkdirs()) {
+ throw new IOException(Constants.ERROR_DIRECTORY_CREATION + parent);
+ }
- /**
- * get machine-readable task name
- *
- * @return task name without non-alphanumerics
- */
- private String getTrimmedTaskName() {
- return getTaskName().replaceAll("[^A-Za-z0-9]", "");
+ // write file content
+ FileOutputStream fos = new FileOutputStream(newFile);
+ int len;
+ while ((len = zis.read(buffer)) > 0) {
+ fos.write(buffer, 0, len);
+ }
+ fos.close();
+ }
+ zipEntry = zis.getNextEntry();
+ }
+ zis.closeEntry();
+ zis.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
/**
- * Set the name of the task that is being written to File. The names of the
- * result files are set based on the provided task name.
- *
- * @param taskName
+ * helper function for unzipFile
+ * @param destinationDir
+ * @param zipEntry
+ * @return
+ * @throws IOException
*/
- private void setTaskName(final String taskName) {
- this.taskName = taskName;
- }
+ public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
+ File destFile = new File(destinationDir, zipEntry.getName());
- /**
- * @return the list of errors.
- */
- private StringBuilder getErrors() {
- return this.errors;
+ String destDirPath = destinationDir.getCanonicalPath();
+ String destFilePath = destFile.getCanonicalPath();
+
+ if (!destFilePath.startsWith(destDirPath + File.separator)) {
+ throw new IOException(Constants.ERROR_ENTRY_OUTSIDE_TARGETDIR + zipEntry.getName());
+ }
+
+ return destFile;
}
/**
- * @param set the string builder to maintain the list of errors.
+ * delete the given directory (used for clean up in the local ExportableTask directory)
+ * @param directoryToBeDeleted
+ * @return true if direcotry succesfully deleted
*/
- private void setErrors(final StringBuilder errors) {
- this.errors = errors;
+ public static boolean deleteDirectory(File directoryToBeDeleted) {
+ File[] allContents = directoryToBeDeleted.listFiles();
+ if (allContents != null) {
+ for (File file : allContents) {
+ deleteDirectory(file);
+ }
+ }
+ return directoryToBeDeleted.delete();
}
-
+
+
}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilitiesImportMode.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilitiesImportMode.java
new file mode 100644
index 000000000..00d59fce6
--- /dev/null
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/FileUtilitiesImportMode.java
@@ -0,0 +1,177 @@
+package de.cognicrypt.integrator.task.controllers;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
+import java.util.List;
+
+import com.google.common.reflect.TypeToken;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import de.cognicrypt.codegenerator.tasks.Task;
+import de.cognicrypt.core.Constants;
+import de.cognicrypt.integrator.task.Activator;
+import de.cognicrypt.integrator.task.models.IntegratorModel;
+
+public class FileUtilitiesImportMode {
+
+ private StringBuilder errors; // Maintain all the errors to display them on the wizard.
+ IntegratorModel integratorModel;
+
+ /**
+ * This class is used to copy the necessary files for Task Integration to the correct destinations
+ * where the Code Generator can use them (ImportMode)
+ * @author felix
+ *
+ */
+ public FileUtilitiesImportMode(){
+ super();
+ errors = new StringBuilder();
+ integratorModel = IntegratorModel.getInstance();
+ }
+
+ /**
+ * copy given template files, given image file and given questionJSON file to local resource directory for custom tasks
+ * (only used in Guided Mode Integration)
+ * @return String with the error messages ("" if no errors happened)
+ */
+ public String writeDataImportMode() {
+ String taskName = integratorModel.getImportFile().getName().replace(".zip", "");
+ integratorModel.setTaskName(taskName);
+ File iconLocation = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + taskName + "/res/" + taskName + ".png");
+ if(iconLocation.exists()) {
+ integratorModel.setLocationOfIconFile(iconLocation);
+ copyImage(iconLocation);
+ }else {
+ errors.append(Constants.ERROR_ICON_FILE_NOT_FOUND);
+ }
+ File jsonLocation = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + taskName + "/res/" + taskName + ".json");
+ if(iconLocation.exists()) {
+ integratorModel.setLocationOfIconFile(jsonLocation);
+ copyJSON(jsonLocation);
+ }else {
+ errors.append(Constants.ERROR_JSON_FILE_NOT_FOUND);
+ }
+ copyTemplatesImportMode();
+ FileUtilities.deleteDirectory(new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + taskName));
+ IntegratorModel.getInstance().setQuestionsJSONFile();
+ return errors.toString();
+ }
+
+ /**
+ * Copy the template files to the appropriate location for code generator
+ *
+ * @throws IOException
+ */
+ private void copyTemplatesImportMode(){
+ File templateDir = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + integratorModel.getTaskName() + "/template");
+ if(!templateDir.exists()) {
+ errors.append("ZIP invalid (Template Dir not found) \n");
+ return;
+ }
+ File[] templates = templateDir.listFiles();
+ if (templates != null) {
+ for (File f : templates) {
+ String destName = f.getName();
+ File destDir = new File(Constants.ECLIPSE_LOC_TEMP_DIR, destName);
+ destDir.mkdir();
+ File templateFile = f.listFiles()[0];
+ File dest = new File(destDir, integratorModel.getTrimmedTaskName() + ".java");
+ try {
+ Files.copy(templateFile.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING,
+ StandardCopyOption.COPY_ATTRIBUTES);
+ } catch (Exception e) {
+ errors.append(Constants.ERROR_FILE_COPY + f.toString() + "/n");
+ }
+
+ }
+ }else {
+ errors.append(Constants.ERROR_TEMPLATE_FILE_NOT_FOUND);
+ }
+ }
+
+
+ /**
+ * Copy the image file to the appropriate location for code generator
+ * @param existingFileLocation the existing image file from the exportable ZIP
+ */
+ private void copyImage(final File existingFileLocation) {
+ File targetDirectory = null;
+ try {
+ if (existingFileLocation.getPath().endsWith(Constants.PNG_EXTENSION)) {
+ targetDirectory = new File(Constants.ECLIPSE_LOC_IMG_DIR, IntegratorModel.getInstance().getTrimmedTaskName() + Constants.PNG_EXTENSION);
+ } else {
+ throw new Exception(Constants.ERROR_UNKNOWN_FILE_TYPE);
+ }
+ Activator.getDefault().logError("CopyNonCustom " + existingFileLocation.getAbsolutePath() + " to " + targetDirectory.getAbsolutePath());
+ Files.copy(existingFileLocation.toPath(), targetDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used by the code generato
+ } catch (final Exception e) {
+ Activator.getDefault().logError(e);
+ errors.append(Constants.ERROR_FILE_COPY);
+ errors.append(existingFileLocation.getName());
+ errors.append("\n");
+ }
+ }
+
+ /**
+ * Copy the questionJSON file to the appropriate location for code generator
+ * @param existingFileLocation the existing questionJSON file from the exportable ZIP
+ */
+ private void copyJSON(final File existingFileLocation) {
+ File targetDirectory = null;
+
+ try {
+ if (existingFileLocation.getPath().endsWith(Constants.JSON_EXTENSION)) {
+ targetDirectory = new File(Constants.ECLIPSE_LOC_TASKDESC_DIR, IntegratorModel.getInstance().getTrimmedTaskName() + Constants.JSON_EXTENSION);
+ } else {
+ throw new Exception(Constants.ERROR_UNKNOWN_FILE_TYPE);
+ }
+ Activator.getDefault().logError("CopyNonCustom " + existingFileLocation.getAbsolutePath() + " to " + targetDirectory.getAbsolutePath());
+ Files.copy(existingFileLocation.toPath(), targetDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //copy to folder structure which is used by the code generator
+
+ } catch (final Exception e) {
+ Activator.getDefault().logError(e);
+ errors.append(Constants.ERROR_FILE_COPY);
+ errors.append(existingFileLocation.getName());
+ errors.append("\n");
+ }
+ }
+
+
+ /**
+ * Update the task.json file with the new Task.
+ *
+ * @param task the Task to be added.
+ */
+ public void writeTaskToJSONFile(final Task task) {
+
+ BufferedReader reader = null;
+ BufferedWriter writer = null;
+ final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ try {
+ reader = new BufferedReader(
+ new FileReader(new File(Constants.customjsonTaskFile)));
+ final List tasks = gson.fromJson(reader, new TypeToken>() {}.getType());
+
+ // Add the new task to the list.
+ tasks.add(task);
+ reader.close();
+
+ writer = new BufferedWriter(
+ new FileWriter(new File(Constants.customjsonTaskFile)));
+ gson.toJson(tasks, new TypeToken>() {
+ }.getType(), writer);
+ writer.close();
+
+ } catch (final IOException e) {
+ Activator.getDefault().logError(e);
+ errors.append(Constants.ERROR_TASK_UPDATE);
+ }
+ }
+}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/SegregatesQuestionsIntoPages.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/SegregatesQuestionsIntoPages.java
index fd3b8b6db..6ae25ffd3 100644
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/SegregatesQuestionsIntoPages.java
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/SegregatesQuestionsIntoPages.java
@@ -9,25 +9,26 @@
import java.util.ArrayList;
import java.util.Collections;
+import java.util.List;
+
import de.cognicrypt.codegenerator.question.Answer;
import de.cognicrypt.codegenerator.question.Page;
import de.cognicrypt.codegenerator.question.Question;
import de.cognicrypt.core.Constants;
+import de.cognicrypt.integrator.task.models.IntegratorModel;
public class SegregatesQuestionsIntoPages {
- private ArrayList listOfAllQuestions;
- private ArrayList pages;
+ private List pages;
private int pageId = 0;
- public SegregatesQuestionsIntoPages(final ArrayList listOfAllQuestions) {
- setListOfAllQuestions(listOfAllQuestions);
- this.pages = new ArrayList<>();
- setPages(this.pages);
+ public SegregatesQuestionsIntoPages() {
+ pages = new ArrayList<>();
+ setPages(pages);
/**
* following loop adds the questions to different pages
*/
- for (final Question qstn : listOfAllQuestions) {
+ for (final Question qstn : IntegratorModel.getInstance().getQuestions()) {
// executes when question doesn't exists in any page
if (!questionExistsInAnyPage(qstn)) {
addQuestionToPage(qstn);
@@ -37,7 +38,7 @@ public SegregatesQuestionsIntoPages(final ArrayList listOfAllQuestions
/**
* following loop checks whether the questions in the page has branch or not,if not then updates the page next Id
*/
- for (final Page page : this.pages) {
+ for (final Page page : pages) {
boolean updatePageNextId = false;
for (final Question question : page.getContent()) {
if (!questionHasBranch(question)) {
@@ -51,21 +52,6 @@ public SegregatesQuestionsIntoPages(final ArrayList listOfAllQuestions
}
- /**
- * @return the lists of all questions
- */
- public ArrayList getListOfAllQuestions() {
- return this.listOfAllQuestions;
- }
-
- /**
- * sets the list of all question
- *
- * @param listOfAllQuestions the list containing all the questions
- */
- public void setListOfAllQuestions(final ArrayList listOfAllQuestions) {
- this.listOfAllQuestions = listOfAllQuestions;
- }
/**
* checks if question exists in any page or not
@@ -74,7 +60,7 @@ public void setListOfAllQuestions(final ArrayList listOfAllQuestions)
* @return true if the qstn exists in any page otherwise false
*/
private boolean questionExistsInAnyPage(final Question qstn) {
- for (final Page page : this.pages) {
+ for (final Page page : pages) {
for (final Question question : page.getContent()) {
if (question.getId() == qstn.getId()) {
return true;
@@ -136,11 +122,11 @@ else if (previousQuestionPage.getContent().size() == 3) {
private void addQuestionToNewPage(final Question qstn) {
final Page page = new Page();
page.setId(this.pageId);
- this.pageId++;
+ pageId++;
final ArrayList question = new ArrayList<>();
page.setContent(question);
page.getContent().add(qstn);
- this.pages.add(page);
+ pages.add(page);
/**
* executes when question has branch
*/
@@ -155,10 +141,7 @@ private void addQuestionToNewPage(final Question qstn) {
* @return true if the current question is the first question in the list of Questions
*/
private boolean isFirstQuestion(final Question qstn) {
- if (qstn.getId() == 0) {
- return true;
- }
- return false;
+ return qstn.getId() == 0;
}
/**
@@ -166,7 +149,7 @@ private boolean isFirstQuestion(final Question qstn) {
* @return the previous question
*/
private Question findPreviousQuestion(final Question qstn) {
- for (final Question question : this.listOfAllQuestions) {
+ for (final Question question : IntegratorModel.getInstance().getQuestions()) {
if (question.getId() == qstn.getId() - 1) {
return question;
}
@@ -213,7 +196,7 @@ private void updateAnsNextIdToPageId(final Question qstn) {
/**
* if the question is the last question then sets the answer next ID to -1
*/
- if (qstn.getId() == this.listOfAllQuestions.size() - 1) {
+ if (qstn.getId() == IntegratorModel.getInstance().getQuestions().size() - 1) {
for (final Answer ans : qstn.getAnswers()) {
ans.setNextID(Constants.ANSWER_NO_FOLLOWING_QUESTION_NEXT_ID);
}
@@ -221,7 +204,7 @@ private void updateAnsNextIdToPageId(final Question qstn) {
/**
* executes when the current question is not the last question
*/
- else if (qstn.getId() != this.listOfAllQuestions.size() - 1) {
+ else if (qstn.getId() != IntegratorModel.getInstance().getQuestions().size() - 1) {
final ArrayList ansNextIds = new ArrayList<>();
for (final Answer ans : qstn.getAnswers()) {
ansNextIds.add(ans.getNextID());
@@ -274,7 +257,7 @@ else if (qstn.getId() != this.listOfAllQuestions.size() - 1) {
* @return the question
*/
private Question questionWithId(final int id) {
- for (final Question question : this.listOfAllQuestions) {
+ for (final Question question : IntegratorModel.getInstance().getQuestions()) {
if (question.getId() == id) {
return question;
}
@@ -325,7 +308,7 @@ private void updatePageNextID(final Page page) {
* @param nextId answer next id
* @return the answer whose next id is equal to nextId
*/
- private Answer findAnswer(final ArrayList answers, final int nextId) {
+ private Answer findAnswer(final List answers, final int nextId) {
for (final Answer answer : answers) {
if (answer.getNextID() == nextId) {
return answer;
@@ -339,7 +322,7 @@ private Answer findAnswer(final ArrayList answers, final int nextId) {
* @return the page array
*/
- public ArrayList getPages() {
+ public List getPages() {
return this.pages;
}
@@ -348,7 +331,7 @@ public ArrayList getPages() {
*
* @param pages
*/
- public void setPages(final ArrayList pages) {
+ public void setPages(final List pages) {
this.pages = pages;
}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/ValidationUtils.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/ValidationUtils.java
new file mode 100644
index 000000000..964e3d1bf
--- /dev/null
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/ValidationUtils.java
@@ -0,0 +1,58 @@
+/********************************************************************************
+ * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
+ *
+
+ * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
+ ********************************************************************************/
+
+package de.cognicrypt.integrator.task.controllers;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+
+import de.cognicrypt.codegenerator.question.Answer;
+import de.cognicrypt.codegenerator.question.Question;
+import de.cognicrypt.codegenerator.tasks.Task;
+import de.cognicrypt.codegenerator.tasks.TaskJSONReader;
+import de.cognicrypt.integrator.task.models.IntegratorModel;
+
+public abstract class ValidationUtils {
+
+ /*
+ * Returns true if @taskName has already been added
+ */
+ public static boolean checkIfTaskNameAlreadyExists(final String taskName) {
+ final List existingTasks = TaskJSONReader.getTasks(); // required to validate the task name that is chosen by the user.
+ boolean taskNameAlreadyExists = false;
+
+ // Validation: check whether the name already exists.
+ for (final Task task : existingTasks) {
+ if (task.getName().toLowerCase(Locale.ENGLISH).equals(taskName.toLowerCase(Locale.ENGLISH)) || task.getDescription().toLowerCase(Locale.ENGLISH).equals(taskName.toLowerCase(Locale.ENGLISH))) {
+ taskNameAlreadyExists = true;
+ break;
+ }
+ }
+
+ return taskNameAlreadyExists;
+ }
+
+ /*
+ * Returns true if an added template is not used
+ */
+ public static boolean checkForUnusedIdentifiers() {
+ List questions = IntegratorModel.getInstance().getQuestions();
+
+ HashSet identifiers = new HashSet<>();
+
+ for(Question q : questions) {
+ for(Answer a : q.getAnswers()) {
+ if (a.getOption() != null) {
+ identifiers.add(a.getOption());
+ }
+ }
+ }
+
+ return identifiers.size() < IntegratorModel.getInstance().getIdentifiers().size();
+ }
+}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/Validator.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/Validator.java
deleted file mode 100644
index 7e456e477..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/Validator.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task.controllers;
-
-import java.util.List;
-import de.cognicrypt.codegenerator.tasks.Task;
-import de.cognicrypt.codegenerator.tasks.TaskJSONReader;
-
-public class Validator {
-
- public static boolean checkIfTaskNameAlreadyExists(final String taskName) {
- final List existingTasks = TaskJSONReader.getTasks(); // Required to validate the task name that is chosen by the user.
- boolean validString = true;
-
- // Validation : check whether the name already exists.
- for (final Task task : existingTasks) {
- if (task.getName().toLowerCase().equals(taskName.toLowerCase()) || task.getDescription().toLowerCase().equals(taskName.toLowerCase())) {
- validString = false;
- break;
- }
- }
-
- return validString;
- }
-
- public static String getValidXMLString(final String stringData) {
- return stringData.replace("<", "").replace(">", "").replace("&", "").replace("\'", "").replace("\"", "");
- }
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XSLStringGenerationAndManipulation.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XSLStringGenerationAndManipulation.java
deleted file mode 100644
index e536ddf46..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XSLStringGenerationAndManipulation.java
+++ /dev/null
@@ -1,360 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-/**
- *
- */
-package de.cognicrypt.integrator.task.controllers;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import org.clafer.instance.InstanceClafer;
-import org.dom4j.Attribute;
-import org.dom4j.Document;
-import org.dom4j.Element;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Display;
-import de.cognicrypt.codegenerator.featuremodel.clafer.InstanceGenerator;
-import de.cognicrypt.codegenerator.question.Answer;
-import de.cognicrypt.codegenerator.question.ClaferDependency;
-import de.cognicrypt.codegenerator.question.CodeDependency;
-import de.cognicrypt.codegenerator.question.Question;
-import de.cognicrypt.codegenerator.utilities.XMLClaferParser;
-import de.cognicrypt.core.Constants;
-import de.cognicrypt.integrator.task.Activator;
-
-public class XSLStringGenerationAndManipulation {
-
- /**
- * @param filePath
- * @param existingText
- * @param selected
- * @return
- */
- public static String generateXSLStringFromPath(final String filePath, final String existingText, final Point selected, final String stringToAdd) {
- final StringBuilder dataFromFile = new StringBuilder();
-
- final String xslStringBeforeAddingText =
- "\n\n\n\n\n\n\npackage ; \n\n";
- final String xslStringAfterAddingText = "\n\n\nimport ;\n\n";
-
- if (filePath != null) {
- final Path path = Paths.get(filePath);
- if (path.getFileName().toString().endsWith(".java") || path.getFileName().toString().endsWith(".JAVA") || path.getFileName().toString().endsWith(".txt")
- || path.getFileName().toString().endsWith(".TXT")) {
-
- // Check if the XSL tags have already been created. If yes then add the text at the cursor location.
- if (existingText.contains("\n");
- dataFromFile.append("package ;\n\n");
- dataFromFile.append("\n");
- appendTextFromFileToStringBuilder(dataFromFile, filePath);
- dataFromFile.append("\n");
- dataFromFile.append("");
- dataFromFile.append("\n");
- dataFromFile.append(existingText.substring(selected.y, existingText.length()));
-
- } else {
- dataFromFile.append(xslStringBeforeAddingText);
- appendTextFromFileToStringBuilder(dataFromFile, filePath);
- dataFromFile.append(xslStringAfterAddingText);
- }
-
- } else {
- appendTextFromFileToStringBuilder(dataFromFile, filePath);
- }
- } else {
- dataFromFile.append(xslStringBeforeAddingText);
- dataFromFile.append(stringToAdd);
- dataFromFile.append(xslStringAfterAddingText);
- }
-
- return dataFromFile.toString();
- }
-
- /**
- * Read the data from the file and add it to the StringBuilder.
- *
- * @param dataFromFile the StringBuilder.
- * @param filePath the location of the file to be read.
- */
- private static void appendTextFromFileToStringBuilder(final StringBuilder dataFromFile, final String filePath) {
- try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
-
- String line = br.readLine();
-
- while (line != null) {
- dataFromFile.append(line);
- dataFromFile.append(System.lineSeparator());
- line = br.readLine();
- }
- }
- catch (final FileNotFoundException e) {
- Activator.getDefault().logError(e);
- }
- catch (final IOException e) {
- Activator.getDefault().logError(e);
- }
-
- }
-
- /**
- * Set the colors to all the {@link XmlRegion}.
- *
- * @param regions the List of {@link XmlRegion}
- * @return returns the {@link StyleRange} for the given code.
- */
- public static List computeStyleForXMLRegions(final List regions) {
- final List styleRanges = new ArrayList();
- for (final XmlRegion xr : regions) {
-
- // The style itself depends on the region type
- // In this example, we use colors from the system
- final StyleRange sr = new StyleRange();
- switch (xr.getXmlRegionType()) {
- case MARKUP:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_DARK_GREEN);
- break;
-
- case ATTRIBUTE:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_DARK_RED);
- break;
-
- case ATTRIBUTE_VALUE:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_BLUE);
- break;
-
- case MARKUP_VALUE:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY);
- break;
- case COMMENT:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_GRAY);
- break;
- case INSTRUCTION:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
- break;
- case CDATA:
- sr.foreground = Display.getDefault().getSystemColor(SWT.COLOR_DARK_GREEN);
- break;
- case WHITESPACE:
- break;
- default:
- break;
- }
-
- // Define the position and limit
- sr.start = xr.getStart();
- sr.length = xr.getEnd() - xr.getStart();
- styleRanges.add(sr);
- }
-
- return styleRanges;
- }
-
- public static void getListOfValidSuggestionsForXSLTags(final String jsFilePath, final String taskName, final String taskDescription, final List questions,
- final HashMap tagValueTagData) {
- if (jsFilePath != null) {
- final InstanceGenerator instanceGenerator = new InstanceGenerator(jsFilePath, "c0_" + taskName, taskDescription);
-
- // This will contain the xml strings that are generated for every -> operator encountered.
- final List xmlStrings = new ArrayList();
-
- final XMLClaferParser xmlParser = new XMLClaferParser();
- // this will remain empty for the first instance, that contains no -> operators.
- final HashMap constraints = new HashMap<>();
- final List instances = instanceGenerator.generateInstances(constraints);
- if (instances.size() > 0) {
- final InstanceClafer initialInstance = instances.get(0);
- xmlStrings.add(xmlParser.displayInstanceValues(initialInstance, constraints));
-
- // Questions needed to get the answer that has a constraint with the -> operator.
- // QuestionsJSONReader reader = new QuestionsJSONReader();
- // TODO update this to read the data generated in the questions page.
-
- // List pages = reader.getPages("/src/main/resources/TaskDesc/SymmetricEncryption.json");
-
- // for (Page page : pages) {
- for (final Question question : questions) {
- for (final Answer answer : question.getAnswers()) {
- if (answer.getClaferDependencies() != null) {
- for (final ClaferDependency claferDependency : answer.getClaferDependencies()) {
- if ("->".equals(claferDependency.getOperator())) {
- xmlStrings.add(getXMLForNewAlgorithmInsertion(question, answer, xmlParser, instanceGenerator, claferDependency));
-
- }
- } // clafer dependency loop
- } // clafer dependency check
- if (answer.getCodeDependencies() != null) {
- for (final CodeDependency codeDependency : answer.getCodeDependencies()) {
- // xmlStrings.get(0).elementByID(Constants.Code).addElement(codeDependency.getOption()).addText(codeDependency.getValue() + "");
- final Element root = xmlStrings.get(0).getRootElement();
-
- for (final Iterator element = root.elementIterator(Constants.Code); element.hasNext();) {
- final Element codeElement = element.next();
- // TODO fix question page to not create null code dependencies
- if (codeDependency != null && codeDependency.getOption() != null && codeDependency.getValue() != null) {
- codeElement.addElement(codeDependency.getOption()).addText(codeDependency.getValue() + "");
- }
- }
- } // code dependency loop
- } // code dependency check
- } // answer loop
- } // question loop
- // } // page loop
-
- // Process each xml document that is generated.
- for (final Document xmlDocument : xmlStrings) {
- processXMLDocument(xmlDocument, tagValueTagData);
- }
- }
-
- }
- }
-
- /**
- * This method is created to be able to exit the nested loops as soon as the correct instance is found.
- *
- * @param question The question object from the outer loop.
- * @param answer The answer object from the outer loop.
- * @param xmlParser This object is needed to generate the xml string.
- * @param instanceGenerator This object is needed to generate the instances
- * @param claferDependency The claferDependency from the outer loop
- * @return
- */
- private static Document getXMLForNewAlgorithmInsertion(final Question question, final Answer answer, final XMLClaferParser xmlParser, final InstanceGenerator instanceGenerator,
- final ClaferDependency claferDependency) {
- final HashMap constraints = new HashMap<>();
- constraints.put(question, answer);
- final String constraintOnType = claferDependency.getAlgorithm();
- for (final InstanceClafer instance : instanceGenerator.generateInstances(constraints)) {
- for (final InstanceClafer childInstance : instance.getChildren()) {
- // check if the name of the constraint on the clafer instance is the same as the one on the clafer dependency from the outer loop.
- if (childInstance.getType().getName().equals(constraintOnType)) {
- return xmlParser.displayInstanceValues(instance, constraints);
- }
- } // child instance loop
- } // instance loop
- return null;
- }
-
- /**
- * Process the XML document here to generate values to be displayed to the user for selection.
- *
- * @param xmlDocument The serialized object representing the generated XML string.
- * @param tagValueTagData
- */
- private static void processXMLDocument(final Document xmlDocument, final HashMap tagValueTagData) {
- final Element root = xmlDocument.getRootElement();
- // send a slash as a parameter to keep the recursive method as generic as possible.
- processElement(root, "", Constants.SLASH, true, tagValueTagData);
- }
-
- /**
- * This method will process each element individually, and is called recursively to process nested tags.
- *
- * @param xmlElement The element under consideration.
- * @param existingNameToBeDisplayed The string that will be displayed to the user for selection.
- * @param existingDataForXSLDocument The actual string that will be added to the code base on the selection that is done by the user.
- * @param isRoot true if the element is the root element.
- * @param tagValueTagData
- */
- private static void processElement(final Element xmlElement, final String existingNameToBeDisplayed, final String existingDataForXSLDocument, final boolean isRoot,
- final HashMap tagValueTagData) {
- final StringBuilder tagNameToBeDisplayed = new StringBuilder();
- final StringBuilder tagDataForXSLDocument = new StringBuilder();
-
- tagNameToBeDisplayed.append(existingNameToBeDisplayed);
- tagDataForXSLDocument.append(existingDataForXSLDocument);
-
- if (!isRoot) {
- tagNameToBeDisplayed.append(Constants.DOT);
- }
- tagNameToBeDisplayed.append(xmlElement.getName());
- tagDataForXSLDocument.append(Constants.SLASH);
- tagDataForXSLDocument.append(xmlElement.getName());
-
- final int builderDisplayDataSizeTillRoot = tagNameToBeDisplayed.length();
- final int builderTagDataSizeTillRoot = tagDataForXSLDocument.length();
-
- if (xmlElement.attributeCount() == 0 && !xmlElement.elementIterator().hasNext()) {
- // adding the tag, if there are no attributes.
- tagValueTagData.put(tagNameToBeDisplayed.toString(), tagDataForXSLDocument.toString());
- } else {
- for (final Iterator attribute = xmlElement.attributeIterator(); attribute.hasNext();) {
- final Attribute attributeData = attribute.next();
- // TODO the name of the task can be fixed here based on what is chosen before.
-
- if (tagNameToBeDisplayed.length() > builderDisplayDataSizeTillRoot) {
- tagNameToBeDisplayed.delete(builderDisplayDataSizeTillRoot, tagNameToBeDisplayed.length());
- }
-
- if (tagDataForXSLDocument.length() > builderTagDataSizeTillRoot) {
- tagDataForXSLDocument.delete(builderTagDataSizeTillRoot, tagDataForXSLDocument.length());
- }
-
- tagNameToBeDisplayed.append(Constants.DOT);
- tagNameToBeDisplayed.append("@" + attributeData.getName());
-
- tagDataForXSLDocument.append(Constants.ATTRIBUTE_BEGIN);
- tagDataForXSLDocument.append(attributeData.getName());
- tagDataForXSLDocument.append(Constants.ATTRIBUTE_END);
-
- tagValueTagData.put(tagNameToBeDisplayed.toString(), tagDataForXSLDocument.toString());
-
- // Adding the loop for the remaining elements within the attribute loop to have unique tags based on the attributes.
- for (final Iterator element = xmlElement.elementIterator(); element.hasNext();) {
- final Element currentElement = element.next();
- // do not consider the imports tag. The data is not relevant.
- if (!currentElement.getName().equals("Imports")) {
- if (tagNameToBeDisplayed.length() > builderDisplayDataSizeTillRoot) {
- tagNameToBeDisplayed.delete(builderDisplayDataSizeTillRoot, tagNameToBeDisplayed.length());
- }
-
- if (isRoot) {
- if (tagDataForXSLDocument.length() > builderTagDataSizeTillRoot) {
- tagDataForXSLDocument.delete(builderTagDataSizeTillRoot, tagDataForXSLDocument.length());
- }
- }
- // recursive call
- processElement(currentElement, tagNameToBeDisplayed.toString(), tagDataForXSLDocument.toString(), false, tagValueTagData);
- }
- }
- }
- }
-
- // A similar loop outside the attribute loop to check the tags that are not nested.
- for (final Iterator element = xmlElement.elementIterator(); element.hasNext();) {
- final Element currentElement = element.next();
- // do not consider the imports tag. The data is not relevant.
- if (!currentElement.getName().equals("Imports")) {
- if (tagNameToBeDisplayed.length() > builderDisplayDataSizeTillRoot) {
- tagNameToBeDisplayed.delete(builderDisplayDataSizeTillRoot, tagNameToBeDisplayed.length());
- }
-
- if (isRoot) {
- if (tagDataForXSLDocument.length() > builderTagDataSizeTillRoot) {
- tagDataForXSLDocument.delete(builderTagDataSizeTillRoot, tagDataForXSLDocument.length());
- }
- }
- // recursive call
- processElement(currentElement, tagNameToBeDisplayed.toString(), tagDataForXSLDocument.toString(), false, tagValueTagData);
- }
- }
- }
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegion.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegion.java
deleted file mode 100644
index ef4a96bd3..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegion.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-/****************************************************************************
- * Copyright (c) 2012, Vincent Zurczak - All rights reserved. This source file is released under the terms of the BSD license. Redistribution and use in source and binary forms,
- * with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of
- * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
- * THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *****************************************************************************/
-
-package de.cognicrypt.integrator.task.controllers;
-
-/**
- * A XML region, with a type, a start position (included) and an end position (excluded).
- *
- * A XML region is limited in the range [start, end[
- *
- *
- * @author Vincent Zurczak
- * @version 1.0 (tag version)
- */
-public class XmlRegion {
-
- public enum XmlRegionType {
- INSTRUCTION, COMMENT, CDATA, MARKUP, ATTRIBUTE, MARKUP_VALUE, ATTRIBUTE_VALUE, WHITESPACE, UNEXPECTED;
- }
-
- private final XmlRegionType xmlRegionType;
- private final int start;
- private int end;
-
- /**
- * Constructor.
- *
- * @param xmlRegionType
- * @param start
- */
- public XmlRegion(final XmlRegionType xmlRegionType, final int start) {
- this.xmlRegionType = xmlRegionType;
- this.start = start;
- }
-
- /**
- * Constructor.
- *
- * @param xmlRegionType
- * @param start
- * @param end
- */
- public XmlRegion(final XmlRegionType xmlRegionType, final int start, final int end) {
- this(xmlRegionType, start);
- this.end = end;
- }
-
- /**
- * @return the end
- */
- public int getEnd() {
- return this.end;
- }
-
- /**
- * @param end the end to set
- */
- public void setEnd(final int end) {
- this.end = end;
- }
-
- /**
- * @return the xmlRegionType
- */
- public XmlRegionType getXmlRegionType() {
- return this.xmlRegionType;
- }
-
- /**
- * @return the start
- */
- public int getStart() {
- return this.start;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object #toString()
- */
- @Override
- public String toString() {
- return this.xmlRegionType + " [" + this.start + ", " + this.end + "[";
- }
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegionAnalyzer.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegionAnalyzer.java
deleted file mode 100644
index c2c599eb4..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/controllers/XmlRegionAnalyzer.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-/****************************************************************************
- * Copyright (c) 2012, Vincent Zurczak - All rights reserved. This source file is released under the terms of the BSD license. Redistribution and use in source and binary forms,
- * with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of
- * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
- * THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *****************************************************************************/
-
-package de.cognicrypt.integrator.task.controllers;
-
-import java.util.ArrayList;
-import java.util.List;
-import de.cognicrypt.integrator.task.controllers.XmlRegion.XmlRegionType;
-
-/**
- * A class that builds style ranges from a XML input.
- *
- * @author Vincent Zurczak
- * @version 1.0 (tag version)
- */
-public class XmlRegionAnalyzer {
-
- private int offset;
-
- /**
- * Analyzes a XML document.
- *
- * @param xml the XML text (may be an invalid XML document)
- * @return a non-null list of XML positions
- */
- public List analyzeXml(final String xml) {
-
- this.offset = 0;
- final List positions = new ArrayList();
- while (this.offset < xml.length()) {
-
- // White spaces
- analyzeWhitespaces(xml, positions);
- if (this.offset >= xml.length()) {
- break;
- }
-
- // "<" can be several things
- final char c = xml.charAt(this.offset);
- if (c == '<') {
- if (analyzeInstruction(xml, positions)) {
- continue;
- }
- if (analyzeComment(xml, positions)) {
- continue;
- }
- if (analyzeMarkup(xml, positions)) {
- continue;
- }
- if (analyzeCData(xml, positions)) {
- continue;
- }
-
- positions.add(new XmlRegion(XmlRegionType.UNEXPECTED, this.offset, xml.length()));
- break;
- }
-
- // "/" and "/>" can only indicate a mark-up
- else if (c == '/' && xml.charAt(this.offset + 1) == '>' || c == '>') {
- if (analyzeMarkup(xml, positions)) {
- continue;
- }
-
- positions.add(new XmlRegion(XmlRegionType.UNEXPECTED, this.offset, xml.length()));
- break;
- }
-
- // Other things can be...
- if (analyzeAttribute(xml, positions)) {
- continue;
- }
- if (analyzeAttributeValue(xml, positions)) {
- continue;
- }
- if (analyzeMarkupValue(xml, positions)) {
- continue;
- }
-
- positions.add(new XmlRegion(XmlRegionType.UNEXPECTED, this.offset, xml.length()));
- break;
- }
-
- return positions;
- }
-
- /**
- * Tries to analyze a XML instruction.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeInstruction(final String xml, final List positions) {
-
- boolean result = false;
- int newPos = this.offset;
- if (newPos < xml.length() && xml.charAt(newPos) == '<' && ++newPos < xml.length() && xml.charAt(newPos) == '?') {
-
- while (++newPos < xml.length() && xml.charAt(newPos) != '>') {
- newPos = xml.indexOf('?', newPos);
- }
-
- if (xml.charAt(newPos) == '>') {
- positions.add(new XmlRegion(XmlRegionType.INSTRUCTION, this.offset, newPos + 1));
- this.offset = newPos + 1;
- result = true;
- }
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a XML comment.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeComment(final String xml, final List positions) {
-
- boolean result = false;
- int newPos = this.offset;
- if (xml.charAt(newPos) == '<' && ++newPos < xml.length() && xml.charAt(newPos) == '!' && ++newPos < xml.length() && xml.charAt(newPos) == '-' && ++newPos < xml.length()
- && xml.charAt(newPos) == '-') {
-
- int seq = 0;
- while (seq != 3 && ++newPos < xml.length()) {
- final char c = xml.charAt(newPos);
- seq = c == '-' && seq < 2 || c == '>' && seq == 2 ? seq + 1 : 0;
- }
-
- if (seq == 3) {
- newPos++;
- }
-
- positions.add(new XmlRegion(XmlRegionType.COMMENT, this.offset, newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a XML mark-up.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeMarkup(final String xml, final List positions) {
-
- int newPos = this.offset;
- boolean result = false;
-
- // "<..."
- if (xml.charAt(newPos) == '<') {
-
- // Do not process a CData section or a comment as a mark-up
- if (newPos + 1 < xml.length() && xml.charAt(newPos + 1) == '!') {
- return false;
- }
-
- // Mark-up name
- char c = '!';
- while (newPos < xml.length() && (c = xml.charAt(newPos)) != '>' && !Character.isWhitespace(c)) {
- newPos++;
- }
-
- if (c == '>') {
- newPos++;
- }
-
- positions.add(new XmlRegion(XmlRegionType.MARKUP, this.offset, newPos));
- this.offset = newPos;
- result = true;
- }
-
- // "/>"
- else if (xml.charAt(newPos) == '/' && ++newPos < xml.length() && xml.charAt(newPos) == '>') {
-
- positions.add(new XmlRegion(XmlRegionType.MARKUP, this.offset, ++newPos));
- this.offset = newPos;
- result = true;
- }
-
- // "attributes... >"
- else if (xml.charAt(newPos) == '>') {
- positions.add(new XmlRegion(XmlRegionType.MARKUP, this.offset, ++newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a XML attribute.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeAttribute(final String xml, final List positions) {
-
- // An attribute value follows a mark-up
- for (int i = positions.size() - 1; i >= 0; i--) {
- final XmlRegion xr = positions.get(i);
- if (xr.getXmlRegionType() == XmlRegionType.WHITESPACE) {
- continue;
- }
-
- if (xr.getXmlRegionType() == XmlRegionType.ATTRIBUTE_VALUE) {
- break;
- }
-
- if (xr.getXmlRegionType() == XmlRegionType.MARKUP) {
- final char c = xml.charAt(xr.getEnd() - 1);
- if (c != '>') {
- break;
- }
- }
-
- return false;
- }
-
- // Analyze what we have...
- boolean result = false;
- int newPos = this.offset;
- char c;
- while (newPos < xml.length() && (c = xml.charAt(newPos)) != '=' && c != '/' && c != '>' && !Character.isWhitespace(c)) {
- newPos++;
- }
-
- // Found one?
- if (newPos != this.offset) {
- positions.add(new XmlRegion(XmlRegionType.ATTRIBUTE, this.offset, newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a mark-up's value.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeMarkupValue(final String xml, final List positions) {
-
- // A mark-up value follows a mark-up
- for (int i = positions.size() - 1; i >= 0; i--) {
- final XmlRegion xr = positions.get(i);
- if (xr.getXmlRegionType() == XmlRegionType.WHITESPACE) {
- continue;
- }
-
- if (xr.getXmlRegionType() == XmlRegionType.MARKUP || xr.getXmlRegionType() == XmlRegionType.COMMENT) {
- final char c = xml.charAt(xr.getEnd() - 1);
- if (c == '>') {
- break;
- }
- }
-
- return false;
- }
-
- // Read...
- boolean result = false;
- int newPos = this.offset;
- while (newPos < xml.length() && xml.charAt(newPos) != '<') {
- newPos++;
- }
-
- // We read something and this something is not only made up of white spaces
- if (this.offset != newPos) {
-
- // We must here repair the list if the previous position is made up of white spaces
- final XmlRegion xr = positions.get(positions.size() - 1);
- int start = this.offset;
- if (xr.getXmlRegionType() == XmlRegionType.WHITESPACE) {
- start = xr.getStart();
- positions.remove(xr);
- }
-
- positions.add(new XmlRegion(XmlRegionType.MARKUP_VALUE, start, newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a XML attribute's value.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeAttributeValue(final String xml, final List positions) {
-
- // An attribute value follows an attribute
- for (int i = positions.size() - 1; i >= 0; i--) {
- final XmlRegion xr = positions.get(i);
- if (xr.getXmlRegionType() == XmlRegionType.WHITESPACE) {
- continue;
- }
-
- if (xr.getXmlRegionType() == XmlRegionType.ATTRIBUTE) {
- break;
- }
-
- return false;
- }
-
- // Analyze what we have
- boolean result = false;
- int newPos = this.offset;
- if (xml.charAt(newPos) == '=') {
- analyzeWhitespaces(xml, positions);
-
- int cpt = 0;
- char previous = '!';
- while (++newPos < xml.length()) {
- final char c = xml.charAt(newPos);
- if (previous != '\\' && c == '"') {
- cpt++;
- }
-
- previous = c;
- if (cpt == 2) {
- newPos++;
- break;
- }
- }
-
- positions.add(new XmlRegion(XmlRegionType.ATTRIBUTE_VALUE, this.offset, newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze a CDATA section.
- *
- * @param xml the XML text
- * @param positions the positions already found
- * @return true if it recognized a XML instruction
- */
- boolean analyzeCData(final String xml, final List positions) {
-
- boolean result = false;
- int newPos = this.offset;
- if (xml.charAt(newPos) == '<' && ++newPos < xml.length() && xml.charAt(newPos) == '!' && ++newPos < xml.length() && xml.charAt(newPos) == '[' && ++newPos < xml.length()
- && xml.charAt(newPos) == 'C' && ++newPos < xml.length() && xml.charAt(newPos) == 'D' && ++newPos < xml.length() && xml.charAt(newPos) == 'A' && ++newPos < xml.length()
- && xml.charAt(newPos) == 'T' && ++newPos < xml.length() && xml.charAt(newPos) == 'A' && ++newPos < xml.length() && xml.charAt(newPos) == '[') {
-
- int cpt = 0;
- while (++newPos < xml.length()) {
- final char c = xml.charAt(newPos);
- if (cpt < 2 && c == ']' || cpt == 2 && c == '>') {
- cpt++;
- } else {
- cpt = 0;
- }
-
- if (cpt == 3) {
- newPos++;
- break;
- }
- }
-
- positions.add(new XmlRegion(XmlRegionType.CDATA, this.offset, newPos));
- this.offset = newPos;
- result = true;
- }
-
- return result;
- }
-
- /**
- * Tries to analyze white spaces.
- *
- * If white spaces are found, a XML position is stored and the offset is updated.
- *
- *
- * @param xml the XML text
- * @param positions the positions already found
- */
- void analyzeWhitespaces(final String xml, final List positions) {
-
- int i = this.offset;
- while (i < xml.length() && Character.isWhitespace(xml.charAt(i))) {
- i++;
- }
-
- if (i != this.offset) {
- positions.add(new XmlRegion(XmlRegionType.WHITESPACE, this.offset, i));
- this.offset = i;
- }
- }
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/exceptions/ErrorMessageException.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/exceptions/ErrorMessageException.java
new file mode 100644
index 000000000..5cac27eb6
--- /dev/null
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/exceptions/ErrorMessageException.java
@@ -0,0 +1,20 @@
+package de.cognicrypt.integrator.task.exceptions;
+
+public class ErrorMessageException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ private String text;
+
+ public ErrorMessageException(String msg) {
+ super(msg);
+ }
+
+ public ErrorMessageException(String msg, String text) {
+ super(msg);
+ this.text = text;
+ }
+
+ public String getText() {
+ return text;
+ }
+}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/IntegratorModel.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/IntegratorModel.java
new file mode 100644
index 000000000..20c5f89d2
--- /dev/null
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/IntegratorModel.java
@@ -0,0 +1,485 @@
+/********************************************************************************
+ * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
+ *
+
+ * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
+ ********************************************************************************/
+
+/**
+ *
+ */
+package de.cognicrypt.integrator.task.models;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.util.*;
+import java.util.zip.ZipOutputStream;
+
+import de.cognicrypt.codegenerator.question.Answer;
+import de.cognicrypt.codegenerator.question.Question;
+import de.cognicrypt.codegenerator.tasks.Task;
+import de.cognicrypt.core.Constants;
+import de.cognicrypt.core.Constants.CodeGenerators;
+import de.cognicrypt.integrator.task.controllers.FileUtilities;
+import de.cognicrypt.integrator.task.controllers.FileUtilitiesImportMode;
+import de.cognicrypt.integrator.task.controllers.ValidationUtils;
+import de.cognicrypt.integrator.task.exceptions.ErrorMessageException;
+
+public final class IntegratorModel {
+ private File locationOfCryslTemplate;
+ private File iconFile;
+ private File jsonFile;
+ private File locationImportFile;
+ private boolean isGuidedModeChosen;
+ private boolean isImportModeChosen;
+ private final Task task;
+
+ private Map cryslTemplateFiles;
+ private final List questions;
+
+ private static IntegratorModel instance = new IntegratorModel();
+
+ /**
+ *
+ * @return singleton object
+ */
+ public static IntegratorModel getInstance() {
+ return instance;
+ }
+
+ /**
+ * Resets the singleton object that contains the plugin state
+ */
+ public static void resetInstance() {
+ instance = new IntegratorModel();
+ }
+
+ private IntegratorModel() {
+ super();
+ task = new Task();
+ cryslTemplateFiles = new HashMap();
+ questions = new ArrayList<>();
+ }
+
+
+ /**
+ *
+ * @param templateFilePath to be added
+ * @return true if the added template was the first one
+ * @throws ErrorMessageException if warning has to be shown
+ */
+ public boolean addTemplate(String templateFilePath) throws ErrorMessageException {
+
+ boolean newTaskName = false;
+
+ if (templateFilePath == null) {
+ return false; // user canceled the file dialog
+ }
+ // Set the task name or verify that it's equal
+ String[] filePathParts = templateFilePath.split("(\\/|\\\\)");
+ String taskName = filePathParts[filePathParts.length - 1].replace(".java", "");
+
+ if(ValidationUtils.checkIfTaskNameAlreadyExists(taskName)) { // can not be tested because TaskJSONReader requires the plugin bundle
+ throw new ErrorMessageException(Constants.ERROR_TASK_ALREADY_INTEGRATED);
+ }
+
+ if (getTaskName() == null) {
+ setTaskName(taskName);
+ newTaskName = true;
+ }else if (!taskName.contentEquals(IntegratorModel.getInstance().getTaskName())) {
+ throw new ErrorMessageException(Constants.ERROR_DIFFERENT_TASK_NAME);
+ }
+
+ // Extract package line from the template's source code
+ String packageLine = "";
+
+ Scanner scanner;
+ try {
+ scanner = new Scanner(new File(templateFilePath));
+ } catch (FileNotFoundException e1) {
+ throw new ErrorMessageException(Constants.ERROR_FILE_NOT_FOUND);
+ }
+
+ while ("".contentEquals(packageLine)) {
+
+ if(!scanner.hasNextLine()) {
+ scanner.close();
+ throw new ErrorMessageException(Constants.ERROR_NO_PACKAGE);
+ }
+
+ String[] expr = scanner.nextLine().split(";");
+
+ // Lines may contain multiple expressions
+ for(String e : expr) {
+ String line = e.trim();
+ if (line.startsWith("package")) {
+ packageLine = line;
+ break;
+ }
+ if (line.contains("class")) {
+ break;
+ }
+ }
+
+ }
+ scanner.close();
+
+ // Extract identifier
+ String[] packageParts = packageLine.split("\\.");
+ String templateIdentifier = packageParts[packageParts.length - 1].replace(taskName, "").replace(";", "");
+
+ cryslTemplateFiles.put(templateIdentifier, new File(templateFilePath));
+
+ return newTaskName;
+ }
+
+ /**
+ * @throws ErrorMessageException if templates is empty or single template's identifier does not match the task name (task information page is incomplete)
+ */
+ public void checkTemplatesDec() throws ErrorMessageException {
+ // Template list is empty
+ if(isTemplatesEmpty()) {
+ throw new ErrorMessageException(Constants.ERROR_BLANK_TEMPLATE_LIST);
+ }
+ // Single template identifier does not match the task name
+ if(getIdentifiers().size() == 1 && !getIdentifiers().get(0).isEmpty()) {
+ throw new ErrorMessageException(Constants.ERROR_SINGLE_TEMPLATE_ID);
+ }
+ }
+
+ /**
+ *
+ * @param templateIdentifier to be removed
+ * @return true if last template was removed
+ * @throws ErrorMessageException if template is used in an answer and therefor not removed
+ */
+ public boolean removeTemplate(String templateIdentifier) throws ErrorMessageException {
+
+ for(Question q : questions) {
+ for(Answer a : q.getAnswers()) {
+ if(a.getOption().contentEquals(templateIdentifier)) {
+ throw new ErrorMessageException(Constants.ERROR_TEMPLATE_IS_USED_IN_ANSWER);
+ }
+ }
+ }
+
+ cryslTemplateFiles.remove(templateIdentifier);
+
+ if(isTemplatesEmpty()) {
+ setTaskName(null);
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Adds a question to the plugin state
+ */
+ public void addQuestion() throws ErrorMessageException {
+ int questionID = questions.size();
+
+ if (questionID > 0) {
+ throw new ErrorMessageException(Constants.ERROR_MULTIPLE_QUESTIONS_NOT_SUPPORTED);
+ }
+ Question questionDetails = new Question();
+ questionDetails.setQuestionText("");
+ questionDetails.setHelpText("");
+ questionDetails.setAnswers(new ArrayList());
+ questionDetails.setId(questionID);
+
+ questions.add(questionDetails);
+ }
+
+ /**
+ * Deletes the question
+ *
+ * @param questionIndex index of the question to be deleted
+ */
+ public void removeQuestion(int questionIndex) {
+
+ questions.remove(questionIndex);
+
+ int qID = 0;
+ for (Question qstn : questions) {
+ qstn.setId(qID++);
+ }
+ }
+
+ /**
+ * Creates a new answer and adds it to the question
+ * @param questionIndex
+ */
+ public void addAnswer(int questionIndex) {
+ int answerIndex = questions.get(questionIndex).getAnswers().size();
+
+ Answer a = new Answer();
+ a.setValue("");
+ a.setOption(getIdentifiers().get(answerIndex % getIdentifiers().size()));
+
+ if(answerIndex == 0) {
+ a.setDefaultAnswer(true);
+ }
+
+ questions.get(questionIndex).getAnswers().add(a);
+ }
+
+ /**
+ * Removes an answer and updates the default answer
+ * @param answerIndex to be removed from the question
+ * @param questionIndex
+ */
+ public void removeAnswer(int questionIndex, int answerIndex) {
+
+ boolean wasDefaultAnswer = getAnswer(questionIndex, answerIndex).isDefaultAnswer();
+
+ getQuestion(questionIndex).getAnswers().remove(answerIndex);
+
+ if(wasDefaultAnswer && !getQuestion(questionIndex).getAnswers().isEmpty()) {
+ getAnswer(questionIndex, 0).setDefaultAnswer(true);
+ }
+ }
+
+ /**
+ *
+ * @param questionIndex
+ * @throws ErrorMessageException if question text is empty
+ */
+ public void checkQuestionDec(int questionIndex) throws ErrorMessageException {
+ if(getQuestion(questionIndex).getQuestionText().isEmpty()) {
+ throw new ErrorMessageException(Constants.ERROR_MESSAGE_BLANK_QUESTION_NAME);
+ }
+ }
+
+ /**
+ *
+ * @param questionIndex
+ * @throws ErrorMessageException if no answers were given or an answer's text is empty
+ */
+ public void checkAnswersDec(int questionIndex) throws ErrorMessageException {
+
+ ArrayList answers = getQuestions().get(questionIndex).getAnswers();
+
+ if(answers.isEmpty()) {
+ throw new ErrorMessageException(Constants.ERROR_BLANK_ANSWERS_LIST);
+ }
+
+ boolean isAnswerTextEmpty = false;
+
+ for(Answer a : answers) {
+ isAnswerTextEmpty |= a.getValue().isEmpty();
+ }
+
+ if(isAnswerTextEmpty) {
+ throw new ErrorMessageException(Constants.ERROR_EMPTY_ANSWER_TEXT);
+ }
+ }
+
+ /**
+ *
+ * @return true if an identifier is not used in any answer
+ */
+ public boolean checkForUnusedIdentifiers() {
+ return !isImportModeChosen && isGuidedModeChosen && getIdentifiers().size() > 1 && ValidationUtils.checkForUnusedIdentifiers();
+ }
+
+ /**
+ * Copies the task using FileUtilities
+ * @throws ErrorMessageException if something goes wrong during copy
+ */
+ public void copyTask() throws ErrorMessageException {
+ setQuestionsJSONFile();
+
+ final FileUtilities fileUtilities = new FileUtilities();
+ final FileUtilitiesImportMode fileUtilitiesImportMode = new FileUtilitiesImportMode();
+
+ String fileWriteAttemptResult;
+
+ if (isImportModeChosen) {
+ FileUtilities.unzipFile(locationImportFile.toString(), new File(Constants.ECLIPSE_LOC_EXPORT_DIR));
+ fileWriteAttemptResult = fileUtilitiesImportMode.writeDataImportMode();
+ if ("".equals(fileWriteAttemptResult)) {
+ task.setImage(task.getName().replaceAll("[^A-Za-z0-9]", ""));
+ task.setCodeGen(CodeGenerators.CrySL);
+ fileUtilitiesImportMode.writeTaskToJSONFile(task);
+ } else {
+ throw new ErrorMessageException(fileWriteAttemptResult, Constants.ERROR_PROBLEMS_WITH_ZIP);
+ }
+ }else{
+ File taskDir = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName());
+ taskDir.mkdir();
+
+ File templateDir = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName() + "/template");
+ templateDir.mkdir();
+
+ File resourceDir = new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName() + "/res");
+ resourceDir.mkdir();
+
+ if (isGuidedModeChosen) {
+ fileWriteAttemptResult = fileUtilities.writeData();
+ if (getIdentifiers().size() == 1) {
+ fileUtilities.writeJSONFile(new ArrayList());
+ } else {
+ fileUtilities.writeJSONFile(getQuestions());
+ }
+ } else {
+ fileWriteAttemptResult = fileUtilities.writeDataNonGuidedMode();
+ }
+
+ if ("".equals(fileWriteAttemptResult)) {
+ task.setImage(task.getName().replaceAll("[^A-Za-z0-9]", ""));
+ task.setCodeGen(CodeGenerators.CrySL);
+ fileUtilities.writeTaskToJSONFile(task);
+
+ try {
+ String sourceFile = Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName();
+ FileOutputStream fos = new FileOutputStream(
+ Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName() + ".zip");
+ ZipOutputStream zipOut = new ZipOutputStream(fos);
+ File fileToZip = new File(sourceFile);
+
+ FileUtilities.zipFile(fileToZip, fileToZip.getName(), zipOut);
+ zipOut.close();
+ fos.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ FileUtilities.deleteDirectory(new File(Constants.ECLIPSE_LOC_EXPORT_DIR + "/" + task.getName()));
+ } else {
+ throw new ErrorMessageException(fileWriteAttemptResult, Constants.ERROR_PROBLEMS_WITH_FILES);
+ }
+ }
+
+ }
+
+ public String getTaskName() {
+ return task.getName();
+ }
+
+ /**
+ *
+ * @return task name without special characters
+ */
+ public String getTrimmedTaskName() {
+ return getTaskName().replaceAll("[^A-Za-z0-9]", "");
+ }
+
+
+ public void setTaskName(final String taskName) {
+ task.setName(taskName);
+
+
+ if(taskName != null) {
+ task.setDescription(taskName);
+ }
+ }
+
+ public void setQuestionsJSONFile() {
+ task.setQuestionsJSONFile(Constants.ECLIPSE_LOC_TASKDESC_DIR + "/" + getTaskName() + Constants.JSON_EXTENSION);
+ }
+
+ public File getIconFile() {
+ return iconFile;
+ }
+
+ public void setLocationOfIconFile(File locationOfIconFile) {
+ this.iconFile = locationOfIconFile;
+ }
+
+ public File getImportFile() {
+ return locationImportFile;
+ }
+
+ public void setLocationOfImportFile(File locationOfImportFile) {
+ this.locationImportFile = locationOfImportFile;
+ }
+
+ public File getJSONFile() {
+ return this.jsonFile;
+ }
+
+ public void setJSONFile(final File locationOfJSONFile) {
+ this.jsonFile = locationOfJSONFile;
+ }
+
+ public boolean isGuidedModeChosen() {
+ return this.isGuidedModeChosen;
+ }
+
+ public void setGuidedModeChosen(final boolean isGuidedModeChosen) {
+ this.isGuidedModeChosen = isGuidedModeChosen;
+ }
+
+ public boolean isImportModeChosen() {
+ return this.isImportModeChosen;
+ }
+
+ public void setImportModeChosen(final boolean isImportModeChosen) {
+ this.isImportModeChosen = isImportModeChosen;
+ }
+
+ public Task getTask() {
+ return this.task;
+ }
+
+ public String getTaskDescription() {
+ return task.getTaskDescription();
+ }
+
+ public void setTaskDescription(final String taskDescription) {
+ task.setTaskDescription(taskDescription);
+ }
+
+ public String getDescription() {
+ return task.getDescription();
+ }
+
+ public void setDescription(String description) {
+ task.setDescription(description);
+ }
+
+ public File getLocationOfCryslTemplate() {
+ return locationOfCryslTemplate;
+ }
+
+ public void setLocationOfCryslTemplate(File locationOfCryslTemplate) {
+ this.locationOfCryslTemplate = locationOfCryslTemplate;
+ }
+
+ public Map getCryslTemplateFiles() {
+ return cryslTemplateFiles;
+ }
+
+ public boolean isTemplatesEmpty() {
+ return cryslTemplateFiles.isEmpty();
+ }
+
+
+ public boolean contains(String identifier) {
+ return cryslTemplateFiles.containsKey(identifier);
+ }
+
+ public List getIdentifiers(){
+ ArrayList identifiers = new ArrayList();
+ identifiers.addAll(cryslTemplateFiles.keySet());
+ return identifiers;
+ }
+
+ public File getTemplate(String identifier){
+ return cryslTemplateFiles.get(identifier);
+ }
+
+ public List getQuestions() {
+ return questions;
+ }
+
+ public Question getQuestion(int questionIndex) {
+ return questions.get(questionIndex);
+ }
+
+ public Answer getAnswer(int questionIndex, int answerIndex) {
+ return questions.get(questionIndex).getAnswers().get(answerIndex);
+ }
+}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/ModelAdvancedMode.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/ModelAdvancedMode.java
deleted file mode 100644
index c84a6fa8e..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/ModelAdvancedMode.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-/**
- *
- */
-package de.cognicrypt.integrator.task.models;
-
-import java.io.File;
-import java.util.HashMap;
-
-import de.cognicrypt.codegenerator.tasks.Task;
-import de.cognicrypt.core.Constants;
-
-public class ModelAdvancedMode {
-
- private String nameOfTheTask;
- private File locationOfCustomLibrary;
- private File locationOfClaferFile;
- private File locationOfXSLFile;
- private File locationOfCryslTemplate;
- private File locationOfIconFile;
- private File locationOfJSONFile;
- private File locationOfHelpXMLFile;
- private boolean isCustomLibraryRequired;
- private boolean isGuidedModeChosen;
- // private boolean isGuidedModeForced;
- private final Task task;
- private String description;
- private String taskDescription;
- private HashMap crylTemplatesWithOption;
-
- public ModelAdvancedMode() {
- super();
- this.task = new Task();
- }
-
- /**
- * Generate a name for the task based on the input given by the user and return it.
- *
- * @param stringTaskName
- * @return
- */
- private String getMachineReadableName(final String stringTaskName) {
- final String[] split = stringTaskName.split(" ");
- final StringBuilder machineReadable = new StringBuilder();
- if (stringTaskName.length() > 0) {
- for (final String string : split) {
- machineReadable.append(string.substring(0, 1).toUpperCase());
- machineReadable.append(string.substring(1));
- }
- }
-
- return machineReadable.toString();
- }
-
- /**
- * @return the nameOfTheTask
- */
- public String getNameOfTheTask() {
- return this.nameOfTheTask;
- }
-
- /**
- * @param nameOfTheTask the nameOfTheTask to set
- */
- public void setNameOfTheTask(final String nameOfTheTask) {
- this.nameOfTheTask = getMachineReadableName(nameOfTheTask); // generate the task name that will be used as the machine readable identifier for the task.
- setDescription(nameOfTheTask); // This is the human readable name entered by the user.
- }
-
- public File getLocationOfIconFile() {
- return locationOfIconFile;
- }
-
- public void setLocationOfIconFile(File locationOfIconFile) {
- this.locationOfIconFile = locationOfIconFile;
- }
-
- /**
- * @return the locationOfCustomLibrary
- */
- public File getLocationOfCustomLibrary() {
- return this.locationOfCustomLibrary;
- }
-
- /**
- * @param locationOfCustomLibrary the locationOfCustomLibrary to set
- */
- public void setLocationOfCustomLibrary(final File locationOfCustomLibrary) {
- this.locationOfCustomLibrary = locationOfCustomLibrary;
- }
-
- /**
- * @return the locationOfClaferFile
- */
- public File getLocationOfClaferFile() {
- return this.locationOfClaferFile;
- }
-
- /**
- * @param locationOfClaferFile the locationOfClaferFile to set
- */
- public void setLocationOfClaferFile(final File locationOfClaferFile) {
- this.locationOfClaferFile = locationOfClaferFile;
- }
-
-
- /**
- * @return the locationOfXSLFile
- */
- public File getLocationOfXSLFile() {
- return this.locationOfXSLFile;
- }
-
- /**
- * @param locationOfXSLFile the locationOfXSLFile to set
- */
- public void setLocationOfXSLFile(final File locationOfXSLFile) {
- this.locationOfXSLFile = locationOfXSLFile;
- }
-
- /**
- * @return the locationOfJSONFile
- */
- public File getLocationOfJSONFile() {
- return this.locationOfJSONFile;
- }
-
- /**
- * @param locationOfJSONFile the locationOfJSONFile to set
- */
- public void setLocationOfJSONFile(final File locationOfJSONFile) {
- this.locationOfJSONFile = locationOfJSONFile;
- }
-
- /**
- * @return the isGuidedModeChosen
- */
- public boolean isGuidedModeChosen() {
- return this.isGuidedModeChosen;
- }
-
- /**
- * @param isGuidedModeChosen the isGuidedModeChosen to set
- */
- public void setGuidedModeChosen(final boolean isGuidedModeChosen) {
- this.isGuidedModeChosen = isGuidedModeChosen;
- }
- /* *//**
- * @return the isGuidedModeForced
- */
- /*
- * public boolean isGuidedModeForced() { return isGuidedModeForced; }
- *//**
- * @param isGuidedModeForced the isGuidedModeForced to set
- *//*
- * private void setGuidedModeForced(boolean isGuidedModeForced) { this.isGuidedModeForced = isGuidedModeForced; }
- */
-
- /**
- * @return the isCustomLibraryRequired
- */
- public boolean isCustomLibraryRequired() {
- return this.isCustomLibraryRequired;
- }
-
- /**
- * @param isCustomLibraryRequired the isCustomLibraryRequired to set
- */
- public void setCustomLibraryRequired(final boolean isCustomLibraryRequired) {
- this.isCustomLibraryRequired = isCustomLibraryRequired;
- }
-
- /**
- * @return the task
- */
- public Task getTask() {
- return this.task;
- }
-
- /**
- * Generate the Task instance from the advanced mode model.
- */
- public void setTask() {
- this.task.setName(getNameOfTheTask());
- this.task.setDescription(getDescription());
- this.task.setModelFile(Constants.CFR_FILE_DIRECTORY_PATH + getNameOfTheTask() + Constants.JS_EXTENSION);
- this.task.setQuestionsJSONFile(Constants.JSON_FILE_DIRECTORY_PATH + getNameOfTheTask() + Constants.JSON_EXTENSION);
- this.task.setTaskDescription(getTaskDescription() == null ? "" : getTaskDescription());
- this.task.setCodeTemplate(Constants.XSL_FILE_DIRECTORY_PATH + getNameOfTheTask() + Constants.XSL_EXTENSION);
- this.task.setAdditionalResources(Constants.JAR_FILE_DIRECTORY_PATH + getNameOfTheTask());
- }
-
- /**
- * @return the description
- */
- public String getDescription() {
- return this.description;
- }
-
- /**
- * @param description the description to set
- */
- public void setDescription(final String description) {
- this.description = description;
- }
-
- /**
- * @return the taskDescryption
- */
- public String getTaskDescription() {
- return this.taskDescription;
- }
-
- /**
- * @param taskDescription the taskDescryption to set
- */
- public void setTaskDescription(final String taskDescription) {
- this.taskDescription = taskDescription;
- }
-
- /**
- * @return the locationOfHelpXMLFile
- */
- public File getLocationOfHelpXMLFile() {
- return this.locationOfHelpXMLFile;
- }
-
- /**
- * @param locationOfHelpXMLFile the locationOfHelpXMLFile to set
- */
- public void setLocationOfHelpXMLFile(final File locationOfHelpXMLFile) {
- this.locationOfHelpXMLFile = locationOfHelpXMLFile;
- }
-
- public File getLocationOfCryslTemplate() {
- return locationOfCryslTemplate;
- }
-
- public void setLocationOfCryslTemplate(File locationOfCryslTemplate) {
- this.locationOfCryslTemplate = locationOfCryslTemplate;
- }
-
- public HashMap getCrylTemplatesWithOption() {
- return crylTemplatesWithOption;
- }
-
- public void setCrylTemplatesWithOption(HashMap crylTemplatesWithOption) {
- this.crylTemplatesWithOption = crylTemplatesWithOption;
- }
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLAttribute.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLAttribute.java
deleted file mode 100644
index 82372e5b1..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLAttribute.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task.models;
-
-import de.cognicrypt.core.Constants;
-
-public class XSLAttribute {
-
- private String XSLAttributeName;
- private String XSLAttributeData;
-
- /**
- * For consistency, the name for XSLAttribute should come from the Array of String for the attributes associated to the {@code XSLTags} in {@link Constants} class.
- *
- * @param xSLAttributeName the name of the XSLAttribute.
- * @param xSLAttributeData the value for the XSLAttribute.
- */
- public XSLAttribute(final String xSLAttributeName, final String xSLAttributeData) {
- super();
- setXSLAttributeName(xSLAttributeName);
- setXSLAttributeData(xSLAttributeData);
- }
-
- /**
- * @return the name of the XSLAttribute.
- */
- public String getXSLAttributeName() {
- return this.XSLAttributeName;
- }
-
- /**
- * @param xSLAttributeName set the name of the XSLAttribute. For consistency, the name for XSLAttribute should come from the Array of String for the attributes associated to the
- * {@code XSLTags} in {@link Constants} class.
- */
- public void setXSLAttributeName(final String xSLAttributeName) {
- this.XSLAttributeName = xSLAttributeName;
- }
-
- /**
- * @return the XSLAttribute value.
- */
- public String getXSLAttributeData() {
- return this.XSLAttributeData;
- }
-
- /**
- * @param xSLAttributeData set the value for the XSLAttribute.
- */
- public void setXSLAttributeData(final String xSLAttributeData) {
- this.XSLAttributeData = xSLAttributeData;
- }
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLTag.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLTag.java
deleted file mode 100644
index 9fd8cfa82..000000000
--- a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/models/XSLTag.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/********************************************************************************
- * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
- *
-
- * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
- ********************************************************************************/
-
-package de.cognicrypt.integrator.task.models;
-
-import java.util.ArrayList;
-import de.cognicrypt.core.Constants;
-import de.cognicrypt.core.Constants.XSLTags;
-
-public class XSLTag {
-
- private Constants.XSLTags XSLTagDetails; // Variable to hold all the XSL tag data.
- private ArrayList XSLAttributes; // Variable to hold the selected tag attributes.
-
- /**
- * @param xSLTagDetails This detail come from the enumeration {@code XSLTags} in {@link Constants} class. These include the XSLTagFaceName, XSLBeginTag, XSLEndTag and an
- * ArrayList of all possible attributes (XSLAttribute)
- * @param xSLAttributes This is an ArrayList of type {@link XSLAttribute} that are actually chosen.
- */
- public XSLTag(final XSLTags xSLTagDetails, final ArrayList xSLAttributes) {
- super();
- setXSLTagDetails(xSLTagDetails);
- setXSLAttributes(xSLAttributes);
- }
-
- /**
- * @return XSLTagDetails the constant from {@code XSLTags} in {@link Constants} passed to the constructor.
- */
- public Constants.XSLTags getXSLTagDetails() {
- return this.XSLTagDetails;
- }
-
- /**
- * @param xSLTagDetails set the constant from {@code XSLTags} in {@link Constants}.
- */
- private void setXSLTagDetails(final Constants.XSLTags xSLTagDetails) {
- this.XSLTagDetails = xSLTagDetails;
- }
-
- /**
- * @return the ArrayList of type {@link XSLAttribute}.
- */
- public ArrayList getXSLAttributes() {
- return this.XSLAttributes;
- }
-
- /**
- * @param xSLAttributes set the ArrayList<{@link XSLAttribute}>.
- */
- private void setXSLAttributes(final ArrayList xSLAttributes) {
- this.XSLAttributes = xSLAttributes;
- }
-
- /**
- * Overridden toString().
- *
- * First generate a String from ArrayList of type {@link XSLAttribute} such that it is in the form {@code ' XSLAttributeName1 = "XSLAttributeData1"' ...}
- *
- * A String for the complete XSLTag is generated, by appending the XSLBeginTag, the attribute string, and the XSLEndTag. XSLTags may have an empty XSLEndTag.
- */
- @Override
- public String toString() {
- final StringBuilder tagString = new StringBuilder();
- final StringBuilder attributeString = new StringBuilder();
-
- // Generate the string for the attributes.
- for (final XSLAttribute attribute : getXSLAttributes()) {
- attributeString.append(" ");
- attributeString.append(attribute.getXSLAttributeName());
- attributeString.append("=\"");
- attributeString.append(attribute.getXSLAttributeData());
- attributeString.append("\"");
- }
-
- tagString.append(getXSLTagDetails().getXSLBeginTag());
- // The location of the attribute string insertion changes if there is no end tag. e.g.
- int VALUE_TO_GET_LOCATION_TO_INSERT_ATTRIBUTES = 1;
- if (getXSLTagDetails().getXSLEndTag().equals("")) {
- VALUE_TO_GET_LOCATION_TO_INSERT_ATTRIBUTES = 2;
- }
- tagString.insert(getXSLTagDetails().getXSLBeginTag().length() - VALUE_TO_GET_LOCATION_TO_INSERT_ATTRIBUTES, attributeString.toString());
- tagString.append(getXSLTagDetails().getXSLEndTag());
-
- return tagString.toString();
- }
-
-}
diff --git a/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/widgets/AnswerGroup.java b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/widgets/AnswerGroup.java
new file mode 100644
index 000000000..6eeaf1d5d
--- /dev/null
+++ b/plugins/de.cognicrypt.integrator.task/src/main/java/de/cognicrypt/integrator/task/widgets/AnswerGroup.java
@@ -0,0 +1,143 @@
+/********************************************************************************
+ * Copyright (c) 2015-2019 TU Darmstadt, Paderborn University
+ *
+
+ * http://www.eclipse.org/legal/epl-2.0. SPDX-License-Identifier: EPL-2.0
+ ********************************************************************************/
+
+package de.cognicrypt.integrator.task.widgets;
+
+import java.util.List;
+
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Combo;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Group;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+import de.cognicrypt.codegenerator.question.Answer;
+import de.cognicrypt.core.Constants;
+import de.cognicrypt.integrator.task.models.IntegratorModel;
+
+public class AnswerGroup extends Group {
+
+ private Text txtAnswer;
+ private Combo possibleIdentifiers;
+
+ /**
+ * Create the composite.
+ *
+ * @param parent
+ * @param style
+ */
+ public AnswerGroup(final Composite parent, final int style, final int answerIndex, final int questionIndex) {
+ super(parent, style);
+
+ Answer answer = IntegratorModel.getInstance().getAnswer(questionIndex, answerIndex);
+
+ txtAnswer = new Text(this, SWT.BORDER);
+ txtAnswer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true));
+
+ if (answer.getValue() != null) {
+ txtAnswer.setText(answer.getValue());
+ }
+ txtAnswer.addModifyListener(new ModifyListener() {
+
+ @Override
+ public void modifyText(ModifyEvent e) {
+ answer.setValue(txtAnswer.getText());
+ ((QuestionInformationComposite) parent.getParent().getParent()).checkAnswersDec();
+ }
+ });
+
+ possibleIdentifiers = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
+ possibleIdentifiers.setItems(IntegratorModel.getInstance().getIdentifiers().toArray(new String[0]));
+
+ if (answer.getOption() != null) {
+ String selected = answer.getOption();
+ possibleIdentifiers.select(IntegratorModel.getInstance().getIdentifiers().indexOf(selected));
+ }
+
+ possibleIdentifiers.addSelectionListener(new SelectionListener() {
+
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ answer.setOption(possibleIdentifiers.getText());
+ }
+
+ @Override
+ public void widgetDefaultSelected(SelectionEvent e) {
+ answer.setOption(possibleIdentifiers.getText());
+ }
+ });
+
+
+ final Button btnDefaultAnswer = new Button(this, SWT.RADIO);
+
+ final List