public class ShowAppFactoryPerspective extends Action {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public void run() {
    try {
      LoginAction loginAction = new LoginAction();
      loginAction.login(true, true);

    } catch (Exception e) {
      log.error("Cannot open AppFactory perspective", e);
    }
  }

  public String getText() {
    return "Switch to AppFactory perspective";
  }

  public ImageDescriptor getImageDescriptor() {
    return ImageDescriptor.createFromImage(
        SWTResourceManager.getImage(this.getClass(), "/icons/appfac.png"));
  }

  public String getDescription() {
    return "Switch to AppFactory perspective";
  }
}
public class CloudConnectorImportWizard extends Wizard {

  private ImportCloudConnectorDetailsWizardPage detailWizardPage;
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
  private static final String DIR_DOT_METADATA = ".metadata";
  private static final String DIR_CONNECTORS = ".Connectors";

  public void init(IStructuredSelection selection) {
    detailWizardPage = new ImportCloudConnectorDetailsWizardPage(selection);
  }

  public void addPages() {
    addPage(detailWizardPage);
    super.addPages();
  }

  public boolean performFinish() {
    String source = detailWizardPage.getCloudConnectorPath();
    try {
      ZipFile zipFile = new ZipFile(source);
      String[] segments = source.split(Pattern.quote(File.separator));
      String zipFileName = segments[segments.length - 1].split(".zip")[0];
      // String destination =
      // detailWizardPage.getSelectedProject().getLocation().toOSString()+File.separator+"cloudConnectors"+File.separator+zipFileName;
      String destination =
          detailWizardPage.getSelectedProject().getWorkspace().getRoot().getLocation().toString()
              + File.separator
              + DIR_DOT_METADATA
              + File.separator
              + DIR_CONNECTORS
              + File.separator
              + zipFileName;
      zipFile.getFile();
      zipFile.extractAll(destination);
      IUpdateGMFPlugin updateGMFPlugin = GMFPluginDetails.getiUpdateGMFPlugin();
      if (updateGMFPlugin != null) {
        updateGMFPlugin.updateOpenedEditors();
      }
      /*
       * Refresh the project.
       */
      detailWizardPage.getSelectedProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (ZipException e) {
      log.error("Error while extracting the connector zip", e);
    } catch (CoreException e) {
      log.error("Cannot refresh the project", e);
    }
    return true;
  }
}
public class ProjectList extends AbstractListDataProvider {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public List<ListData> getListData(String modelProperty, ProjectDataModel model) {

    List<ListData> list = new ArrayList<ListData>();

    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    final String EXTENSIONPOINT_ID = "org.wso2.developerstudio.eclipse.capp.artifacts.provider";
    IConfigurationElement[] config =
        Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSIONPOINT_ID);

    for (IConfigurationElement element : config) {
      Object obj = null;
      try {
        obj = element.createExecutableExtension("class");
      } catch (CoreException ex) {
        log.error("Error executing CappArtifactsListProvider extension ", ex);
      }

      if (obj instanceof CappArtifactsListProvider) {

        CappArtifactsListProvider provider = (CappArtifactsListProvider) obj;
        String nature = element.getAttribute("nature");
        for (IProject project : projects) {
          try {
            if (project.isOpen() && project.hasNature(nature)) {
              List<ListData> listReceivedFromprovider = null;
              listReceivedFromprovider = provider.getArtifactsListForCappExport(project);
              list.addAll(listReceivedFromprovider);
            }
          } catch (Exception e) {
            log.error("Error getting artifacts from extension", e);
          }
        }
      }
    }

    return list;
  }
}
public class CarbonServerBehavior32 extends CarbonServerBehaviour {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private void checkClosed(IModule[] module) throws CoreException {
    for (int i = 0; i < module.length; i++) {
      if (module[i] instanceof DeletedModule) {
        IStatus status =
            new Status(
                IStatus.ERROR,
                CorePlugin.PLUGIN_ID,
                0,
                NLS.bind(GenericServerCoreMessages.canNotPublishDeletedModule, module[i].getName()),
                null);
        throw new CoreException(status);
      }
    }
  }

  public void publishModule(int kind, int deltaKind, IModule[] module, IProgressMonitor monitor)
      throws CoreException {
    IModule m = module[module.length - 1];
    if (deltaKind == ADDED) {
      checkClosed(module);
      ServerController.getInstance()
          .getServerManager()
          .publishServiceModule(getServer().getId(), "", m.getName());
    } else if (deltaKind == REMOVED) {
      ServerController.getInstance()
          .getServerManager()
          .unpublishServiceModule(getServer().getId(), "", m.getName());
    } else {
      checkClosed(module);
      // To add any new services
      ServerController.getInstance()
          .getServerManager()
          .hotUpdateServiceModule(getServer().getId(), "", m.getName());
    }
    setModulePublishState(module, null);
  }

  private void setModulePublishState(IModule[] module, IStatus[] status) throws CoreException {
    if (module == null) return;
    for (int i = 0; i < module.length; i++) {
      if (status == null
          || status.length < i
          || status[i] == null
          || status[i].getSeverity() == IStatus.OK) {
        setModulePublishState(module, IServer.PUBLISH_STATE_NONE);
      } else {
        if (IStatus.ERROR == status[i].getSeverity()) {
          setModulePublishState(module, IServer.PUBLISH_STATE_UNKNOWN);
          throw new CoreException(status[i]);
        }
      }
    }
  }

  protected void doServerStartedTasks() {
    super.doServerStartedTasks();
    doBrowserPopup();
  }

  protected void doServerStoppedTasks() {}

  private void doBrowserPopup() {
    Boolean popupBrowser = CarbonServer32Utils.isServerStartBrowserPopup(getServer());
    if (popupBrowser != null && popupBrowser) {
      CarbonUploadServiceRequestUtil uoloadServiceRequestUtil =
          CarbonUploadServiceRequestUtil.getInstance();
      uoloadServiceRequestUtil.popupExternalBrowser(
          CommonOperations.getLocalServerPort(getServer())
              + CarbonServer32Utils.getWebContextRoot(getServer())
              + "/carbon");
    }
  }

  protected String getVmArguments() {
    String vmArguments = super.getVmArguments();
    Boolean enableOSGIConsole = CarbonServer32Utils.isServerStartWithOSGiConsole(getServer());
    if (enableOSGIConsole != null && enableOSGIConsole) {
      vmArguments = vmArguments + " -DosgiConsole";
    }
    return vmArguments;
  }

  protected String[] getPingURLList() {
    try {
      setServerisStillStarting(true);
      String url = "http://" + getServer().getHost();
      List<String> urls = new ArrayList<String>();
      ServerPort[] ports = getServerPorts(getServer());
      ServerPort sp = null;
      int port = 0;
      int offSet = 0;

      for (int i = 0; i < ports.length; i++) {
        int j = CarbonServerConstants.PORT_CAPTIONS.indexOf(ports[i].getName());
        if (j != -1 && CarbonServerConstants.PORT_IDS.get(j).equals("carbon.http")) {
          sp = ports[i];
          port = sp.getPort();
        } else if (j != -1 && CarbonServerConstants.PORT_IDS.get(j).equals("carbon.offset")) {
          sp = ports[i];
          offSet = sp.getPort();
        }
      }

      String newUrl = url;
      if (port != 80) {
        newUrl = newUrl + ":" + (port + offSet); // $NON-NLS-1$
      }
      newUrl = newUrl + CarbonServer32Utils.getWebContextRoot(getServer()) + "/carbon";
      urls.add(newUrl);

      return urls.toArray(new String[] {});
    } catch (Exception e) {
      Trace.trace(Trace.SEVERE, "Can't ping for server startup.");
    }
    return null;
  }

  protected List getStartClasspath() {
    List startClasspath = super.getStartClasspath();
    GenericServerRuntime runtime = getRuntimeDelegate();

    IVMInstall vmInstall = runtime.getVMInstall();
    File jdkLib = new File(vmInstall.getInstallLocation(), "lib");

    if (jdkLib.exists() && jdkLib.isDirectory()) {
      for (String cpath : jdkLib.list()) {
        Path newCPath = new Path(new File(jdkLib, cpath).toString());
        String fileExtension = newCPath.getFileExtension();
        if (fileExtension != null && fileExtension.equalsIgnoreCase("jar"))
          startClasspath.add(JavaRuntime.newArchiveRuntimeClasspathEntry(newCPath));
      }
    }
    return startClasspath;
  }

  protected String getCarbonXmlFilePath() {
    IPath serverHome = CarbonServerManager.getServerHome(getServer());
    return CarbonServer32Utils.getServerXmlPathFromLocalWorkspaceRepo(serverHome.toOSString());
  }

  protected String getTransportXmlFilePath() {
    IPath serverHome = CarbonServerManager.getServerHome(getServer());
    String transportsXmlPath =
        CarbonServer32Utils.getTransportsXmlPathFromLocalWorkspaceRepo(serverHome.toOSString());
    return transportsXmlPath;
  }

  protected String getAxis2FilePath() {
    return CarbonServer32Utils.getAxis2FilePath(getServer());
  }

  protected Integer[] getAllPortsServerWillUse(IServer server) {
    List<Integer> ports = new ArrayList<Integer>();

    String axis2FilePath = getAxis2FilePath();
    String transportsXmlPath = getTransportXmlFilePath();
    String carbonXmlPath = getCarbonXmlFilePath();

    addServletTransportPorts(ports, carbonXmlPath);
    addAxis2XmlPorts(ports, axis2FilePath);

    return ports.toArray(new Integer[] {});
  }

  protected void addServletTransportPorts(List<Integer> ports, String carbonXmlPath) {
    int port = 0;
    XPathFactory factory = XPathFactory.newInstance();
    NamespaceContext cntx = CarbonServer32Utils.getCarbonNamespace();
    File xmlDocument = new File(carbonXmlPath);
    try {
      InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document document = builder.parse(xmlDocument);
      XPath xPath = factory.newXPath();
      xPath.setNamespaceContext(cntx);

      int offSet =
          Integer.parseInt(
              (String) xPath.evaluate("/Server/Ports/Offset", document, XPathConstants.STRING));
      String evaluate =
          (String)
              xPath.evaluate(
                  "/Server/Ports/ServletTransports/HTTPS", document, XPathConstants.STRING);

      if (!evaluate.equals("")) {
        port = Integer.parseInt(evaluate) + offSet;
      } else {
        port = getPortfromTransportXML("https");
      }
      ports.add(port);
      inputSource = new InputSource(new FileInputStream(xmlDocument));
      evaluate =
          (String)
              xPath.evaluate(
                  "/Server/Ports/ServletTransports/HTTP", document, XPathConstants.STRING);

      if (!evaluate.equals("")) {
        port = Integer.parseInt(evaluate) + offSet;
      } else {
        port = getPortfromTransportXML("http");
      }
      ports.add(port);

    } catch (NumberFormatException e) {
      log.error(e);
    } catch (FileNotFoundException e) {
      log.error(e);
    } catch (XPathExpressionException e) {
      log.error(e);
    } catch (ParserConfigurationException e) {
      log.error(e);
    } catch (SAXException e) {
      log.error(e);
    } catch (IOException e) {
      log.error(e);
    }
  }

  private int getPortfromTransportXML(String protocolType) {
    int port = 0;
    String transportsXmlPath = getTransportXmlFilePath();
    XPathFactory factory = XPathFactory.newInstance();
    File xmlDocument = new File(transportsXmlPath);
    try {
      InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
      XPath xPath = factory.newXPath();
      XPathExpression xPathExpression =
          xPath.compile(
              "/transports/transport[@name='" + protocolType + "']/parameter[@name='port']");
      String evaluate = xPathExpression.evaluate(inputSource);
      port = Integer.parseInt(evaluate);
    } catch (NumberFormatException e) {
      log.error(e);
    } catch (FileNotFoundException e) {
      log.error(e);
    } catch (XPathExpressionException e) {
      log.error(e);
    }
    return port;
  }
}
/**
 * This class provides a skeletal implementation of the IEsbNodeDeserializer interface,
 * deserializers are used to deserialize the objects from synapse to an EMF object that can be of
 * any type that the developer wants.
 *
 * <p>Instances of AbstractEsbNodeDeserializer are not safe for use by multiple threads and should
 * NOT be initialized by multiple editor instances
 *
 * @param <T> Input synapse object
 * @param <R> Return type of createNode()
 */
public abstract class AbstractEsbNodeDeserializer<T, R extends EsbNode>
    implements IEsbNodeDeserializer<T, R> {
  private static EsbDiagramEditor diagramEditor;
  private static Map<EsbConnector, LinkedList<EsbNode>> connectionFlowMap =
      new LinkedHashMap<EsbConnector, LinkedList<EsbNode>>();
  private static Map<EObject, ShapeNodeEditPart> editPartMap =
      new HashMap<EObject, ShapeNodeEditPart>();
  private static Map<EsbConnector, EsbConnector> pairMediatorFlowMap =
      new HashMap<EsbConnector, EsbConnector>();
  private static List<EObject> reversedNodes = new ArrayList<EObject>();
  private static Map<EsbConnector, LinkedList<EsbNode>> complexFiguredReversedFlows =
      new HashMap<EsbConnector, LinkedList<EsbNode>>();
  private static Map<EsbNode, Rectangle> nodeBounds = new HashMap<EsbNode, Rectangle>();
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
  private static GraphicalEditPart rootCompartment;
  private static List<EsbConnector> rootInputConnectors = new ArrayList<EsbConnector>();
  private static List<EditPart> startNodes = new ArrayList<EditPart>();
  private EObject elementToEdit;
  private boolean reversed;
  private static boolean hasInlineEndPoint;
  private static boolean addedAddressingEndPoint;

  public void setElementToEdit(EObject elementToEdit) {
    this.elementToEdit = elementToEdit;
  }

  private static Map<EsbConnector, Rectangle> currentLocation;

  public static EsbDiagramEditor getDiagramEditor() {
    /* Always refers EsbDiagramEditor from EsbDeserializerRegistry unless it is NULL
     * This ensures that the operations are executed by deserializer performs against the EsbDiagramEditor
     * initialized in EsbDeserializerRegistry
     * */
    EsbDiagramEditor diagramEditorRef = EsbDeserializerRegistry.getInstance().getDiagramEditor();
    if (diagramEditorRef != null) {
      diagramEditor = diagramEditorRef;
      return diagramEditorRef;
    }
    return diagramEditor;
  }

  public void setDiagramEditor(EsbDiagramEditor diagramEditor) {
    AbstractEsbNodeDeserializer.diagramEditor = diagramEditor;
  }

  /**
   * Deserialize a sequence
   *
   * @param mediatorFlow
   * @param sequence
   * @param connector
   * @throws DeserializerException
   */
  protected void deserializeSequence(
      IGraphicalEditPart part, SequenceMediator sequence, EsbConnector connector)
      throws DeserializerException {
    deserializeSequence(part, sequence, connector, isReversed());
  }

  /**
   * Deserialize a sequence
   *
   * @param mediatorFlow
   * @param sequence
   * @param connector
   * @param reversed
   * @throws DeserializerException
   */
  protected void deserializeSequence(
      IGraphicalEditPart part,
      SequenceMediator sequenceMediator,
      EsbConnector connector,
      boolean reversed)
      throws DeserializerException {
    LinkedList<EsbNode> nodeList = new LinkedList<>();
    LinkedList<CommentMediator> commentMediatorList = new LinkedList<>();
    SequenceMediator sequence = EditorUtils.stripUnsupportedMediators(sequenceMediator);

    TransactionalEditingDomain domain = part.getEditingDomain();

    if (connector instanceof OutputConnector) {
      int mediatorsCount = sequence.getList().size();
      boolean lastMediator = false;
      for (int i = 0; i < mediatorsCount; ++i) {
        AbstractMediator mediator = (AbstractMediator) sequence.getList().get(i);
        if (mediatorsCount == (i + 1)) {
          lastMediator = true;
        }
        if (reversedNodes.contains(connector.eContainer())) {
          executeMediatorDeserializer(
              part, nodeList, domain, mediator, true, commentMediatorList, lastMediator);
          reversedNodes.addAll(nodeList);
        } else {
          executeMediatorDeserializer(
              part, nodeList, domain, mediator, reversed, commentMediatorList, lastMediator);
          if (reversed) {
            reversedNodes.addAll(nodeList);
          }
        }
      }
      connectionFlowMap.put(connector, nodeList);
    } else if (connector instanceof InputConnector) {
      int mediatorsCount = sequence.getList().size();
      boolean lastMediator = false;
      for (int i = mediatorsCount - 1; i >= 0; --i) {
        if (i == 0) {
          lastMediator = true;
        }
        AbstractMediator mediator = (AbstractMediator) sequence.getList().get(i);
        executeMediatorDeserializer(
            part, nodeList, domain, mediator, true, commentMediatorList, lastMediator);
      }
      connectionFlowMap.put(connector, nodeList);
      reversedNodes.addAll(nodeList);
    }
  }

  /**
   * Execute deserializer
   *
   * @param mediatorFlow
   * @param nodeList
   * @param domain
   * @param mediator
   * @param reversed
   * @param commentMediatorList
   * @param lastMediator
   * @throws DeserializerException
   */
  private void executeMediatorDeserializer(
      IGraphicalEditPart part,
      LinkedList<EsbNode> nodeList,
      TransactionalEditingDomain domain,
      AbstractMediator mediator,
      boolean reversed,
      LinkedList<CommentMediator> commentMediatorList,
      boolean lastMediator)
      throws DeserializerException {
    @SuppressWarnings("rawtypes")
    IEsbNodeDeserializer deserializer =
        EsbDeserializerRegistry.getInstance().getDeserializer(mediator);
    if (deserializer != null) {
      deserializer.setReversed(reversed);
      @SuppressWarnings("unchecked")
      EsbNode node = deserializer.createNode(part, mediator);
      if (node != null) {
        // If there is any comment mediator(XML comment) in the source,
        // we will add
        // that into previous output connector's comment mediator list.
        // So that comment mediators have been encapsulated inside
        // output connectors which will prevent editor representing
        // comment mediators graphically.
        if (node instanceof CommentMediator) {
          AbstractOutputConnectorEditPart abstractOutputConnectorEditPart = null;
          if (reversed) {
            ProxyServiceEditPart proxyEditPart = EditorUtils.getProxy(part);
            commentMediatorList.add((CommentMediator) node);
            boolean faultSequence = isMediationFlowInFaultSequence(part);
            if (lastMediator && !faultSequence) {
              if (proxyEditPart != null) {
                abstractOutputConnectorEditPart =
                    EditorUtils.getProxyOutSequenceOutputConnector(proxyEditPart);
              }
              APIResourceEditPart apiEditPart = EditorUtils.getApiResourceFromEditPart(part);
              if (apiEditPart != null) {
                abstractOutputConnectorEditPart =
                    EditorUtils.getProxyOutSequenceOutputConnector(apiEditPart);
              }
              for (CommentMediator commentMediator : commentMediatorList) {
                if (abstractOutputConnectorEditPart != null) {
                  executeAddValueCommand(
                      ((OutputConnector)
                              ((Node) abstractOutputConnectorEditPart.getModel()).getElement())
                          .getCommentMediators(),
                      commentMediator,
                      reversed);
                }
              }
            }
          } else {
            abstractOutputConnectorEditPart = getPreviousOutputConnector(part, nodeList, reversed);
            if (abstractOutputConnectorEditPart != null) {
              executeAddValueCommand(
                  ((OutputConnector)
                          ((Node) abstractOutputConnectorEditPart.getModel()).getElement())
                      .getCommentMediators(),
                  (CommentMediator) node,
                  reversed);
            }
          }
        } else {
          nodeList.add(node);
          if (reversed) {
            for (CommentMediator commentMediator : commentMediatorList) {
              AbstractOutputConnectorEditPart abstractOutputConnectorEditPart =
                  getPreviousOutputConnector(part, nodeList, reversed);
              if (abstractOutputConnectorEditPart != null) {
                executeAddValueCommand(
                    ((OutputConnector)
                            ((Node) abstractOutputConnectorEditPart.getModel()).getElement())
                        .getCommentMediators(),
                    commentMediator,
                    reversed);
              }
            }
            commentMediatorList.clear();
          }
        }
        if (node instanceof SendMediator) {
          if (getRootCompartment() != null) {
            SendMediator sendMediator = (SendMediator) node;
            EndPoint endPoint = sendMediator.getNextNode();
            // Extract the endPoint info from the sendMediator
            if (endPoint != null) {
              if (reversed) {
                nodeList.add(nodeList.size(), endPoint);
              } else {
                nodeList.add(endPoint);
              }
            }
          }
        }
      }
    }
  }

  private boolean isMediationFlowInFaultSequence(IGraphicalEditPart part) {
    EditPart temp = part;
    while ((temp != null) && ((!(temp instanceof ProxyServiceFaultContainerEditPart)))) {
      temp = temp.getParent();
    }
    if (temp instanceof ProxyServiceFaultContainerEditPart) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * This method will return the OutputConnector of previous mediator in the mediator list. If the
   * mediator list is empty, this will return the output connector associated with that mediatorFlow
   *
   * @param part
   * @param nodeList
   * @return
   */
  private AbstractOutputConnectorEditPart getPreviousOutputConnector(
      IGraphicalEditPart part, LinkedList<EsbNode> nodeList, boolean reversed) {
    if (nodeList.isEmpty()) {
      ProxyServiceEditPart proxyEditPart = EditorUtils.getProxy(part);
      if (proxyEditPart != null) {
        return EditorUtils.getOutputConnector(proxyEditPart);
      }
      APIResourceEditPart apiResourceEditPart = EditorUtils.getApiResourceFromEditPart(part);
      if (apiResourceEditPart != null) {
        return EditorUtils.getProxyOutputConnector(apiResourceEditPart);
      }
      return null;
    } else {
      org.wso2.developerstudio.eclipse.gmf.esb.Mediator mediator =
          (org.wso2.developerstudio.eclipse.gmf.esb.Mediator) nodeList.getLast();
      refreshEditPartMap();
      return EditorUtils.getMediatorOutputConnector((ShapeNodeEditPart) getEditpart(mediator));
    }
  }

  protected void addPairMediatorFlow(EsbConnector startEnd, EsbConnector stopEnd) {
    pairMediatorFlowMap.put(startEnd, stopEnd);
  }

  private static void pairMediatorFlows() {
    for (Map.Entry<EsbConnector, EsbConnector> pair : pairMediatorFlowMap.entrySet()) {

      EditPart firstPart = (EditPart) getEditpart(pair.getKey());
      EditPart secondPart = (EditPart) getEditpart(pair.getValue());
      AbstractConnectorEditPart sourceConnector = null;
      AbstractConnectorEditPart targetConnector = null;

      if (firstPart instanceof SequencesOutputConnectorEditPart
          && secondPart instanceof SequencesInputConnectorEditPart) {

        AbstractSequencesEditPart sequence =
            EditorUtils.getSequence((SequencesOutputConnectorEditPart) firstPart);
        IGraphicalEditPart mediatorFlow =
            (IGraphicalEditPart)
                sequence.getChildren().get(0); // assuming mediatorflow is the first child
        IGraphicalEditPart mediatorFlowCompartment =
            (IGraphicalEditPart) mediatorFlow.getChildren().get(0);
        int numOfChildren = mediatorFlowCompartment.getChildren().size();
        if (numOfChildren >= 1) {
          // get last child and connect its output connector to secuenceinputconnector (right hand
          // side)
          // Assuming getChildren().get(numOfChildren - 1) gives the last element in the flow
          ShapeNodeEditPart lastChild =
              (ShapeNodeEditPart) mediatorFlowCompartment.getChildren().get(numOfChildren - 1);
          AbstractOutputConnectorEditPart lastOutputConnector =
              EditorUtils.getMediatorOutputConnector(lastChild);
          sourceConnector = lastOutputConnector;
          targetConnector = (AbstractConnectorEditPart) secondPart;
        }
      } else if ((firstPart instanceof InboundEndpointSequenceOutputConnectorEditPart
              && secondPart instanceof InboundEndpointSequenceInputConnectorEditPart)
          || (firstPart instanceof InboundEndpointOnErrorSequenceOutputConnectorEditPart
              && secondPart instanceof InboundEndpointOnErrorSequenceInputConnectorEditPart)) {
        LinkedList<EsbNode> seq = connectionFlowMap.get(pair.getKey());
        if (seq != null && seq.size() > 0 && seq.getLast() instanceof Sequence) {
          sourceConnector =
              (AbstractConnectorEditPart)
                  getEditpart(((Sequence) seq.getLast()).getOutputConnector().get(0));
          targetConnector = (AbstractConnectorEditPart) secondPart;
        }
      } else {
        if (firstPart instanceof ProxyOutputConnectorEditPart
            && secondPart instanceof ProxyInputConnectorEditPart) {
          LinkedList<EsbNode> seq = connectionFlowMap.get(pair.getKey());
          if (seq != null && seq.size() > 0 && seq.getLast() instanceof SendMediator) {
            sourceConnector =
                (AbstractConnectorEditPart)
                    getEditpart(((SendMediator) seq.getLast()).getOutputConnector());
            EList<ProxyInSequenceInputConnector> inputConnectors =
                ((ProxyService) ((Node) EditorUtils.getProxy(secondPart).getModel()).getElement())
                    .getInSequenceInputConnectors();
            for (ProxyInSequenceInputConnector con : inputConnectors) {
              if (con.getIncomingLinks().size() == 0) {
                targetConnector = (AbstractConnectorEditPart) getEditpart(con);
                break;
              }
            }
          }
          LinkedList<EsbNode> outSeq = connectionFlowMap.get(pair.getValue());
          if (outSeq == null || outSeq.size() == 0) {
            continue;
          }

          sourceConnector =
              EditorUtils.getProxyOutSequenceOutputConnector(
                  (ShapeNodeEditPart)
                      EditorUtils.getAbstractBaseFigureEditPart(
                          (EditPart) getEditpart(outSeq.getLast())));
          if (outSeq.size() > 0 && outSeq.getLast() != null) {
            targetConnector =
                EditorUtils.getInputConnector((ShapeNodeEditPart) getEditpart(outSeq.getLast()));
          } else {
            if (pair.getValue() instanceof AbstractConnectorEditPart) {
              targetConnector = (AbstractConnectorEditPart) pair.getValue();
            } else continue;
          }

        } else if (firstPart instanceof APIResourceOutputConnectorEditPart
            && secondPart instanceof APIResourceInputConnectorEditPart) {
          LinkedList<EsbNode> seq = connectionFlowMap.get(pair.getKey());
          if (seq != null && seq.size() > 0 && seq.getLast() instanceof SendMediator) {
            sourceConnector =
                (AbstractConnectorEditPart)
                    getEditpart(((SendMediator) seq.getLast()).getOutputConnector());
            EList<APIResourceInSequenceInputConnector> inputConnectors =
                ((APIResource)
                        ((Node)
                                EditorUtils.getAPIResource((AbstractConnectorEditPart) secondPart)
                                    .getModel())
                            .getElement())
                    .getInSequenceInputConnectors();
            for (APIResourceInSequenceInputConnector con : inputConnectors) {
              if (con.getIncomingLinks().size() == 0) {
                targetConnector = (AbstractConnectorEditPart) getEditpart(con);
                break;
              }
            }
          }
          LinkedList<EsbNode> outSeq = connectionFlowMap.get(pair.getValue());
          if (outSeq == null || outSeq.size() == 0) {
            continue;
          }

          sourceConnector =
              EditorUtils.getProxyOutSequenceOutputConnector(
                  (ShapeNodeEditPart)
                      EditorUtils.getAbstractBaseFigureEditPart(
                          (EditPart) getEditpart(outSeq.getLast())));
          if (outSeq.size() > 0 && outSeq.getLast() != null) {
            targetConnector =
                EditorUtils.getInputConnector((ShapeNodeEditPart) getEditpart(outSeq.getLast()));
          } else {
            if (pair.getValue() instanceof AbstractConnectorEditPart) {
              targetConnector = (AbstractConnectorEditPart) pair.getValue();
            } else continue;
          }
        } else {
          LinkedList<EsbNode> outSeq = connectionFlowMap.get(pair.getValue());
          if (outSeq == null || outSeq.size() == 0) {
            continue;
          }

          sourceConnector =
              EditorUtils.getProxyOutSequenceOutputConnector(
                  (ShapeNodeEditPart)
                      EditorUtils.getAbstractBaseFigureEditPart(
                          (EditPart) getEditpart(outSeq.getLast())));
          if (outSeq.size() > 0 && outSeq.getLast() != null) {
            targetConnector =
                EditorUtils.getInputConnector((ShapeNodeEditPart) getEditpart(outSeq.getLast()));
          } else {
            if (pair.getValue() instanceof AbstractConnectorEditPart) {
              targetConnector = (AbstractConnectorEditPart) pair.getValue();
            } else continue;
          }
        }
      }

      if (sourceConnector != null && targetConnector != null) {
        ConnectionUtils.createConnection(targetConnector, sourceConnector);
      }
    }

    /*		for (Map.Entry<EsbConnector, EsbConnector> pair : pairMediatorFlowMap.entrySet()) {
    	LinkedList<EsbNode> inSeq = connectionFlowMap.get(pair.getKey());
    	LinkedList<EsbNode> outSeq = connectionFlowMap.get(pair.getValue());

    	if (inSeq == null || outSeq == null) {
    		continue;
    	}

    	if (inSeq.size() > 0 && inSeq.getLast() instanceof EndPoint) {
    		EsbNode last = inSeq.getLast();
    		AbstractConnectorEditPart sourceConnector = EditorUtils
    				.getOutputConnector((ShapeNodeEditPart) getEditpart(last));
    		AbstractConnectorEditPart targetConnector = null;
    		if(outSeq.size() > 0 && outSeq.getLast() != null){
    			targetConnector = EditorUtils
    			.getInputConnector((ShapeNodeEditPart) getEditpart(outSeq.getLast()));
    		} else{
    			if(pair.getValue() instanceof AbstractConnectorEditPart){
    				targetConnector = (AbstractConnectorEditPart) pair.getValue();
    			} else continue;

    		}

    		if (sourceConnector != null && targetConnector != null) {
    			ConnectionUtils.createConnection(targetConnector,sourceConnector);
    		}
    	}
    }
    //looking for other possible connections  : around 1
    //Connecting endpoints to last node of out-sequence
    Iterator<EsbConnector> iterator = getRootInputConnectors().iterator();
    while (iterator.hasNext()) {
    	EsbConnector rootConnector = iterator.next();
    		for (LinkedList<EsbNode> nodes : connectionFlowMap.values()) {
    			if (!pairMediatorFlowMap.values().contains(nodes)) {
    				if (nodes.size() > 0 && (nodes.getLast() instanceof EndPoint ||
    						rootConnector.eContainer() instanceof Sequences)) {
    					LinkedList<EsbNode> outSeq = connectionFlowMap.get(rootConnector);
    					AbstractConnectorEditPart targetConnector = null;
    					EsbNode last = nodes.getLast();
    					AbstractConnectorEditPart sourceConnector = EditorUtils
    							.getOutputConnector((ShapeNodeEditPart) getEditpart(last));
    					if (outSeq!=null &&( outSeq.size() > 0 && outSeq.getLast() != null)) {
    						targetConnector = EditorUtils
    								.getInputConnector((ShapeNodeEditPart) getEditpart(outSeq
    										.getLast()));
    					} else {
    						targetConnector = (AbstractConnectorEditPart) getEditpart(rootConnector);
    					}

    					if (sourceConnector != null && targetConnector != null) {
    						if(targetConnector instanceof SequencesInputConnectorEditPart){
    							if(sourceConnector.getParent().getParent().getParent().getParent().equals(targetConnector.getParent())){
    								ConnectionUtils.createConnection(targetConnector, sourceConnector);
    							}
    						}else{
    							ConnectionUtils.createConnection(targetConnector, sourceConnector);
    						}
    					}
    				}
    			}
    		}
    }

    //looking for other possible connections : around 2
    //Connecting send mediators to an inline endpoint or a dummy endpoint
    EsbNode targetNode = null;
    List<EsbNode> sourceNodes = new LinkedList<EsbNode>();
    for (LinkedList<EsbNode> nodes : connectionFlowMap.values()) {
    	if (targetNode==null) {
    		if (nodes.size() > 0 && nodes.getLast() instanceof AbstractEndPoint) {
    			AbstractEndPoint endPoint = (AbstractEndPoint) nodes.getLast();
    			if (endPoint instanceof AddressingEndpoint || endPoint.isInLine()) {
    				targetNode = endPoint;
    			}
    		}
    	}

    	if (nodes.size() > 0 && nodes.getLast() instanceof SendMediator) {
    		sourceNodes.add(nodes.getLast());
    	}
    }

    if(targetNode!=null && sourceNodes.size()>0){
    	AbstractConnectorEditPart targetConnector = EditorUtils
    	.getInputConnector((ShapeNodeEditPart) getEditpart(targetNode));
    	for (EsbNode sourceNode : sourceNodes) {
    		AbstractConnectorEditPart sourceConnector = EditorUtils
    		.getOutputConnector((ShapeNodeEditPart) getEditpart(sourceNode));
    		if (sourceConnector != null && targetConnector != null) {
    			ConnectionUtils.createConnection(targetConnector, sourceConnector);
    		}
    	}
    }*/

  }

  /** Connect all mediator-flows according to sequence */
  public static synchronized void connectMediatorFlows() {
    refreshEditPartMap();
    for (EObject node : reversedNodes) {
      EditPart editpart = getEditpart(node);
      if (editpart
          instanceof org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediator) {
        ((org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediator) editpart)
            .reverseConnectors();
      }
    }
    currentLocation = new HashMap<EsbConnector, Rectangle>();
    for (Map.Entry<EsbConnector, LinkedList<EsbNode>> flow : connectionFlowMap.entrySet()) {
      relocateFlow(flow.getKey(), flow.getValue());
      EObject container = flow.getKey().eContainer();
      if (reversedNodes.contains(container)) {
        EditPart editpart = getEditpart(container);
        if (editpart instanceof complexFiguredAbstractMediator) {
          complexFiguredReversedFlows.put(flow.getKey(), flow.getValue());
        }
      }
    }
    clearLinks();
    for (Map.Entry<EsbConnector, LinkedList<EsbNode>> flow :
        complexFiguredReversedFlows.entrySet()) {
      reverseComplexFlow(flow.getKey(), flow.getValue());
    }
    refreshEditPartMap();
    for (Map.Entry<EsbConnector, LinkedList<EsbNode>> flow : connectionFlowMap.entrySet()) {
      connectMediatorFlow(flow.getKey(), flow.getValue());
    }
    pairMediatorFlows();
    cleanupData();
  }

  /**
   * Reverse nodes in inside complexFigured mediators of out-sequence
   *
   * @param connector
   * @param nodes
   */
  public static void reverseComplexFlow(EsbConnector connector, LinkedList<EsbNode> nodes) {

    Rectangle containerBounds = currentLocation.get(connector);

    if (containerBounds != null) {
      for (Iterator<EsbNode> i = nodes.iterator(); i.hasNext(); ) {
        EsbNode node = i.next();
        GraphicalEditPart editpart = (GraphicalEditPart) getEditpart(node);
        Rectangle rect = nodeBounds.get(node);
        if (rect != null) {
          rect.x = containerBounds.x - (rect.x + rect.width);
          SetBoundsCommand sbc =
              new SetBoundsCommand(
                  editpart.getEditingDomain(),
                  "change location",
                  new EObjectAdapter((View) editpart.getModel()),
                  rect);
          editpart.getDiagramEditDomain().getDiagramCommandStack().execute(new ICommandProxy(sbc));
        }
      }
    }
  }

  /** Cleanup everything used by deserializers */
  public static void cleanupData() {
    if (connectionFlowMap != null) {
      connectionFlowMap.clear();
    }

    if (reversedNodes != null) {
      reversedNodes.clear();
    }

    if (pairMediatorFlowMap != null) {
      pairMediatorFlowMap.clear();
    }

    if (rootInputConnectors != null) {
      rootInputConnectors.clear();
    }

    if (complexFiguredReversedFlows != null) {
      complexFiguredReversedFlows.clear();
    }

    if (nodeBounds != null) {
      nodeBounds.clear();
    }

    rootCompartment = null;
    hasInlineEndPoint = false;
    addedAddressingEndPoint = false;
  }

  /**
   * Connect mediator-flow to a connector
   *
   * @param connector
   * @param nodeList
   */
  private static void connectMediatorFlow(EsbConnector connector, LinkedList<EsbNode> nodeList) {
    AbstractConnectorEditPart sourceConnector = null;
    AbstractConnectorEditPart targetConnector = null;

    boolean reversedMode = (connector instanceof InputConnector);

    EditPart sourceConnectorEditpart = getEditpart(connector);
    if (sourceConnectorEditpart instanceof AbstractConnectorEditPart) {
      sourceConnector = (AbstractConnectorEditPart) getEditpart(connector);
    }

    Iterator<EsbNode> iterator = nodeList.iterator();

    while (iterator.hasNext()) {
      EsbNode mediatornode = iterator.next();
      AbstractConnectorEditPart nextSourceConnector = null;
      targetConnector = null;

      EditPart editpart = getEditpart(mediatornode);
      if (editpart instanceof ShapeNodeEditPart) {
        if (reversedMode) {
          targetConnector = getOutputConnector((ShapeNodeEditPart) editpart);
          nextSourceConnector = EditorUtils.getInputConnector((ShapeNodeEditPart) editpart);
        } else {
          targetConnector = EditorUtils.getInputConnector((ShapeNodeEditPart) editpart);
          nextSourceConnector = getOutputConnector((ShapeNodeEditPart) editpart);
        }
      }

      if (targetConnector != null && sourceConnector != null) {
        if (reversedMode) {
          ConnectionUtils.createConnection(sourceConnector, targetConnector);
        } else {
          ConnectionUtils.createConnection(targetConnector, sourceConnector);
        }
        sourceConnector = nextSourceConnector;
      }
      // sourceConnector = nextSourceConnector;
    }
  }

  /**
   * Look up OutputConnector by EditPart
   *
   * @param editpart
   * @return
   */
  private static AbstractConnectorEditPart getOutputConnector(ShapeNodeEditPart editpart) {
    return EditorUtils.getOutputConnector(editpart, AbstractMediatorOutputConnectorEditPart.class);
  }

  /**
   * @param reversedMode
   * @param editpart
   */
  private static void relocateNode(final Rectangle location, EditPart editpart) {

    GraphicalEditPart gEditpart = (GraphicalEditPart) editpart;

    if (editpart
        instanceof org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediator) {
      Rectangle rect =
          new Rectangle(new Point(), gEditpart.getFigure().getPreferredSize()).getCopy();
      Rectangle rectCopy = rect.getCopy();
      if (editpart instanceof complexFiguredAbstractMediator) {
        @SuppressWarnings("rawtypes")
        List children = gEditpart.getChildren();
        int pointY = 50;
        for (Object child : children) {
          if (child instanceof AbstractOutputConnectorEditPart) {
            EsbConnector connector =
                (EsbConnector) ((Node) ((EditPart) child).getModel()).getElement();
            Rectangle point = currentLocation.get(connector);
            if (point != null) {
              rectCopy.width = Math.max(rectCopy.width, point.x + 50);
              pointY += (point.y + point.height) + 20;
              rectCopy.height = Math.max(rectCopy.height, pointY);
            }
            if (((complexFiguredAbstractMediator) editpart).reversed) {
              rect.width += 50; // no effect on width
            }
          }
        }
      }
      rect.x = location.x;
      rect.y = location.y;
      SetBoundsCommand sbc =
          new SetBoundsCommand(
              gEditpart.getEditingDomain(),
              "change location",
              new EObjectAdapter((View) editpart.getModel()),
              rect);
      nodeBounds.put((EsbNode) ((View) editpart.getModel()).getElement(), rect.getCopy());

      gEditpart.getDiagramEditDomain().getDiagramCommandStack().execute(new ICommandProxy(sbc));
      location.x = location.x + rectCopy.width + 40;
      location.height = Math.max(location.height, rectCopy.height);
    }
  }

  private static Iterator<EsbNode> getNodeIterator(LinkedList<EsbNode> nodeList) {
    Iterator<EsbNode> iterator = nodeList.iterator();

    if (nodeList.size() > 0) {
      EditPart editpart = getEditpart(nodeList.getFirst());
      if (editpart != null) {
        if (editpart.getParent() instanceof AbstractMediatorCompartmentEditPart) {
          if (editpart.getParent().getParent() instanceof ShapeNodeEditPart) {
            EditPart container = editpart.getParent().getParent().getParent();
            if (container instanceof complexFiguredAbstractMediator) {
              if (((complexFiguredAbstractMediator) container).reversed) {
                iterator = nodeList.descendingIterator();
              }
            }
          }
        }
      }
    }

    return iterator;
  }

  private static void relocateFlow(EsbConnector connector, LinkedList<EsbNode> nodeList) {
    if (!currentLocation.containsKey(connector)) {
      currentLocation.put(connector, new Rectangle(25, getInitialY(connector, nodeList), 0, 0));
    }

    Rectangle point = currentLocation.get(connector);
    Iterator<EsbNode> iterator = getNodeIterator(nodeList);
    int count = 0;
    while (iterator.hasNext()) {
      EsbNode mediatornode = iterator.next();
      EditPart editpart = getEditpart(mediatornode);
      if (++count == 1) {
        startNodes.add(editpart);
      }
      relocateNode(point, editpart);
    }

    EsbConnector pairConnector = pairMediatorFlowMap.get(connector);
    if (pairConnector != null) {
      currentLocation.put(pairConnector, new Rectangle(25, Math.max(200, point.height + 30), 0, 0));
    }
  }

  /**
   * This is to avoid RJS0007E Semantic refresh failed issue appears in compartments, which has only
   * one node. This should be replaced with the better approach
   */
  public static void relocateStartNodes() {
    for (Iterator<EditPart> it = startNodes.iterator(); it.hasNext(); ) {

      try {
        EditPart next = it.next();

        GraphicalEditPart gEditpart = (GraphicalEditPart) next;
        Rectangle rect = gEditpart.getFigure().getBounds().getCopy();
        rect.x++;
        SetBoundsCommand sbc =
            new SetBoundsCommand(
                gEditpart.getEditingDomain(),
                "change location",
                new EObjectAdapter((View) next.getModel()),
                rect);

        gEditpart.getDiagramEditDomain().getDiagramCommandStack().execute(new ICommandProxy(sbc));

        Thread.sleep(50);
      } catch (Exception e) {
        break;
      }
    }
    startNodes = new ArrayList<EditPart>();
  }

  private static int getInitialY(EsbConnector connector, LinkedList<EsbNode> nodeList) {
    int y = 10;

    EObject eContainer = connector.eContainer();

    if (eContainer != null) {
      // FIXME : Remove hard-coded values
      if (eContainer instanceof ProxyService || eContainer instanceof APIResource) {
        y = 95; // Initial y of proxy, api resource output connector
      } else if (eContainer instanceof Sequences) {
        y = 146; // Initial y of sequence output connector
      } else {
        return y;
      }
      if (nodeList.size() > 0) {
        EditPart editpart = getEditpart(nodeList.getFirst());
        if (editpart != null) {
          if (!(editpart instanceof complexFiguredAbstractMediator)) {
            GraphicalEditPart gEditpart = (GraphicalEditPart) editpart;
            y = y - (gEditpart.getFigure().getPreferredSize().height / 2);
          }
        }
      }
    }

    return y;
  }

  /** Clear links */
  @SuppressWarnings({"rawtypes", "unchecked"})
  private static void clearLinks() {
    Collection values =
        getDiagramEditor().getDiagramGraphicalViewer().getEditPartRegistry().values();
    Iterator iterator = values.iterator();
    CompoundCommand ccModel = new CompoundCommand();
    org.eclipse.gef.commands.CompoundCommand ccView =
        new org.eclipse.gef.commands.CompoundCommand();

    while (iterator.hasNext()) {
      Object editPart = iterator.next();
      if (editPart instanceof EsbLinkEditPart) {
        EsbLinkEditPart linkEditPart = (EsbLinkEditPart) editPart;
        /*
         * We shouldn't remove EsbLinkEditParts if the target of the link is a AbstractEndpointInputConnectorEditPart.
         * Because these kind of links will not be get regenerated again according to the current implementation.
         */
        if (linkEditPart.getTarget() instanceof AbstractEndpointInputConnectorEditPart) {
          continue;
        }
        Collection linkCollection = new ArrayList();
        linkCollection.add(((ConnectorImpl) linkEditPart.getModel()).getElement());
        org.eclipse.emf.edit.command.DeleteCommand modelDeleteCommand =
            new org.eclipse.emf.edit.command.DeleteCommand(
                getDiagramEditor().getEditingDomain(), linkCollection);
        if (modelDeleteCommand.canExecute()) {
          ccModel.append(modelDeleteCommand);
        }
        DeleteCommand viewDeleteCommand = new DeleteCommand(linkEditPart.getNotationView());
        if (viewDeleteCommand.canExecute()) {
          ccView.add(new ICommandProxy(viewDeleteCommand));
        }
      }
    }

    if (ccModel.canExecute()) {
      getDiagramEditor().getEditingDomain().getCommandStack().execute(ccModel);
    }
    if (ccView.canExecute()) {
      getDiagramEditor().getDiagramEditDomain().getDiagramCommandStack().execute(ccView);
    }
  }

  /** Refresh EditPartMap */
  public static void refreshEditPartMap() {
    editPartMap.clear();

    if (getDiagramEditor() == null) return;

    @SuppressWarnings("rawtypes")
    Map editPartRegistry =
        getDiagramEditor().getDiagramEditPart().getViewer().getEditPartRegistry();
    for (Object object : editPartRegistry.keySet()) {
      if (object instanceof Node) {
        Node nodeImpl = (Node) object;
        Object ep = editPartRegistry.get(nodeImpl);
        if (ep instanceof ShapeNodeEditPart) {
          editPartMap.put(nodeImpl.getElement(), (ShapeNodeEditPart) ep);
        }
      }
    }
  }

  /**
   * Get corresponding EditPart of EObject
   *
   * @param node
   * @return
   */
  public static EditPart getEditpart(EObject node) {
    if (editPartMap.containsKey(node)) {
      return editPartMap.get(node);
    }
    return null;
  }

  public static IDeveloperStudioLog getLog() {
    return log;
  }

  public static void setRootCompartment(GraphicalEditPart compartment) {
    AbstractEsbNodeDeserializer.rootCompartment = compartment;
  }

  public static GraphicalEditPart getRootCompartment() {
    return rootCompartment;
  }

  public static void addRootInputConnector(EsbConnector rootInputConnector) {
    rootInputConnectors.add(rootInputConnector);
  }

  public static List<EsbConnector> getRootInputConnectors() {
    return rootInputConnectors;
  }

  /*
   * If you are going to use this method, you must set "elementToEdit" attribute first.
   */
  protected boolean executeSetValueCommand(EStructuralFeature feature, Object value) {
    return executeSetValueCommand(elementToEdit, feature, value);
  }

  protected boolean executeSetValueCommand(
      EObject elementToEdit, EStructuralFeature feature, Object value) {
    SetRequest reqSet =
        new SetRequest(getDiagramEditor().getEditingDomain(), elementToEdit, feature, value);
    SetValueCommand operation = new SetValueCommand(reqSet);
    if (operation.canExecute()) {
      getDiagramEditor()
          .getDiagramEditDomain()
          .getDiagramCommandStack()
          .execute(new ICommandProxy(operation));
      return true;
    }
    return false;
  }

  protected <E extends EObject> boolean executeAddValueCommand(
      final EList<E> list, final E value, boolean addToFront) {
    TransactionalEditingDomain editingDomain = getDiagramEditor().getEditingDomain();
    RecordingCommand command;
    if (!addToFront) {
      command =
          new RecordingCommand(editingDomain) {
            protected void doExecute() {
              list.add(value);
            }
          };
    } else {
      command =
          new RecordingCommand(editingDomain) {
            protected void doExecute() {
              list.add(0, value);
            }
          };
    }
    if (command.canExecute()) {
      editingDomain.getCommandStack().execute(command);
      return true;
    }
    return false;
  }

  protected <E extends Object> boolean executeAddAllCommand(
      final EList<E> list, final List<E> valueList) {
    TransactionalEditingDomain editingDomain = getDiagramEditor().getEditingDomain();
    RecordingCommand command =
        new RecordingCommand(editingDomain) {
          protected void doExecute() {
            list.addAll(valueList);
          }
        };
    if (command.canExecute()) {
      editingDomain.getCommandStack().execute(command);
      return true;
    }
    return false;
  }

  protected NamespacedProperty createNamespacedProperty(SynapseXPath xpath) {
    NamespacedProperty nsp = EsbFactory.eINSTANCE.createNamespacedProperty();
    nsp.setPropertyValue(xpath.toString());
    if (xpath.getNamespaces() != null) {
      @SuppressWarnings("unchecked")
      Map<String, String> map = xpath.getNamespaces();
      nsp.setNamespaces(map);
    }
    return nsp;
  }

  protected NamespacedProperty createNamespacedProperty(SynapsePath path) {
    NamespacedProperty nsp = EsbFactory.eINSTANCE.createNamespacedProperty();
    nsp.setPropertyValue(path.toString());
    if (path.getPathType() == SynapsePath.X_PATH) {
      // nsp.setPropertyValue(path.getExpression());
      if (path.getNamespaces() != null) {
        @SuppressWarnings("unchecked")
        Map<String, String> map = path.getNamespaces();
        nsp.setNamespaces(map);
      }
    } else if (path.getPathType() == SynapsePath.JSON_PATH) {
      // nsp.setPropertyValue(path.getExpression());
    }
    return nsp;
  }

  protected NamespacedProperty createNamespacedProperty(
      String xpath, Map<String, String> namespaces) {
    NamespacedProperty nsp = EsbFactory.eINSTANCE.createNamespacedProperty();
    nsp.setPropertyValue(xpath.toString());
    if (namespaces != null) {
      nsp.setNamespaces(namespaces);
    }
    return nsp;
  }

  public boolean isReversed() {
    return reversed;
  }

  public void setReversed(boolean reversed) {
    this.reversed = reversed;
  }

  protected static LinkedList<EsbNode> getConnectionFlow(EsbConnector connector) {
    LinkedList<EsbNode> nodes = new LinkedList<EsbNode>();
    if (connectionFlowMap.containsKey(connector)) {
      nodes = connectionFlowMap.get(connector);
    } else {
      connectionFlowMap.put(connector, nodes);
    }
    return nodes;
  }

  protected static void setHasInlineEndPoint(boolean hasInlineEndPoint) {
    AbstractEsbNodeDeserializer.hasInlineEndPoint = hasInlineEndPoint;
  }

  protected static boolean hasInlineEndPoint() {
    return hasInlineEndPoint;
  }

  protected static void setAddedAddressingEndPoint(boolean addedAddressingEndPoint) {
    AbstractEsbNodeDeserializer.addedAddressingEndPoint = addedAddressingEndPoint;
  }

  protected static boolean isAddedAddressingEndPoint() {
    return addedAddressingEndPoint;
  }

  protected void setCommonProperties(
      Mediator mediator, org.wso2.developerstudio.eclipse.gmf.esb.Mediator visualElement) {
    executeSetValueCommand(visualElement, ESB_ELEMENT__DESCRIPTION, mediator.getShortDescription());
    executeAddAllCommand(
        visualElement.getCommentsList(), ((AbstractMediator) mediator).getCommentsList());
  }

  public void createNode(FormEditor formEditor, T task) {
    // TODO Auto-generated method stub

  }

  public void deserializeEndpoint(FormEditor formEditor, AbstractEndpoint object) {
    // TODO Auto-generated method stub

  }
}
public class DeveloperStudioElementProviderDialog extends Dialog {
  private Class<?>[] type;
  private TreeViewer treeViewer;
  private String selectedPath = null;
  private String ipathOfselection = null;
  private Button chkOpenResource;
  private static IDeveloperStudioLog log =
      Logger.getLog("org.wso2.developerstudio.eclipse.esb.editor");
  private Map<String, List<String>> filters;
  private String title;
  private boolean showOpenResourceCheckBox = true;
  private boolean showCreateNewResourceLink = false;
  Link createNewLink;

  /**
   * Create the dialog.
   *
   * @param parentShell
   */
  public DeveloperStudioElementProviderDialog(
      Shell parentShell, Class<?>[] type, Map<String, List<String>> filters) {
    super(parentShell);
    setType(type);
    setFilters(filters);
  }

  @Override
  protected void configureShell(Shell newShell) {
    super.configureShell(newShell);
    if (title != null) {
      newShell.setText(title);
    }
  }

  /**
   * Create contents of the dialog.
   *
   * @param parent
   */
  protected Control createDialogArea(Composite parent) {
    final Composite container = (Composite) super.createDialogArea(parent);
    treeViewer = new TreeViewer(container, SWT.BORDER);
    Tree treeResrouceProviders = treeViewer.getTree();
    treeResrouceProviders.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            updateSelectedElement();
            updateOKButtonStatus();
          }
        });

    treeResrouceProviders.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    treeViewer.setContentProvider(
        new ITreeContentProvider() {
          public Object[] getChildren(Object o) {
            return createTreeItemList(o);
          }

          private Object[] createTreeItemList(Object o) {
            List<Object> list = new ArrayList<Object>();
            if (o instanceof IDeveloperStudioProviderData[]) {
              IDeveloperStudioProviderData[] oo = (IDeveloperStudioProviderData[]) o;
              for (IDeveloperStudioProviderData data : oo) {
                IDeveloperStudioProvider provider = data.getProvider();
                if (isChildElementsPresent(provider)) {
                  list.add(data);
                }
              }
            } else if (o instanceof IDeveloperStudioProvider
                || o instanceof IDeveloperStudioProviderData) {
              IDeveloperStudioProvider provider =
                  o instanceof IDeveloperStudioProvider
                      ? (IDeveloperStudioProvider) o
                      : ((IDeveloperStudioProviderData) o).getProvider();
              IDeveloperStudioElement[] resources = provider.getElements(getFilters());
              if (resources != null) {
                list.addAll(Arrays.asList(resources));
              }
              IDeveloperStudioProvider[] categories = provider.getCategories(getFilters());
              if (categories != null) {
                list.addAll(Arrays.asList(categories));
              }
            } else if (o instanceof IDeveloperStudioElement) {
              IDeveloperStudioElement element = (IDeveloperStudioElement) o;
              list.addAll(Arrays.asList(element.getChildren(getFilters())));
            }
            return list.toArray();
          }

          private boolean isChildElementsPresent(IDeveloperStudioProvider provider) {
            IDeveloperStudioElement[] resources = provider.getElements(getFilters());
            IDeveloperStudioProvider[] categories = provider.getCategories(getFilters());
            return (resources != null && resources.length > 0)
                || (categories != null && categories.length > 0);
          }

          public Object getParent(Object arg0) {
            return null;
          }

          public boolean hasChildren(Object o) {
            if (o instanceof IDeveloperStudioProviderData[]) {
              return ((IDeveloperStudioProviderData[]) o).length > 0;
            } else if (o instanceof IDeveloperStudioProviderData) {
              IDeveloperStudioProviderData provider = (IDeveloperStudioProviderData) o;
              return isChildElementsPresent(provider.getProvider());
            } else if (o instanceof IDeveloperStudioProvider) {
              IDeveloperStudioProvider provider = (IDeveloperStudioProvider) o;
              return isChildElementsPresent(provider);
            } else if (o instanceof IDeveloperStudioElement) {
              IDeveloperStudioElement element = (IDeveloperStudioElement) o;
              return element.hasChildren(getFilters());
            }
            return false;
          }

          public Object[] getElements(Object o) {
            return getChildren(o);
          }

          public void dispose() {
            // TODO Auto-generated method stub
          }

          public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
            // TODO Auto-generated method stub
          }
        });
    treeViewer.setLabelProvider(
        new ILabelProvider() {
          public Image getImage(Object o) {
            if (o instanceof IDeveloperStudioProviderData) {
              IDeveloperStudioProviderData oo = (IDeveloperStudioProviderData) o;
              if (oo.getProvider().getIcon() != null) {
                return oo.getProvider().getIcon().createImage();
              }
            } else if (o instanceof IDeveloperStudioProvider) {
              IDeveloperStudioProvider provider = (IDeveloperStudioProvider) o;
              if (provider.getIcon() != null) {
                return provider.getIcon().createImage();
              }
            } else if (o instanceof IDeveloperStudioElement) {
              IDeveloperStudioElement resource = (IDeveloperStudioElement) o;
              if (resource.getIcon() != null) {
                return resource.getIcon().createImage();
              }
            }
            return null;
          }

          public String getText(Object o) {
            if (o instanceof IDeveloperStudioProviderData) {
              IDeveloperStudioProviderData oo = (IDeveloperStudioProviderData) o;
              return oo.getName();
            } else if (o instanceof IDeveloperStudioProvider) {
              IDeveloperStudioProvider provider = (IDeveloperStudioProvider) o;
              return provider.getText();
            } else if (o instanceof IDeveloperStudioElement) {
              IDeveloperStudioElement resource = (IDeveloperStudioElement) o;
              return resource.getText();
            }
            return null;
          }

          public void addListener(ILabelProviderListener arg0) {}

          public void dispose() {}

          public boolean isLabelProperty(Object arg0, String arg1) {
            return false;
          }

          public void removeListener(ILabelProviderListener arg0) {}
        });
    List<Object> list = new ArrayList<Object>();

    List<Class<?>> typesList = Arrays.asList(type);

    // IRegistryFile.class, IEsbEndpoint.class, IEsbSequence.class, IEsbLocalEntry.class
    if (typesList.contains(IRegistryFile.class)) {
      list.addAll(Arrays.asList(RegistryManager.getResourceProviders(true)));
    }

    if (typesList.contains(IEsbEndpoint.class)) {
      list.addAll(Arrays.asList(EsbConfigurationManager.getEndpointProviders(true)));
    }

    if (typesList.contains(IEsbSequence.class)) {
      list.addAll(Arrays.asList(EsbConfigurationManager.getSequenceProviders(true)));
    }

    if (typesList.contains(IEsbLocalEntry.class)) {
      list.addAll(Arrays.asList(EsbConfigurationManager.getLocalEntryProviders(true)));
    }

    treeViewer.setInput(list.toArray(new IDeveloperStudioProviderData[] {}));

    if (showOpenResourceCheckBox) {
      chkOpenResource = new Button(container, SWT.CHECK);
      chkOpenResource.setText("Open the resource for editing");
    }

    if (showCreateNewResourceLink) {
      createNewLink = new Link(container, SWT.NONE);
      createNewLink.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              openNewResourceTemplateDialog();
            }
          });
      createNewLink.setText("<a>Create && point to a new DataMapper Configuration. </a>");
    }

    return container;
  }

  private void updateOKButtonStatus() {
    Object firstElement = getSelectedElement();
    boolean okButtonEnabled =
        firstElement == null ? false : isContainsClass(firstElement, getType());
    getButton(IDialogConstants.OK_ID).setEnabled(okButtonEnabled);
  }

  private boolean isContainsClass(Object objectToTest, Class<?>[] classes) {
    for (Class<?> class1 : classes) {
      try {
        class1.cast(objectToTest);
        return true;
      } catch (Exception e) {
        // not an instace of
      }
    }
    return false;
  }

  protected void okPressed() {
    Object selectedElement = getSelectedElement();
    IDeveloperStudioElement resource = (IDeveloperStudioElement) selectedElement;

    /*
    if (resource.getSource() instanceof IFile) {
    	IFile selectedIFile = (IFile) resource.getSource();
    	ipathOfselection = selectedIFile.getFullPath().toString();

    	IProject project = selectedIFile.getProject();
    	RegistryFileImpl rpi = (RegistryFileImpl)selectedElement;
    	String fileName = rpi.getName();
    	String fullPath = rpi.getPath();
    	int index = fullPath.lastIndexOf('/');
    	String path = "";
    	if (index > 0) {
    		path = fullPath.substring(0,index);
    	}

    	if (path != null && !path.isEmpty())
    		try {
    			CreateNewConfigurationDialog.createRegistryResourcesForInputScemaAndOutputSchema(fileName, project, path);
    		} catch (Exception e) {
    			log.error(e.getMessage());
    		}
    }
    */

    if (showOpenResourceCheckBox && chkOpenResource.getSelection()) {
      try {
        if (resource.getSource() instanceof IFile) {
          IDE.openEditor(
              PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
              (IFile) resource.getSource());
        } else if (resource.getSource() instanceof File && ((File) resource.getSource()).isFile()) {
          IFileStore fileStore =
              EFS.getLocalFileSystem().getStore(((File) resource.getSource()).toURI());
          IWorkbenchPage page =
              PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
          IDE.openEditorOnFileStore(page, fileStore);
        }
      } catch (PartInitException e) {
        log.error("Error opening the resource file", e);
      }
    }
    super.okPressed();
  }

  private Object getSelectedElement() {
    return ((ITreeSelection) treeViewer.getSelection()).getFirstElement();
  }

  /**
   * Create contents of the button bar.
   *
   * @param parent
   */
  protected void createButtonsForButtonBar(Composite parent) {
    createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
    createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
    updateOKButtonStatus();
  }

  /** Return the initial size of the dialog. */
  protected Point getInitialSize() {
    return new Point(464, 335);
  }

  public void setType(Class<?>[] type) {
    this.type = type;
  }

  public Class<?>[] getType() {
    return type;
  }

  public void setSelectedPath(String selectedPath) {
    this.selectedPath = selectedPath;
  }

  public String getSelectedPath() {
    return selectedPath;
  }

  public String getIPathOfSelection() {
    return ipathOfselection;
  }

  private void updateSelectedElement() {
    Object selectedElement = getSelectedElement();
    if (selectedElement instanceof IDeveloperStudioElement) {
      setSelectedPath(((IDeveloperStudioElement) selectedElement).getKey());
    } else {
      setSelectedPath(null);
    }
  }

  public void setFilters(Map<String, List<String>> filters) {
    this.filters = filters;
  }

  public Map<String, List<String>> getFilters() {
    return filters;
  }

  public void configureDialog(
      String title, boolean showOpenResourceCheckBox, boolean showCreateNewResourceLink) {
    this.title = title;
    this.showOpenResourceCheckBox = showOpenResourceCheckBox;
    this.showCreateNewResourceLink = showCreateNewResourceLink;
  }

  protected void openNewResourceTemplateDialog() {
    // FIXME handle this in a proper way
    try {
      NewResourceTemplateDialog newResourceTemplateDialog =
          new NewResourceTemplateDialog(getParentShell(), (Map<String, List<String>>) getFilters());
      // CreateNewConfigurationDialog newResourceTemplateDialog = new
      // CreateNewConfigurationDialog(getParentShell(),(Map<String, List<String>>) getFilters());
      newResourceTemplateDialog.create();
      newResourceTemplateDialog.getShell().setText("New DataMapper Configuration");
      newResourceTemplateDialog.open();
      if (newResourceTemplateDialog.getReturnCode() == Window.OK) {
        setSelectedPath(newResourceTemplateDialog.getSelectedPath());
        ipathOfselection = newResourceTemplateDialog.getIPathOfSelection();
        this.close();
      }
    } finally {

    }
  }
}
public class LibraryArtifactHandler extends ProjectArtifactHandler {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public List<IResource> exportArtifact(IProject project) throws Exception {
    List<IResource> exportResources = new ArrayList<IResource>();
    List<String> exportedPackageList = new ArrayList<String>();
    List<String> importededPackageList = new ArrayList<String>();

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();
    NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
    BundlesDataInfo bundleData = new BundlesDataInfo();
    IFile bundleDataFile = project.getFile("bundles-data.xml");
    File tempProject = createTempProject();
    File libResources = createTempDir(tempProject, "lib_resources");
    MavenProject mavenProject =
        MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile());

    if (bundleDataFile.exists()) {
      bundleData.deserialize(bundleDataFile);

      for (String lib : bundleData.getExportedPackageListsFromJar().keySet()) {
        IFile JarFile = project.getFile(lib);
        if (JarFile.exists()) {
          archiveManipulator.extract(JarFile.getLocation().toFile(), libResources);
          exportedPackageList.addAll(bundleData.getExportedPackageListsFromJar().get(lib));
        }
      }
      for (IProject lib : bundleData.getExportedPackageListsFromProject().keySet()) {
        if (lib.isOpen()) {
          lib.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
          IJavaProject javaLibProject = JavaCore.create(lib);
          for (IPackageFragment pkg : javaLibProject.getPackageFragments()) {
            if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
              if (pkg.hasChildren()) {
                exportedPackageList.add(pkg.getElementName());
              }
            }
          }

          IPath outPutPath = getOutputPath(javaLibProject);
          // get resource location
          IPath resources = getResourcePath(lib);

          FileUtils.copyDirectoryContents(outPutPath.toFile(), libResources);
          if (resources.toFile().exists()) {
            FileUtils.copyDirectoryContents(resources.toFile(), libResources);
          }
        }
      }
      getPackages(exportedPackageList, mavenProject, "Export-Package");
      getPackages(importededPackageList, mavenProject, "Import-Package");
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      if (null != mavenProject.getModel().getDescription()
          && !"".equals(mavenProject.getModel().getDescription())) {
        manifest.setBundleDescription(mavenProject.getModel().getDescription());
      } else {
        manifest.setBundleDescription(project.getName());
      }
      if (null != mavenProject.getModel().getVersion()
          && !"".equals(mavenProject.getDescription())) {
        manifest.setBundleVersion(mavenProject.getModel().getVersion());
      } else {
        manifest.setBundleVersion("1.0.0");
      }
      if (null != bundleData.getFragmentHost() && !"".equals(bundleData.getFragmentHost())) {
        manifest.setFragmentHost(bundleData.getFragmentHost());
      }
      manifest.setExportPackagesList(exportedPackageList);
      if (importededPackageList.size() > 0) {
        manifest.setImportPackagesList(importededPackageList);
        manifest.setDynamicImports(false);
      }
      File metaInfDir = new File(libResources, "META-INF");
      if (!metaInfDir.exists()) metaInfDir.mkdir();
      File manifestFile = new File(metaInfDir, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());

      File tmpArchive = new File(tempProject, project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), libResources.toString());

      IFile libArchive = getTargetArchive(project, "jar");
      FileUtils.copy(tmpArchive, libArchive.getLocation().toFile());
      exportResources.add((IResource) libArchive);

      // cleaning temp project
      // if(!org.apache.commons.io.FileUtils.deleteQuietly(tempProject.getLocation().toFile())){
      // tempProject.delete(true, getProgressMonitor());
    }

    TempFileUtils.cleanUp();
    return exportResources;
  }

  private List<String> getPackages(
      List<String> exportedPackagesList, MavenProject mavenProject, String packagetype)
      throws CoreException, JavaModelException, Exception {
    List<Plugin> plugins = mavenProject.getBuild().getPlugins();
    for (Plugin plugin : plugins) {
      if ("maven-bundle-plugin".equalsIgnoreCase(plugin.getArtifactId())) {
        Xpp3Dom configurationNode = (Xpp3Dom) plugin.getConfiguration();
        Xpp3Dom[] instructions = configurationNode.getChildren("instructions");
        if (instructions.length == 1) {
          Xpp3Dom[] exportPackage = instructions[0].getChildren(packagetype);
          if (exportPackage.length == 1) {
            exportedPackagesList.clear(); // clear default configuration (All packages by default)
            String exportpackages = exportPackage[0].getValue();
            if (exportpackages != null) {
              exportedPackagesList.addAll(Arrays.asList(exportpackages.split(",")));
            }
          } else {
            log.warn(
                "Invalid configuration for <Export-Package> entry"
                    + " using default configuration for <Export-Package>");
          }
        } else {
          log.warn(
              "Invalid instructions configuration for plugin : maven-bundle-plugin"
                  + " using default configuration for <Export-Package>");
        }
        break; // not considering multiple versions of the maven-bundle-plugin
      }
    }
    return exportedPackagesList;
  }
}
public class RefactorUtils {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public static Dependency getDependencyForTheProject(IFile file) {
    IProject project = file.getProject();
    MavenProject mavenProject = getMavenProject(project);

    String groupId = mavenProject.getGroupId();
    String artifactId = mavenProject.getArtifactId();
    String version = mavenProject.getVersion();

    String filePath = file.getLocation().toOSString();
    int startIndex =
        (project.getLocation().toOSString()
                + File.separator
                + "src"
                + File.separator
                + "main"
                + File.separator
                + "synapse-config"
                + File.separator)
            .length();
    int endIndex = filePath.lastIndexOf(File.separator);

    String typeString;
    if (startIndex < endIndex) {
      String typeStringFromPath = filePath.substring(startIndex, endIndex);
      if (typeStringFromPath.equalsIgnoreCase("sequences")) {
        typeString = "sequence";
      } else if (typeStringFromPath.equalsIgnoreCase("endpoints")) {
        typeString = "endpoint";
      } else if (typeStringFromPath.equalsIgnoreCase("proxy-services")) {
        typeString = "proxy-service";
      } else {
        typeString = "local-entry";
      }

    } else {
      typeString = "synapse";
    }

    Dependency dependency = new Dependency();
    dependency.setGroupId(groupId + "." + typeString);
    dependency.setArtifactId(artifactId);
    dependency.setVersion(version);

    return dependency;
  }

  public static MavenProject getMavenProject(IProject project) {
    try {
      return MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile());
    } catch (Exception e) {
      log.error("Failed to retrive the maven project for the given project", e);
    }
    return null;
  }

  public static boolean isDependenciesEqual(Dependency source, Dependency target) {
    return (source.getGroupId().equalsIgnoreCase(target.getGroupId())
        && source.getArtifactId().equalsIgnoreCase(target.getArtifactId())
        && source.getVersion().equalsIgnoreCase(target.getVersion()));
  }

  public static int charsOnTheLine(String line) {
    // Here we need to add one to represent the newline character
    return line.length() + 1;
  }

  public static ESBArtifact getESBArtifactFromFile(
      IFile refactoredFile, String projectNatureFilter) {
    IProject esbProject = refactoredFile.getProject();
    try {
      esbProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      if (esbProject.isOpen() && esbProject.hasNature(projectNatureFilter)) {

        ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
        esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml").getLocation().toFile());
        List<ESBArtifact> allESBArtifacts = esbProjectArtifact.getAllESBArtifacts();

        String originalFileRelativePath =
            FileUtils.getRelativePath(
                    esbProject.getLocation().toFile(), refactoredFile.getLocation().toFile())
                .replaceAll(Pattern.quote(File.separator), "/");

        for (ESBArtifact esbArtifact : allESBArtifacts) {
          if (esbArtifact.getFile().equals(originalFileRelativePath)) {
            return esbArtifact;
          }
        }
      }
    } catch (CoreException e) {
      log.error("Error while reading ESB Project", e);
    } catch (FactoryConfigurationError e) {
      log.error("Error while reading ESB Project", e);
    } catch (Exception e) {
      log.error("Error while reading ESB Project", e);
    }

    return null;
  }

  public static String getFilenameWOExtension(String filename) {
    String fileNameWOExt = null;
    if (FilenameUtils.indexOfExtension(filename) == -1) {
      fileNameWOExt = filename;
    } else {
      fileNameWOExt = FilenameUtils.removeExtension(filename);
    }
    return fileNameWOExt;
  }

  public static String getFilenameExtension(String filename) {
    String fileNameExt = "";
    if (FilenameUtils.indexOfExtension(filename) != -1) {
      fileNameExt = FilenameUtils.getExtension(filename);
    }
    return fileNameExt;
  }
}
public class ConfigurationPortEditorSection extends ServerEditorSection {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
  protected Table ports;
  protected TableViewer viewer;

  /** ConfigurationPortEditorSection constructor comment. */
  public ConfigurationPortEditorSection() {

    super();
  }

  protected void addChangeListener() {}

  /**
   * @param name java.lang.String
   * @param port int
   */
  protected void changePortNumber(String name, int port) {
    TableItem[] items = ports.getItems();
    int size = items.length;
    for (int i = 0; i < size; i++) {
      ServerPort sp = (ServerPort) items[i].getData();
      if (sp.getName().equals(name)) {
        items[i].setData(new ServerPort(sp.getId(), sp.getName(), port, sp.getProtocol()));
        items[i].setText(1, port + "");
        CarbonServer31Utils.setServerConfigMapValue(server.getOriginal(), sp.getId(), port + "");
        CarbonServer31Utils.updateTransportXML(server.getOriginal());
        CarbonServer31Utils.updateAxis2XML(server.getOriginal());
        return;
      }
    }
  }

  /**
   * Creates the SWT controls for this workbench part.
   *
   * @param parent the parent control
   */
  public void createSection(Composite parent) {
    super.createSection(parent);
    FormToolkit toolkit = getFormToolkit(parent.getDisplay());

    Section section =
        toolkit.createSection(
            parent,
            ExpandableComposite.TWISTIE
                | ExpandableComposite.EXPANDED
                | ExpandableComposite.TITLE_BAR
                | Section.DESCRIPTION
                | ExpandableComposite.FOCUS_TITLE);
    section.setText("Ports");
    section.setDescription("Modify the server ports.");
    section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));

    // ports
    Composite composite = toolkit.createComposite(section);
    GridLayout layout = new GridLayout();
    layout.marginHeight = 8;
    layout.marginWidth = 8;
    composite.setLayout(layout);
    composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.FILL_HORIZONTAL));
    toolkit.paintBordersFor(composite);
    section.setClient(composite);

    ports = toolkit.createTable(composite, SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
    ports.setHeaderVisible(true);
    ports.setLinesVisible(true);

    TableLayout tableLayout = new TableLayout();

    TableColumn col = new TableColumn(ports, SWT.NONE);
    col.setText("Port Name");
    ColumnWeightData colData = new ColumnWeightData(15, 150, true);
    tableLayout.addColumnData(colData);

    col = new TableColumn(ports, SWT.NONE);
    col.setText("Value");
    colData = new ColumnWeightData(8, 80, true);
    tableLayout.addColumnData(colData);

    GridData data = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
    data.widthHint = 230;
    data.heightHint = 100;
    ports.setLayoutData(data);
    ports.setLayout(tableLayout);

    viewer = new TableViewer(ports);
    viewer.setColumnProperties(new String[] {"name", "port"});

    initialize();
  }

  protected void setupPortEditors() {
    viewer.setCellEditors(new CellEditor[] {null, new TextCellEditor(ports)});

    ICellModifier cellModifier =
        new ICellModifier() {
          public Object getValue(Object element, String property) {
            ServerPort sp = (ServerPort) element;
            if (sp.getPort() < 0) return "-";
            return sp.getPort() + "";
          }

          public boolean canModify(Object element, String property) {
            if ("port".equals(property)) return true;

            return false;
          }

          public void modify(Object element, String property, Object value) {
            try {
              Item item = (Item) element;
              ServerPort sp = (ServerPort) item.getData();
              int port = Integer.parseInt((String) value);
              changePortNumber(sp.getName(), port);
            } catch (Exception ex) {
              log.error(ex);
            }
          }
        };
    viewer.setCellModifier(cellModifier);

    // preselect second column (Windows-only)
    String os = System.getProperty("os.name");
    if (os != null && os.toLowerCase().indexOf("win") >= 0) {
      ports.addSelectionListener(
          new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
              try {
                int n = ports.getSelectionIndex();
                viewer.editElement(ports.getItem(n).getData(), 1);
              } catch (Exception e) {
                // ignore
              }
            }
          });
    }
  }

  public void dispose() {}

  /*
   * (non-Javadoc)
   * Initializes the editor part with a site and input.
   */
  public void init(IEditorSite site, IEditorInput input) {
    super.init(site, input);

    GenericServer gserver = (GenericServer) server.getOriginal().getAdapter(GenericServer.class);
    try {
      gserver.getServerInstanceProperties();
      int a = 10;
    } catch (Exception e) {
      log.error(e);
    }
    addChangeListener();
    initialize();
  }

  /** Initialize the fields in this editor. */
  protected void initialize() {
    if (ports == null) return;

    ports.removeAll();
    CarbonServer31Utils.isServerStartBrowserPopup(server.getOriginal());
    ServerPort[] serverPorts =
        ServerController.getInstance().getServerManager().getServerPorts(server.getOriginal());
    for (ServerPort serverPort : serverPorts) {
      ServerPort port = serverPort;
      TableItem item = new TableItem(ports, SWT.NONE);
      String portStr = "-";
      if (port.getPort() >= 0) portStr = port.getPort() + "";
      String[] s = new String[] {port.getName(), portStr};
      item.setText(s);
      int i = CarbonServerConstants.PORT_CAPTIONS.indexOf(port.getName());
      if (i != -1) {
        port =
            new ServerPort(
                CarbonServerConstants.PORT_IDS.get(i),
                port.getName(),
                port.getPort(),
                port.getProtocol());
      }
      item.setData(port);
    }

    if (readOnly) {
      viewer.setCellEditors(new CellEditor[] {null, null});
      viewer.setCellModifier(null);
    } else {
      setupPortEditors();
    }
  }
}
public class ComplexFiguredAbstractEndpoint extends AbstractEndpoint {

  private static IDeveloperStudioLog log =
      Logger.getLog("org.wso2.developerstudio.eclipse.gmf.esb.diagram");

  public ComplexFiguredAbstractEndpoint(View view) {
    super(view);
  }

  protected NodeFigure createMainFigure() {
    return null;
  }

  public void openPage() {

    final EObject endpoint =
        (ParentEndPoint) ((org.eclipse.gmf.runtime.notation.impl.NodeImpl) getModel()).getElement();
    String name;

    long lDateTime = new Date().getTime();
    final String endpointName = String.valueOf(lDateTime);

    if ((((ParentEndPoint) endpoint).getName() == null)
        || ((ParentEndPoint) endpoint).getName().trim().equals("")) {

      Display.getDefault()
          .asyncExec(
              new Runnable() {
                public void run() {
                  SetRequest setRequest =
                      new SetRequest(
                          getEditingDomain(),
                          endpoint,
                          EsbPackage.eINSTANCE.getParentEndPoint_Name(),
                          endpointName);
                  SetValueCommand operation =
                      new SetValueCommand(setRequest) {

                        public boolean canUndo() {
                          return true;
                        }

                        public boolean canRedo() {
                          return true;
                        }
                      };

                  getEditDomain().getCommandStack().execute(new ICommandProxy(operation));
                }
              });

      name = endpointName;
      createFiles(
          endpoint,
          name,
          "complex_endpoint_" + name + ".esb_diagram",
          "complex_endpoint_" + name + ".esb");
    } else {
      name = ((ParentEndPoint) endpoint).getName();
      createFiles(
          endpoint,
          name,
          "complex_endpoint_" + name + ".esb_diagram",
          "complex_endpoint_" + name + ".esb");
    }
  }

  public boolean createFiles(EObject endpoint, String name, String fileURI1, String fileURI2) {
    /*		Resource diagram;
    String basePath = "platform:/resource/" + currentProject.getName()
    		+ "/" + COMPLEX_ENDPOINT_RESOURCE_DIR  + "/";*/
    IProject currentProject = getActiveProject();
    /*		IFile file = currentProject.getFile(COMPLEX_ENDPOINT_RESOURCE_DIR + "/"
    + fileURI1);*/

    IFile fileTobeOpened = null;
    // if (!file.exists()) {
    try {
      IFolder iFolder = currentProject.getFolder(SYNAPSE_CONFIG_DIR + "/complex-endpoints/");
      if (!iFolder.exists()) {
        iFolder.create(IResource.NONE, true, null);
      }
      fileTobeOpened =
          iFolder.getFile(
              name
                  + ".xml"); // currentProject.getFile(SYNAPSE_CONFIG_DIR + "/complex-endpoints/" +
                             // name + ".xml");

      if (fileTobeOpened.exists()) {
        OpenEditorUtils oeUtils = new OpenEditorUtils();
        oeUtils.openSeparateEditor(fileTobeOpened);
      } else {
        String path = fileTobeOpened.getParent().getFullPath() + "/";
        ArtifactTemplate complexEndpointArtifactTemplate = null;
        ArtifactTemplate[] endpointTemplates = getEndpointTemplates();
        if (endpoint instanceof FailoverEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[4];
        } else if (endpoint instanceof LoadBalanceEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[5];
        } else if (endpoint instanceof RecipientListEndPoint) {
          complexEndpointArtifactTemplate = endpointTemplates[6];
        }
        fileTobeOpened.create(
            complexEndpointArtifactTemplate.getTemplateDataStream(),
            true,
            new NullProgressMonitor());
        String source =
            org.wso2.developerstudio.eclipse.utils.file.FileUtils.getContentAsString(
                complexEndpointArtifactTemplate.getTemplateDataStream());
        source = source.replaceAll("\\{", "<").replaceAll("\\}", ">");
        source = StringUtils.replace(source, "<ep.name>", name);
        source = MessageFormat.format(source, name);
        Openable openable = ESBGraphicalEditor.getOpenable();
        openable.editorOpen(
            fileTobeOpened.getName(), ArtifactType.ENDPOINT.getLiteral(), path, source);
      }
    } catch (Exception e) {
      log.error("Cannot open file " + fileTobeOpened, e);
      return false;
    }
    String path = fileTobeOpened.getParent().getFullPath() + "/";

    /*			diagram = EsbDiagramEditorUtil.createResource(
    URI.createURI(basePath + fileURI1),
    URI.createURI(basePath + fileURI2),
    new NullProgressMonitor(), "complex_endpoint", name, null);*/
    /*			String source;
    try {
    	source = FileUtils.readFileToString(fileTobeOpened.getLocation().toFile());
    	Openable openable = ESBGraphicalEditor.getOpenable();
    	openable.editorOpen(fileTobeOpened.getName(), ArtifactType.COMPLEX_ENDPOINT.getLiteral(), path, source);
    } catch (IOException e1) {
    	log.error("Error while reading the file : "+fileTobeOpened, e1);
    	return false;
    } catch (Exception e) {
    	log.error("Error while opening the file : "+fileTobeOpened, e);
    	return false;
    }	*/
    /*			try {
    	EsbDiagramEditorUtil.openDiagram(diagram);

    } catch (PartInitException e) {
    	log.error("Cannot init editor", e);
    }*/
    return true;
    // }

    /*		else {
    	IWorkbenchPage page = PlatformUI.getWorkbench()
    			.getActiveWorkbenchWindow().getActivePage();
    	IEditorDescriptor desc = PlatformUI.getWorkbench()
    			.getEditorRegistry().getDefaultEditor(file.getName());
    	try {
    		page.openEditor(new FileEditorInput(file), desc.getId());
    	} catch (PartInitException e) {
    		log.error("Cannot init editor", e);
    	}
    	return true;
    }*/
  }

  private ArtifactTemplate[] getEndpointTemplates() {
    Map<String, List<String>> filters = new HashMap<String, List<String>>();
    DeveloperStudioProviderUtils.addFilter(
        filters, CSProviderConstants.FILTER_MEDIA_TYPE, ESBMediaTypeConstants.MEDIA_TYPE_ENDPOINT);
    return ArtifactTemplateHandler.getArtifactTemplates(filters);
  }

  private IProject getActiveProject() {
    IEditorPart editorPart = null;
    IProject activeProject = null;
    IEditorReference editorReferences[] =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
    for (int i = 0; i < editorReferences.length; i++) {
      IEditorPart editor = editorReferences[i].getEditor(false);

      if (editor != null) {
        editorPart = editor.getSite().getWorkbenchWindow().getActivePage().getActiveEditor();
      }

      if (editorPart != null) {
        EsbEditorInput input = (EsbEditorInput) editorPart.getEditorInput();
        IFile file = input.getXmlResource();
        activeProject = file.getProject();
      }
    }
    return activeProject;
  }
}
public class TemplateProjectCreationWizard extends AbstractWSO2ProjectCreationWizard {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private static final String PROJECT_WIZARD_WINDOW_TITLE = "New Template Artifact";
  private TemplateModel templateModel;
  private ESBProjectArtifact esbProjectArtifact;
  private List<File> fileLst = new ArrayList<File>();
  private IProject project;

  private String version = "1.0.0";

  public TemplateProjectCreationWizard() {
    this.templateModel = new TemplateModel();
    setModel(this.templateModel);
    setWindowTitle(PROJECT_WIZARD_WINDOW_TITLE);
    setDefaultPageImageDescriptor(
        TemplateImageUtils.getInstance().getImageDescriptor("template.png"));
  }

  protected boolean isRequireProjectLocationSection() {
    return false;
  }

  public boolean performFinish() {
    try {
      project = templateModel.getTemplateSaveLocation().getProject();
      createSequenceArtifact(templateModel);
      if (fileLst.size() > 0) {
        openEditor(fileLst.get(0));
      }
    } catch (Exception e) {
      log.error("An unexpected error has occurred", e);
    }
    return true;
  }

  private boolean createSequenceArtifact(TemplateModel sequenceModel) throws Exception {
    boolean isNewArtifact = true;
    IContainer location =
        project.getFolder(
            "src"
                + File.separator
                + "main"
                + File.separator
                + "synapse-config"
                + File.separator
                + "templates");
    esbProjectArtifact = new ESBProjectArtifact();
    esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile());
    File pomfile = project.getFile("pom.xml").getLocation().toFile();
    getModel().getMavenInfo().setPackageName("synapse/template");
    if (!pomfile.exists()) {
      createPOM(pomfile);
    }

    updatePom();
    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    String groupId = getMavenGroupId(pomfile);
    groupId += ".template";

    if (getModel().getSelectedOption().equals("import.template")) {
      IFile sequence = location.getFile(new Path(getModel().getImportFile().getName()));
      if (sequence.exists()) {
        if (!MessageDialog.openQuestion(
            getShell(), "WARNING", "Do you like to override exsiting project in the workspace")) {
          return false;
        }
        isNewArtifact = false;
      }
      copyImportFile(location, isNewArtifact, groupId);
    } else {
      String templateContent = "";
      String template = "";
      ArtifactTemplate selectedTemplate = templateModel.getSelectedTemplate();
      templateContent = FileUtils.getContentAsString(selectedTemplate.getTemplateDataStream());

      if (selectedTemplate.getName().equals("Address Endpoint Template")) {
        template = createEPTemplate(templateContent, "Address Endpoint Template");
      } else if (selectedTemplate.getName().equals("WSDL Endpoint Template")) {
        template = createEPTemplate(templateContent, "WSDL Endpoint Template");
      } else if (selectedTemplate.getName().equals("Default Endpoint Template")) {
        template = createEPTemplate(templateContent, "Default Endpoint Template");
      } else if (selectedTemplate.getName().equals("Sequence Template")) {
        template = createEPTemplate(templateContent, "Sequence Template");
      } else if (selectedTemplate.getName().equals("HTTP Endpoint Template")) {
        template = createEPTemplate(templateContent, "HTTP Endpoint Template");
      } else {
        template = createEPTemplate(templateContent, "");
      }

      File destFile =
          new File(location.getLocation().toFile(), sequenceModel.getTemplateName() + ".xml");
      FileUtils.createFile(destFile, template);
      fileLst.add(destFile);
      ESBArtifact artifact = new ESBArtifact();
      artifact.setName(sequenceModel.getTemplateName());
      artifact.setVersion(version);
      if ("Sequence Template".equals(selectedTemplate.getName())) {
        artifact.setType("synapse/sequenceTemplate");
      } else {
        artifact.setType("synapse/endpointTemplate");
      }
      artifact.setServerRole("EnterpriseServiceBus");
      artifact.setGroupId(groupId);
      artifact.setFile(
          FileUtils.getRelativePath(
                  project.getLocation().toFile(),
                  new File(
                      location.getLocation().toFile(), sequenceModel.getTemplateName() + ".xml"))
              .replaceAll(Pattern.quote(File.separator), "/"));
      esbProjectArtifact.addESBArtifact(artifact);
    }
    esbProjectArtifact.toFile();
    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    return true;
  }

  public String createEPTemplate(String templateContent, String type) throws IOException {
    String newContent = "";
    if (type.equals("Sequence Template")) {
      newContent = MessageFormat.format(templateContent, templateModel.getTemplateName());
    } else {
      templateContent = templateContent.replaceAll("\\{", "<");
      templateContent = templateContent.replaceAll("\\}", ">");
      newContent =
          StringUtils.replace(templateContent, "<ep.name>", templateModel.getTemplateName());
      if (type.equals("Address Endpoint Template")) {
        newContent =
            StringUtils.replace(newContent, "<address.uri>", templateModel.getAddressEPURI());
      } else if (type.equals("WSDL Endpoint Template")) {
        newContent = StringUtils.replace(newContent, "<wsdl.uri>", templateModel.getWsdlEPURI());
        newContent =
            StringUtils.replace(newContent, "<service.name>", templateModel.getWsdlEPService());
        newContent =
            StringUtils.replace(newContent, "<service.port>", templateModel.getWsdlEPPort());
      } else if (type.equals("HTTP Endpoint Template")) {
        newContent =
            StringUtils.replace(
                newContent, "<http.uritemplate>", templateModel.getHttpUriTemplate());
        if (!HttpMethodType.Leave_as_is.name().equals(templateModel.getHttpMethod().name())) {
          newContent =
              StringUtils.replace(
                  newContent, "<http.method>", templateModel.getHttpMethod().name().toLowerCase());
        } else {
          newContent = StringUtils.replace(newContent, "<http.method>", "");
        }
      }
    }
    return newContent;
  }

  public void updatePom() throws IOException, XmlPullParserException {
    File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile();
    MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);
    version = mavenProject.getVersion();

    // Skip changing the pom file if group ID and artifact ID are matched
    if (MavenUtils.checkOldPluginEntry(
        mavenProject, "org.wso2.maven", "wso2-esb-template-plugin")) {
      return;
    }

    Plugin plugin =
        MavenUtils.createPluginEntry(
            mavenProject,
            "org.wso2.maven",
            "wso2-esb-template-plugin",
            MavenConstants.WSO2_ESB_TEMPLATE_VERSION,
            true);
    PluginExecution pluginExecution = new PluginExecution();
    pluginExecution.addGoal("pom-gen");
    pluginExecution.setPhase("process-resources");
    pluginExecution.setId("template");

    Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode();
    Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation");
    artifactLocationNode.setValue(".");
    Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList");
    typeListNode.setValue("${artifact.types}");
    pluginExecution.setConfiguration(configurationNode);
    plugin.addExecution(pluginExecution);
    MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation);
  }

  public void copyImportFile(IContainer importLocation, boolean isNewAritfact, String groupId)
      throws IOException {
    File importFile = getModel().getImportFile();
    File destFile = null;
    List<OMElement> selectedSeqList = ((TemplateModel) getModel()).getSelectedTempSequenceList();
    if (selectedSeqList != null && selectedSeqList.size() > 0) {
      for (OMElement element : selectedSeqList) {
        String name = element.getAttributeValue(new QName("name"));
        destFile = new File(importLocation.getLocation().toFile(), name + ".xml");
        FileUtils.createFile(destFile, element.toString());
        fileLst.add(destFile);
        if (isNewAritfact) {
          ESBArtifact artifact = new ESBArtifact();
          artifact.setName(name);
          artifact.setVersion(version);
          artifact.setType("synapse/template");
          artifact.setServerRole("EnterpriseServiceBus");
          artifact.setGroupId(groupId);
          artifact.setFile(
              FileUtils.getRelativePath(
                      importLocation.getProject().getLocation().toFile(),
                      new File(importLocation.getLocation().toFile(), name + ".xml"))
                  .replaceAll(Pattern.quote(File.separator), "/"));
          esbProjectArtifact.addESBArtifact(artifact);
        }
      }
    } else {
      destFile = new File(importLocation.getLocation().toFile(), importFile.getName());
      FileUtils.copy(importFile, destFile);
      fileLst.add(destFile);
      String name = importFile.getName().replaceAll(".xml$", "");
      if (isNewAritfact) {
        ESBArtifact artifact = new ESBArtifact();
        artifact.setName(name);
        artifact.setVersion(version);
        artifact.setType("synapse/template");
        artifact.setServerRole("EnterpriseServiceBus");
        artifact.setGroupId(groupId);
        artifact.setFile(
            FileUtils.getRelativePath(
                    importLocation.getProject().getLocation().toFile(),
                    new File(importLocation.getLocation().toFile(), name + ".xml"))
                .replaceAll(Pattern.quote(File.separator), "/"));
        esbProjectArtifact.addESBArtifact(artifact);
      }
    }
  }

  protected boolean isRequiredWorkingSet() {
    return false;
  }

  public void openEditor(File file) {
    try {
      refreshDistProjects();
      OMElement documentElement = new StAXOMBuilder(new FileInputStream(file)).getDocumentElement();
      String templateType = "";

      if (documentElement.getChildrenWithName(new QName("endpoint")) != null
          && documentElement.getChildrenWithName(new QName("endpoint")).hasNext()) {
        // Endpoint template.
        templateType = ArtifactType.TEMPLATE_ENDPOINT.getLiteral();
        OMElement endpoint =
            (OMElement) documentElement.getChildrenWithName(new QName("endpoint")).next();
        String localName = endpoint.getFirstElement().getLocalName();
        if ("address".equals(localName)) {
          // Address endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_ADDRESS.getLiteral();
        } else if ("wsdl".equals(localName)) {
          // WSDL endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_WSDL.getLiteral();
        } else if ("http".equals(localName)) {
          // HTTP endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_HTTP.getLiteral();
        } else {
          // Default endpoint template.
          templateType = ArtifactType.TEMPLATE_ENDPOINT_DEFAULT.getLiteral();
        }
      } else {
        // Sequence template.
        templateType = ArtifactType.TEMPLATE_SEQUENCE.getLiteral();
      }

      IFile dbsFile =
          ResourcesPlugin.getWorkspace()
              .getRoot()
              .getFileForLocation(Path.fromOSString(file.getAbsolutePath()));
      String path = dbsFile.getParent().getFullPath() + "/";
      String source = FileUtils.getContentAsString(file);
      Openable openable = ESBGraphicalEditor.getOpenable();
      openable.editorOpen(file.getName(), templateType, path, source);
    } catch (Exception e) {
      log.error("Cannot open the editor", e);
    }
  }

  @Override
  public IResource getCreatedResource() {
    return null;
  }
}
public class RegistryInfoEditor extends FormEditor {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
  private StructuredTextEditor sourceEditor;
  private RegistryInfoEditorPage editorPage;
  private boolean dirty;
  private boolean sourceDirty;
  private int formEditorIndex;
  private int sourceEditorIndex;

  protected void addPages() {
    editorPage =
        new RegistryInfoEditorPage(
            this,
            "org.wso2.developerstudio.eclipse.artifact.registry.handler.editor.design",
            "Design");
    sourceEditor = new StructuredTextEditor();
    sourceEditor.setEditorPart(this);
    try {
      editorPage.initContent();
      formEditorIndex = addPage(editorPage);
      sourceEditorIndex = addPage(sourceEditor, getEditorInput());
      setPageText(sourceEditorIndex, "Source");

      getDocument()
          .addDocumentListener(
              new IDocumentListener() {

                public void documentAboutToBeChanged(final DocumentEvent event) {
                  // nothing to do
                }

                public void documentChanged(final DocumentEvent event) {
                  sourceDirty = true;
                  updateDirtyState();
                }
              });
    } catch (Exception e) {
      log.error(e);
    }
  }

  public void doSave(IProgressMonitor monitor) {
    if ((getCurrentPage() == formEditorIndex) && (dirty)) {
      updateSourceFromDesign();
    } else if ((getCurrentPage() == sourceEditorIndex) && (sourceDirty)) {
      updateDesignFromSource();
    }
    sourceDirty = false;
    dirty = false;
    try {
      editorPage.save();
      updateDirtyState();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void doSaveAs() {
    // nothing to do
  }

  public boolean isSaveAsAllowed() {
    return false;
  }

  public IDocument getDocument() {
    final IDocumentProvider provider = sourceEditor.getDocumentProvider();
    return provider.getDocument(getEditorInput());
  }

  private void updateSourceFromDesign() {
    try {
      String source = editorPage.getSource();
      getDocument().set(source);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void updateDesignFromSource() {
    try {
      editorPage.refreshContent();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void pageChange(int newPageIndex) {
    if ((newPageIndex == sourceEditorIndex) && (dirty)) {
      updateSourceFromDesign();
    } else if ((newPageIndex == formEditorIndex) && (sourceDirty)) {
      updateDesignFromSource();
    }

    super.pageChange(newPageIndex);

    final IFormPage page = getActivePageInstance();
    if (page != null) {
      page.setFocus();
    }
  }

  public void updateDirtyState() {
    dirty = editorPage.isDirty();
    firePropertyChange(PROP_DIRTY);
    editorDirtyStateChanged();
  }

  public boolean isDirty() {
    return (dirty || sourceDirty);
  }

  public StructuredTextEditor getSourceEditor() {
    return sourceEditor;
  }
}
public class CustomMediatorCreationWizard extends AbstractWSO2ProjectCreationWizard {

  private static final String PROJECT_WIZARD_WINDOW_TITLE = "New Mediator Artifact";
  private static final String MEDIATOR_PROJECT_NATURE =
      "org.wso2.developerstudio.eclipse.artifact.mediator.project.nature";
  private CustomMediatorModel customMediatorModel;
  private IProject project;
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public CustomMediatorCreationWizard() {
    setCustomMediatorModel(new CustomMediatorModel());
    setModel(customMediatorModel);
    setWindowTitle(PROJECT_WIZARD_WINDOW_TITLE);
    setDefaultPageImageDescriptor(
        MediatorImageUtils.getInstance().getImageDescriptor("new-mediator-wizard.png"));
  }

  public IWizardPage getNextPage(IWizardPage page) {
    IWizardPage nextPage = super.getNextPage(page);
    if (page instanceof ProjectOptionsDataPage) {
      if (getModel().getSelectedOption().equalsIgnoreCase("import.mediator")) {
        IProject temp = customMediatorModel.getMediatorProject();
        File pomfile = temp.getFile("pom.xml").getLocation().toFile();
        if (!pomfile.exists()) {
          try {
            getModel()
                .setMavenInfo(
                    new MavenInfo("org.wso2.carbon." + temp.getName(), temp.getName(), "1.0.0"));
            getModel().setProjectName(temp.getName());
          } catch (Exception e) {
            log.error("project update fail", e);
          }
        } else {
          nextPage = null;
        }
      }
    }
    return nextPage;
  }

  public boolean performFinish() {
    try {

      if (customMediatorModel.getSelectedOption().equals("new.mediator")) {
        project = createNewProject();
        IFolder srcFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java");
        JavaUtils.addJavaSupportAndSourceFolder(project, srcFolder);

        /*create the new Java project*/
        String className = customMediatorModel.getMediatorClassName();
        String packageName = customMediatorModel.getMediatorClassPackageName();
        IJavaProject iJavaProject = JavaCore.create(project);
        IPackageFragmentRoot root = iJavaProject.getPackageFragmentRoot(srcFolder);
        IPackageFragment sourcePackage = root.createPackageFragment(packageName, false, null);

        /*get the Mediator class template*/
        String template = CustomMediatorClassTemplate.getClassTemplete(packageName, className);
        ICompilationUnit cu =
            sourcePackage.createCompilationUnit(className + ".java", template, false, null);

        project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        try {
          IEditorPart javaEditor = JavaUI.openInEditor(cu);
          JavaUI.revealInEditor(javaEditor, (IJavaElement) cu);
        } catch (Exception e) {
          log.error(e);
        }
      } else {
        project = customMediatorModel.getMediatorProject();
        project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      }
      File pomfile = project.getFile("pom.xml").getLocation().toFile();
      getModel().getMavenInfo().setPackageName("bundle");
      if (!pomfile.exists()) {
        createPOM(pomfile);
        addDependancies(project);
      }
      MavenProject mavenProject = MavenUtils.getMavenProject(pomfile);
      boolean pluginExists =
          MavenUtils.checkOldPluginEntry(
              mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4");
      if (!pluginExists) {
        Plugin plugin =
            MavenUtils.createPluginEntry(
                mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4", true);

        Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(plugin);
        Xpp3Dom instructionNode = MavenUtils.createXpp3Node("instructions");
        Xpp3Dom bundleSymbolicNameNode =
            MavenUtils.createXpp3Node(instructionNode, "Bundle-SymbolicName");
        Xpp3Dom bundleNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Name");
        ;
        Xpp3Dom exportPackageNode = MavenUtils.createXpp3Node(instructionNode, "Export-Package");
        Xpp3Dom dynamicImportNode =
            MavenUtils.createXpp3Node(instructionNode, "DynamicImport-Package");
        bundleSymbolicNameNode.setValue(project.getName());
        bundleNameNode.setValue(project.getName());
        if (customMediatorModel.getMediatorClassPackageName() != null
            && !customMediatorModel.getMediatorClassPackageName().trim().isEmpty()) {
          exportPackageNode.setValue(customMediatorModel.getMediatorClassPackageName());
        } else {
          IJavaProject javaProject = JavaCore.create(project);
          if (null != javaProject) {
            StringBuffer sb = new StringBuffer();
            for (IPackageFragment pkg : javaProject.getPackageFragments()) {
              if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
                if (pkg.hasChildren()) {
                  sb.append(pkg.getElementName()).append(",");
                }
              }
            }
            exportPackageNode.setValue(sb.toString().replaceAll(",$", ""));
          }
        }
        dynamicImportNode.setValue("*");
        configurationNode.addChild(instructionNode);
        MavenUtils.saveMavenProject(mavenProject, pomfile);
      }

      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      ProjectUtils.addNatureToProject(project, false, MEDIATOR_PROJECT_NATURE);
      MavenUtils.updateWithMavenEclipsePlugin(
          pomfile,
          new String[] {JDT_BUILD_COMMAND},
          new String[] {MEDIATOR_PROJECT_NATURE, JDT_PROJECT_NATURE});
      customMediatorModel.addToWorkingSet(project);
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      refreshDistProjects();
    } catch (CoreException e) {
      log.error(e);
    } catch (Exception e) {
      log.error(e);
    }
    return true;
  }

  public void setCustomMediatorModel(CustomMediatorModel customMediatorModel) {
    this.customMediatorModel = customMediatorModel;
  }

  public CustomMediatorModel getCustomMediatorModel() {
    return customMediatorModel;
  }

  public IResource getCreatedResource() {
    return project;
  }

  // FIXME - need to get these lib from project scope now
  private void addDependancies(IProject project) throws JavaModelException {

    String[] depedencyList1 = getDepandanceyList();
    for (String libName : depedencyList1) {
      File dependencyPath = LibraryUtils.getDependencyPath(libName);
      if (dependencyPath != null) {
        JavaUtils.addJarLibraryToProject(project, dependencyPath);
      }
    }
  }

  private String[] getDepandanceyList() {
    String[] depedencyList =
        new String[] {
          LibraryUtils.abdera_wso2vXX_jar,
          LibraryUtils.axiom_1_2_11_wso2vXX_jar,
          LibraryUtils.axis2_1_6_1_wso2vXX_jar,
          LibraryUtils.commons_codec_wso2vXX_jar,
          LibraryUtils.commons_httpclient_wso2vXX_jar,
          LibraryUtils.commons_io_wso2vXX_jar,
          LibraryUtils.commons_loggingwso2vXX_jar,
          LibraryUtils.geronimo_stax_api_wso2vXX_jar,
          LibraryUtils.httpcore_4_3_0_wso2vXX_jar,
          LibraryUtils.neethi_wso2vXX_jar,
          LibraryUtils.not_yet_commons_ssl_wso2vXX_jar,
          LibraryUtils.synapse_core_2_1_2_wso2vXX_jar,
          LibraryUtils.wsdl4j_wso2vXX_jar,
          LibraryUtils.XmlSchema_wso2vXX_jar,
          LibraryUtils.woden_1_0_0_M8_wso2vXX_jar
        };

    return depedencyList;
  }
}
public class UpdateManager {

  private static final String FEATURE_GROUP_IU_ID_SFX = "feature.group"; // $NON-NLS-1$
  private static final String PROP_IS_HIDDEN = "isHidden"; // $NON-NLS-1$
  private static final String PROP_IS_KERNEL_FEATURE = "isKernelFeature"; // $NON-NLS-1$
  private static final String PROP_BUG_FIXES = "bugFixes"; // $NON-NLS-1$
  private static final String PROP_WHAT_IS_NEW = "whatIsNew"; // $NON-NLS-1$
  private static final String UPDATE_PROPERTIES_FILE = "update.properties"; // $NON-NLS-1$
  private static final String ICON_FILE = "icon.png"; // $NON-NLS-1$
  private static final String FILE_PROTOCOL = "file://"; // $NON-NLS-1$
  private static final String FEATURE_JAR_EXTRCT_FOLDER = "extracted"; // $NON-NLS-1$
  private static final String FEATURE_JAR_IU_ID_SFX = "feature.jar"; // $NON-NLS-1$
  private static final String WSO2_FEATURE_PREFIX = "org.wso2"; // $NON-NLS-1$
  private static final String DEVS_UPDATER_TMP = "DevSUpdaterTmp"; // $NON-NLS-1$
  private static final String JAVA_IO_TMPDIR = "java.io.tmpdir"; // $NON-NLS-1$
  private static final String NOT_RESOLVED_ERROR = Messages.UpdateManager_13;

  @Inject protected IProvisioningAgentProvider agentProvider;
  protected IProvisioningAgent p2Agent;
  protected ProvisioningSession session;

  // Provisioning Operations
  protected UpdateOperation updateOperation;
  protected InstallOperation installOperation;

  // Repository Managers
  protected IArtifactRepositoryManager artifactRepoManager;
  protected IMetadataRepositoryManager metadataRepoManager;

  // Installed Features
  protected Map<String, IInstallableUnit> installedWSO2FeaturesMap;

  // lists and maps related to Update Repository and updates
  protected Map<String, Update> availableUpdates;
  protected Update[] selectedUpdates;
  protected Map<String, EnhancedFeature> featuresWithPossibleUpdates;

  // lists and maps related to Release Repository and available Features
  protected Map<String, IInstallableUnit> allAvailableFeatures;
  protected Map<String, EnhancedFeature> availableNewFeatures;
  protected Collection<IInstallableUnit> selectedFeatures;

  protected static IDeveloperStudioLog log = Logger.getLog(UpdaterPlugin.PLUGIN_ID);

  public UpdateManager() throws RuntimeException {
    initProvisioningAgent();
  }

  protected void initProvisioningAgent() throws RuntimeException {
    try {
      // Inject references
      BundleContext bundleContext = FrameworkUtil.getBundle(UpdateManager.class).getBundleContext();
      IEclipseContext serviceContext = EclipseContextFactory.getServiceContext(bundleContext);
      ContextInjectionFactory.inject(this, serviceContext);
      // get p2 agent for current system(Eclipse instance in this
      // case)
      // the location for the currently running system is null (see
      // docs)
      p2Agent = agentProvider.createAgent(null);
      session = new ProvisioningSession(p2Agent);
      artifactRepoManager =
          (IArtifactRepositoryManager)
              p2Agent.getService(IArtifactRepositoryManager.class.getName());
      metadataRepoManager =
          (IMetadataRepositoryManager)
              p2Agent.getService(IMetadataRepositoryManager.class.getName());

    } catch (Exception e) {
      throw new RuntimeException(Messages.UpdateManager_14, e);
    }
  }

  /**
   * Finds available WSO2 features in current profile and search for updates to them in WSO2 p2
   * repository for updates.
   *
   * @param monitor
   * @throws Exception
   */
  public void checkForAvailableUpdates(IProgressMonitor monitor) throws Exception {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_18, 6);

    // get all available IUs in update repository
    IMetadataRepository metadataRepo =
        metadataRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));
    IQuery<IInstallableUnit> allIUQuery = QueryUtil.createIUAnyQuery();
    IQueryResult<IInstallableUnit> allIUQueryResult =
        metadataRepo.query(allIUQuery, progress.newChild(1));

    // read artifact repository for updates
    IArtifactRepository artifactRepo =
        artifactRepoManager.loadRepository(getDevStudioUpdateSite(), progress.newChild(1));

    // read meta-data of all available features
    Map<String, EnhancedFeature> allFeaturesInUpdateRepo =
        loadWSO2FeaturesInRepo(artifactRepo, allIUQueryResult, progress.newChild(1));

    // get all installed wso2 features
    Collection<IInstallableUnit> installedWSO2Features =
        getInstalledWSO2Features(progress.newChild(1));

    installedWSO2FeaturesMap = new HashMap<String, IInstallableUnit>();
    for (IInstallableUnit iInstallableUnit : installedWSO2Features) {
      installedWSO2FeaturesMap.put(iInstallableUnit.getId(), iInstallableUnit);
    }

    if (progress.isCanceled()) {
      throw new OperationCanceledException();
    }

    URI[] repos = new URI[] {getDevStudioUpdateSite()};
    updateOperation = new UpdateOperation(session, installedWSO2Features);
    updateOperation.getProvisioningContext().setArtifactRepositories(repos);
    updateOperation.getProvisioningContext().setMetadataRepositories(repos);

    // resolve update operation
    IStatus status = updateOperation.resolveModal(progress.newChild(1));
    // user cancelled the job while resolving
    if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
      throw new OperationCanceledException();
    }
    // there is nothing to update
    if (status.getCode() == UpdateOperation.STATUS_NOTHING_TO_UPDATE) {
      featuresWithPossibleUpdates = new HashMap<String, EnhancedFeature>();
      log.info(Messages.UpdateManager_19);
    } else if (status.getSeverity() == IStatus.ERROR) { // resolution errors
      // something wrong with the updates
      log.info(Messages.UpdateManager_20);
    } else {
      // good to proceed installing updates
      setPossibleUpdates(updateOperation.getPossibleUpdates(), allFeaturesInUpdateRepo);
    }
  }

  /**
   * Searches available features in WSO2 p2 repository for the current version of Developer Studio
   * and filters new features that can be installed.
   *
   * @param monitor
   * @throws Exception
   */
  public void checkForAvailableFeatures(IProgressMonitor monitor) throws Exception {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_21, 5);

    // get all available IUs in release repository
    IMetadataRepository metadataRepository =
        metadataRepoManager.loadRepository(getDevStudioReleaseSite(), progress.newChild(1));
    IQuery<IInstallableUnit> allIUQuery = QueryUtil.createIUAnyQuery();
    IQueryResult<IInstallableUnit> allIUQueryResult =
        metadataRepository.query(allIUQuery, progress.newChild(1));

    // load artifact repository for releases
    IArtifactRepository artifactRepository =
        artifactRepoManager.loadRepository(getDevStudioReleaseSite(), progress.newChild(1));

    // read meta-data of all available features
    Map<String, EnhancedFeature> allFeaturesInReleaseRepo =
        loadWSO2FeaturesInRepo(artifactRepository, allIUQueryResult, progress.newChild(1));

    Collection<IInstallableUnit> filteredIUs =
        filterInstallableUnits(
            WSO2_FEATURE_PREFIX, FEATURE_GROUP_IU_ID_SFX, allIUQueryResult, progress.newChild(1));
    allAvailableFeatures = new HashMap<String, IInstallableUnit>();
    availableNewFeatures = new HashMap<String, EnhancedFeature>();
    for (IInstallableUnit iInstallableUnit : filteredIUs) {
      allAvailableFeatures.put(iInstallableUnit.getId(), iInstallableUnit);
      if (!installedWSO2FeaturesMap.containsKey(iInstallableUnit.getId())) {
        availableNewFeatures.put(
            iInstallableUnit.getId(), allFeaturesInReleaseRepo.get(iInstallableUnit.getId()));
      } else {
        Version versionInstalled =
            installedWSO2FeaturesMap.get(iInstallableUnit.getId()).getVersion();
        // if the version we have is greater than the installed version view it in the available
        // feature list
        if (versionInstalled != null
            && (iInstallableUnit.getVersion().compareTo(versionInstalled) == 1)) {
          availableNewFeatures.put(
              iInstallableUnit.getId(), allFeaturesInReleaseRepo.get(iInstallableUnit.getId()));
        }
      }
    }
  }

  /**
   * Set selected updates to install.
   *
   * @param selectedFeaturesList selected updates to install.
   */
  public void setSelectedUpdates(List<EnhancedFeature> selectedFeaturesList) {
    selectedUpdates = new Update[selectedFeaturesList.size()];
    int count = 0;
    for (EnhancedFeature selectedFeature : selectedFeaturesList) {
      selectedUpdates[count] = availableUpdates.get(selectedFeature.getId());
      count++;
    }
  }

  /**
   * Install selected updates in to developer studio. Note: call {@link #setSelectedUpdates(List)
   * setSelectedUpdates} first.
   *
   * @param monitor
   */
  public void installSelectedUpdates(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_26, 2);
    URI[] repos = new URI[] {getDevStudioUpdateSite()};
    session = new ProvisioningSession(p2Agent);
    updateOperation = new UpdateOperation(session);
    updateOperation.getProvisioningContext().setArtifactRepositories(repos);
    updateOperation.getProvisioningContext().setMetadataRepositories(repos);

    updateOperation.setSelectedUpdates(selectedUpdates);
    IStatus status = updateOperation.resolveModal(progress.newChild(1));
    if (status.getSeverity() == IStatus.CANCEL) {
      throw new OperationCanceledException();
    } else if (status.getSeverity() == IStatus.ERROR) {
      String message = status.getChildren()[0].getMessage();
      log.error(Messages.UpdateManager_27 + message);
    } else {
      final ProvisioningJob provisioningJob =
          updateOperation.getProvisioningJob(progress.newChild(1));
      if (provisioningJob != null) {
        provisioningJob.addJobChangeListener(
            new JobChangeAdapter() {
              @Override
              public void done(IJobChangeEvent arg0) {
                Display.getDefault()
                    .syncExec(
                        new Runnable() {
                          @Override
                          public void run() {
                            boolean restart =
                                MessageDialog.openQuestion(
                                    Display.getDefault().getActiveShell(),
                                    Messages.UpdateManager_28,
                                    Messages.UpdateManager_29 + Messages.UpdateManager_30);
                            if (restart) {
                              PlatformUI.getWorkbench().restart();
                            }
                          }
                        });
              }
            });
        provisioningJob.schedule();
        Display.getDefault()
            .syncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    try {
                      PlatformUI.getWorkbench()
                          .getActiveWorkbenchWindow()
                          .getActivePage()
                          .showView(IProgressConstants.PROGRESS_VIEW_ID);
                    } catch (PartInitException e) {
                      log.error(e);
                    }
                  }
                });
      } else {
        log.error(Messages.UpdateManager_31);
      }
    }
  }

  /**
   * Set the selected new features to install.
   *
   * @param selectedDevSFeatures Features to install.
   */
  public void setSelectedFeaturesToInstall(List<EnhancedFeature> selectedDevSFeatures) {
    this.selectedFeatures = new ArrayList<IInstallableUnit>();
    for (EnhancedFeature devStudioFeature : selectedDevSFeatures) {
      selectedFeatures.add(allAvailableFeatures.get(devStudioFeature.getId()));
    }
  }

  /**
   * Install selected features in to developer studio. Note: call {@link
   * #setSelectedFeaturesToInstall(List) setSelectedFeaturesToInstall} first.
   *
   * @param monitor
   */
  public void installSelectedFeatures(IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_32, 2);

    URI[] repos = new URI[] {getDevStudioReleaseSite()};
    session = new ProvisioningSession(p2Agent);
    installOperation = new InstallOperation(session, selectedFeatures);
    installOperation.getProvisioningContext().setArtifactRepositories(repos);
    installOperation.getProvisioningContext().setMetadataRepositories(repos);
    IStatus status = installOperation.resolveModal(progress.newChild(1));
    if (status.getSeverity() == IStatus.CANCEL || progress.isCanceled()) {
      throw new OperationCanceledException();
    } else if (status.getSeverity() == IStatus.ERROR) {
      String message = status.getChildren()[0].getMessage();
      log.error(Messages.UpdateManager_33 + message);
    } else {
      ProvisioningJob provisioningJob = installOperation.getProvisioningJob(progress.newChild(1));
      if (provisioningJob != null) {
        provisioningJob.addJobChangeListener(
            new JobChangeAdapter() {
              @Override
              public void done(IJobChangeEvent arg0) {
                Display.getDefault()
                    .syncExec(
                        new Runnable() {
                          @Override
                          public void run() {
                            boolean restart =
                                MessageDialog.openQuestion(
                                    Display.getDefault().getActiveShell(),
                                    Messages.UpdateManager_34,
                                    Messages.UpdateManager_35 + Messages.UpdateManager_36);
                            if (restart) {
                              PlatformUI.getWorkbench().restart();
                            }
                          }
                        });
              }
            });
        provisioningJob.schedule();
        Display.getDefault()
            .syncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    try {
                      PlatformUI.getWorkbench()
                          .getActiveWorkbenchWindow()
                          .getActivePage()
                          .showView(IProgressConstants.PROGRESS_VIEW_ID);
                    } catch (PartInitException e) {
                      log.error(e);
                    }
                  }
                });
      } else {
        log.error(Messages.UpdateManager_37);
      }
    }
  }

  public Map<String, EnhancedFeature> getPossibleUpdatesMap() throws IllegalStateException {
    if (featuresWithPossibleUpdates == null) {
      throw new IllegalStateException(NOT_RESOLVED_ERROR);
    }
    return featuresWithPossibleUpdates;
  }

  public boolean hasPossibleUpdates() throws IllegalStateException {
    if (featuresWithPossibleUpdates == null) {
      throw new IllegalStateException(NOT_RESOLVED_ERROR);
    }
    return (featuresWithPossibleUpdates.size() > 0) ? true : false;
  }

  public Map<String, EnhancedFeature> getAvailableFeaturesMap() throws IllegalStateException {
    if (availableNewFeatures == null) {
      throw new IllegalStateException(NOT_RESOLVED_ERROR);
    }
    return availableNewFeatures;
  }

  private Map<String, EnhancedFeature> loadWSO2FeaturesInRepo(
      IArtifactRepository artifactRepository,
      IQueryResult<IInstallableUnit> allAvailableIUs,
      IProgressMonitor monitor)
      throws ProvisionException, URISyntaxException, IOException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_15, 10);

    String tmpRoot = System.getProperty(JAVA_IO_TMPDIR) + File.separator + DEVS_UPDATER_TMP;

    Collection<IInstallableUnit> wso2FeatureJars =
        filterInstallableUnits(
            WSO2_FEATURE_PREFIX, FEATURE_JAR_IU_ID_SFX, allAvailableIUs, progress.newChild(1));

    Map<String, EnhancedFeature> loadedFeatureMap = new HashMap<>();

    for (IInstallableUnit iu : wso2FeatureJars) {
      SubMonitor downloadProgress =
          SubMonitor.convert(progress, Messages.UpdateManager_16, wso2FeatureJars.size() * 2);
      Collection<IArtifactKey> artifacts = iu.getArtifacts();
      // ideally there should be only one artifact in a feature.jar iu
      for (IArtifactKey iArtifactKey : artifacts) {
        IArtifactDescriptor[] artifactDescriptors =
            artifactRepository.getArtifactDescriptors(iArtifactKey);
        File featureCacheRoot =
            new File(tmpRoot, iu.getId() + File.separator + iu.getVersion().toString());
        File cachedFeatureDir = new File(featureCacheRoot, FEATURE_JAR_EXTRCT_FOLDER);

        if (cachedFeatureDir.exists() && cachedFeatureDir.isDirectory()) {
          downloadProgress.worked(2);
        } else {
          featureCacheRoot.mkdirs();
          File jarFile = new File(featureCacheRoot, iu.getId());
          try {
            if (jarFile.exists()) {
              // something is wrong with the file
              // if it is there without the cache dir.
              jarFile.delete();
            }
            FileOutputStream fop = new FileOutputStream(jarFile);
            // jar iu only contains a single artifact. hence [0]
            artifactRepository.getArtifact(
                artifactDescriptors[0], fop, downloadProgress.newChild(1));
            cachedFeatureDir.mkdirs();
            extractJar(jarFile, cachedFeatureDir);
            downloadProgress.worked(1);
          } catch (IOException e) {
            throw new IOException(Messages.UpdateManager_17, e);
          }
        }
        EnhancedFeature feature = readEnhancedMetadata(iu, cachedFeatureDir);
        loadedFeatureMap.put(feature.getId(), feature);
      }
    }
    return loadedFeatureMap;
  }

  private EnhancedFeature readEnhancedMetadata(IInstallableUnit iu, File cachedFeatureDir) {
    EnhancedFeature feature = new EnhancedFeature(iu);
    feature.setIconURL(FILE_PROTOCOL + cachedFeatureDir + File.separator + ICON_FILE);
    try {
      File updateProperties = new File(cachedFeatureDir, UPDATE_PROPERTIES_FILE);
      Properties prop = new Properties();
      InputStream input = new FileInputStream(updateProperties);
      prop.load(input);
      feature.setWhatIsNew(prop.getProperty(PROP_WHAT_IS_NEW));
      feature.setBugFixes(prop.getProperty(PROP_BUG_FIXES));
      feature.setKernelFeature(Boolean.parseBoolean(prop.getProperty(PROP_IS_KERNEL_FEATURE)));
      feature.setHidden(Boolean.parseBoolean(prop.getProperty(PROP_IS_HIDDEN)));
    } catch (Exception e) {
      // ignore - Additional meta-data was not provided in feature.jar
      // log.error(e);
    }
    return feature;
  }

  private Collection<IInstallableUnit> filterInstallableUnits(
      String idPrefix,
      String idSuffix,
      IQueryResult<IInstallableUnit> queryResult,
      IProgressMonitor monitor)
      throws OperationCanceledException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    Collection<IInstallableUnit> wso2IUs = new ArrayList<IInstallableUnit>();
    Iterator<IInstallableUnit> iterator = queryResult.iterator();
    SubMonitor progress =
        SubMonitor.convert(monitor, Messages.UpdateManager_24, queryResult.toSet().size());
    ;
    while (iterator.hasNext()) {
      if (progress.isCanceled()) {
        throw new OperationCanceledException();
      }
      IInstallableUnit iu = iterator.next();
      String versionedID = iu.getId();
      progress.subTask(Messages.UpdateManager_25 + versionedID);
      if (versionedID != null
          && versionedID.startsWith(idPrefix)
          && versionedID.endsWith(idSuffix)) {
        wso2IUs.add(iu);
      }
      progress.worked(1);
    }
    return wso2IUs;
  }

  /**
   * Extracts a jar file to a given directory.
   *
   * @param jar Source jar file.
   * @param extractpath Destination to extract.
   * @throws IOException
   */
  private void extractJar(File jar, File extractpath) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {
      Enumeration<? extends ZipEntry> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(extractpath, entry.getName());
        if (entry.isDirectory()) entryDestination.mkdirs();
        else {
          entryDestination.getParentFile().mkdirs();
          InputStream in = zipFile.getInputStream(entry);
          OutputStream out = new FileOutputStream(entryDestination);
          IOUtils.copy(in, out);
          IOUtils.closeQuietly(in);
          out.close();
        }
      }
    } finally {
      zipFile.close();
    }
  }

  private Collection<IInstallableUnit> getInstalledWSO2Features(IProgressMonitor monitor)
      throws OperationCanceledException {
    SubMonitor progress = SubMonitor.convert(monitor, Messages.UpdateManager_23, 2);

    OperationFactory operationFactory = new OperationFactory();
    IQueryResult<IInstallableUnit> queryResult =
        operationFactory.listInstalledElements(true, progress.newChild(1));
    return filterInstallableUnits(
        WSO2_FEATURE_PREFIX, FEATURE_GROUP_IU_ID_SFX, queryResult, progress.newChild(1));
  }

  private void setPossibleUpdates(
      Update[] possibleUpdates, Map<String, EnhancedFeature> allFeaturesInUpdateRepo) {
    availableUpdates = new HashMap<String, Update>();
    featuresWithPossibleUpdates = new HashMap<String, EnhancedFeature>();
    for (Update update : possibleUpdates) {
      String id = update.replacement.getId();
      String oldVersion = update.toUpdate.getVersion().toString();
      String newVersion = update.replacement.getVersion().toString();
      EnhancedFeature updatebleFeature = allFeaturesInUpdateRepo.get(id);
      updatebleFeature.setCurrentVersion(oldVersion);
      updatebleFeature.setVersion(newVersion);
      availableUpdates.put(id, update);
      featuresWithPossibleUpdates.put(id, updatebleFeature);
    }
  }

  private URI getDevStudioUpdateSite() {
    URI updateSite = null;
    try {
      IPreferenceStore preferenceStore =
          org.wso2.developerstudio.eclipse.platform.ui.Activator.getDefault().getPreferenceStore();
      String url = preferenceStore.getString(UpdateCheckerPreferencePage.UPDATE_SITE_URL);
      updateSite = new URI(url);
    } catch (URISyntaxException e) {
      log.error(e);
    }
    return updateSite;
  }

  private URI getDevStudioReleaseSite() {
    URI releaseSite = null;
    try {
      IPreferenceStore preferenceStore =
          org.wso2.developerstudio.eclipse.platform.ui.Activator.getDefault().getPreferenceStore();
      String url = preferenceStore.getString(UpdateCheckerPreferencePage.RELESE_SITE_URL);
      releaseSite = new URI(url);
    } catch (URISyntaxException e) {
      log.error(e);
    }
    return releaseSite;
  }
}
Beispiel #15
0
public class LibraryUtils {
	private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
	
	public static String axiom_1_2_11_wso2vXX_jar = "axiom_1.2.11.wso2v4.jar"; 
	public static String axis2_1_6_1_wso2vXX_jar = "axis2_1.6.1.wso2v10.jar";
	public static String httpcore_4_3_0_wso2vXX_jar = "httpcore_4.3.0.wso2v1.jar";
	public static String woden_1_0_0_M8_wso2vXX_jar = "woden-1.0.0.M8-wso2v1.jar";
	public static String synapse_core_2_1_2_wso2vXX_jar = "synapse-core_2.1.2.wso2v2.jar";
	
	public static File getDependencyPath(String dependencyName, boolean isRelativePath){
		String dependencyPath = getLibLocation() + dependencyName;  
		URL resource = getResourceURL(dependencyPath);
		return getDependencyPath(resource,isRelativePath);
	}

	public static File getDependencyPath(String dependencyName){
		return getDependencyPath(dependencyName,true);
	}
	
	public static URL getResourceURL(String dependencyPath) {
		return Platform.getBundle(Activator.PLUGIN_ID).getResource(dependencyPath);
	}

	public static File getDependencyPath(URL resource) {
		return getDependencyPath(resource,true);
	}
	
	public static File getDependencyPath(URL resource, boolean isRelativePath) {
		if (resource!=null) {
			IPath path = Activator.getDefault().getStateLocation();
			IPath libFolder = path.append("lib");
			String[] paths = resource.getFile().split("/");
			IPath library = libFolder.append(paths[paths.length - 1]);
			File libraryFile = library.toFile();
			if (!libraryFile.exists()) {
				try {
					writeToFile(libraryFile, resource.openStream());
				} catch (IOException e) {
					log.error(e);
					return null;
				}
			}
			if (isRelativePath) {
				IPath relativePath = EclipseUtils
						.getWorkspaceRelativePath(library);
				relativePath = new Path(Constants.ECLIPSE_WORKSPACE_PATH)
						.append(relativePath);
				return relativePath.toFile();
			} else {
				return library.toFile();
			}
		} else{
			log.error("the requested resource does not exist in library path");
			return null;
		}
	}

	private static String getLibLocation() {
		return "lib/";
	} 
	
	private static void writeToFile(File file, InputStream stream) throws IOException{
		file.getParentFile().mkdirs();
	    OutputStream out=new FileOutputStream(file);
	    byte buf[]=new byte[1024];
	    int len;
	    while((len=stream.read(buf))>0)
	    	out.write(buf,0,len);
	    out.close();
	    stream.close();
	}

}
public class ValidateMediatorTransformer extends AbstractEsbNodeTransformer {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  public void transform(TransformationInfo information, EsbNode subject)
      throws TransformerException {
    try {
      information.getParentSequence().addChild(createValidateMediator(subject, information));
      doTransform(information, ((ValidateMediator) subject).getOutputConnector());
    } catch (JaxenException e) {
      throw new TransformerException(e);
    }
  }

  public void createSynapseObject(
      TransformationInfo info, EObject subject, List<Endpoint> endPoints) {}

  public void transformWithinSequence(
      TransformationInfo information, EsbNode subject, SequenceMediator sequence)
      throws TransformerException {

    try {
      sequence.addChild(createValidateMediator(subject, information));
      doTransformWithinSequence(
          information,
          ((ValidateMediator) subject).getOutputConnector().getOutgoingLink(),
          sequence);
    } catch (JaxenException e) {
      throw new TransformerException(e);
    }
  }

  private org.apache.synapse.mediators.builtin.ValidateMediator createValidateMediator(
      EsbNode subject, TransformationInfo information) throws TransformerException, JaxenException {

    /*
     * Check subject.
     */
    Assert.isTrue(subject instanceof ValidateMediator, "Invalid subject.");
    ValidateMediator visualValidateMediator = (ValidateMediator) subject;
    /*
     * Configure Validate mediator.
     */

    org.apache.synapse.mediators.builtin.ValidateMediator validateMediator =
        new org.apache.synapse.mediators.builtin.ValidateMediator();
    setCommonProperties(validateMediator, visualValidateMediator);

    NamespacedProperty sourceXPath = visualValidateMediator.getSourceXpath();
    if (sourceXPath.getPropertyValue() != null && !sourceXPath.getPropertyValue().equals("")) {
      SynapseXPath synapseXPath = new SynapseXPath(sourceXPath.getPropertyValue());
      for (Entry<String, String> entry : sourceXPath.getNamespaces().entrySet()) {
        synapseXPath.addNamespace(entry.getKey(), entry.getValue());
      }
      validateMediator.setSource(synapseXPath);
    }

    List<Value> valueList = new ArrayList<Value>();
    for (ValidateSchema schema : visualValidateMediator.getSchemas()) {

      if (schema.getValidateSchemaKeyType().getLiteral().equals(KeyType.STATIC.getLiteral())) {

        if (schema.getValidateStaticSchemaKey() != null
            && schema.getValidateStaticSchemaKey().getKeyValue() != null) {
          Value val = new Value(schema.getValidateStaticSchemaKey().getKeyValue());
          valueList.add(val);
        }

      } else {

        NamespacedProperty dynamicSchemaKey = schema.getValidateDynamicSchemaKey();
        if (dynamicSchemaKey != null && dynamicSchemaKey.getPropertyValue() != null) {
          SynapseXPath xpath = new SynapseXPath(dynamicSchemaKey.getPropertyValue());
          for (Entry<String, String> entry : dynamicSchemaKey.getNamespaces().entrySet()) {
            xpath.addNamespace(entry.getKey(), entry.getValue());
          }
          Value val = new Value(xpath);
          valueList.add(val);
        }
      }
    }
    validateMediator.setSchemaKeys(valueList);

    // ListMediator onFailMediatorList = new AnonymousListMediator();
    SequenceMediator onFailMediatorList = new SequenceMediator();
    TransformationInfo newOnFailInfo = new TransformationInfo();
    newOnFailInfo.setTraversalDirection(information.getTraversalDirection());
    newOnFailInfo.setSynapseConfiguration(information.getSynapseConfiguration());
    newOnFailInfo.setOriginInSequence(information.getOriginInSequence());
    newOnFailInfo.setOriginOutSequence(information.getOriginOutSequence());
    newOnFailInfo.setCurrentProxy(information.getCurrentProxy());
    newOnFailInfo.setParentSequence(onFailMediatorList);
    doTransform(newOnFailInfo, visualValidateMediator.getOnFailOutputConnector());
    validateMediator.addAll(onFailMediatorList.getList());

    for (ValidateFeature feature : visualValidateMediator.getFeatures()) {
      try {
        validateMediator.addFeature(feature.getFeatureName(), feature.isFeatureEnabled());
      } catch (Exception e) {
        log.error(e);
      }
    }

    if (!visualValidateMediator.getResources().isEmpty()) {

      ResourceMap rMap = new ResourceMap();

      for (ValidateResource resource : visualValidateMediator.getResources()) {

        if (resource.getLocation() != null && resource.getKey() != null) {

          rMap.addResource(resource.getLocation(), resource.getKey().getKeyValue());
        }
      }

      validateMediator.setResourceMap(rMap);
    }

    return validateMediator;
  }
}
public class UserPermissionDialog extends Dialog {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private String[] titles = {"Role", "Read", "Write", "Delete", "Authorize"};
  private Table table;
  private RegistryResourceNode regResourceNode;
  private Button check = null;

  /**
   * UserPermissionDialog constructor
   *
   * @param parentShell
   * @param regNode
   */
  public UserPermissionDialog(Shell parentShell, RegistryResourceNode regNode) {
    super(parentShell);
    this.regResourceNode = regNode;
  }

  /** create dialog */
  public void create() {
    super.create();
  }

  /** create dialog area for the user permission dialog */
  protected Control createDialogArea(final Composite parent) {
    parent
        .getShell()
        .setText(
            "Permissions for "
                + regResourceNode.getConnectionInfo().getUrl().toString()
                + regResourceNode.getRegistryResourcePath());

    GridLayout gridLayout = new GridLayout(1, true);
    gridLayout.marginWidth = 5;
    parent.setLayout(gridLayout);

    Group group = new Group(parent, SWT.FILL);
    group.setLayoutData(new GridData(GridData.FILL_BOTH));
    gridLayout = new GridLayout(1, true);
    group.setLayout(gridLayout);

    createTable(group);
    try {
      loadData();
    } catch (RemoteException e) {
      log.error(e);
    } catch (Exception e) {
      log.error(e);
    }

    return super.createDialogArea(parent);
  }

  /**
   * create table
   *
   * @param composite
   */
  public void createTable(Composite composite) {
    table = new Table(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    table.setHeaderVisible(false);
    table.setLinesVisible(false);
    GridData data = new GridData(GridData.FILL_BOTH);
    table.setLayoutData(data);
    createTableColumns();
  }

  /** create table columns with checkbox */
  public void createTableColumns() {
    TableLayout tableLayout = new TableLayout();
    table.setLayout(tableLayout);
    tableLayout.addColumnData(new ColumnWeightData(10, 150, true));
    TableColumn column = new TableColumn(table, SWT.NONE | SWT.DM_FILL_NONE);

    column.setText(titles[0]);
    column.setAlignment(SWT.LEFT);
    for (int i = 1; i < titles.length; i++) {
      tableLayout.addColumnData(new ColumnWeightData(10, 80, false));
      column = new TableColumn(table, SWT.NONE);
      column.setText(titles[i]);
      column.setAlignment(SWT.CENTER);
    }

    column.addSelectionListener(
        new SelectionListener() {

          public void widgetSelected(SelectionEvent event) {}

          public void widgetDefaultSelected(SelectionEvent event) {}
        });
  }

  private Map<String, Role> getRolePermissionMap(List<Role> roles) {
    Map<String, Role> roleMap = new HashMap<String, ResourceAdmin.Role>();
    for (Role role : roles) {
      roleMap.put(role.getRole(), role);
    }
    return roleMap;
  }

  /**
   * load data for table
   *
   * @throws RemoteException
   * @throws Exception
   */
  public void loadData() throws RemoteException, Exception {
    ResourceAdmin rsAd = regResourceNode.getConnectionInfo().getResourceAdmin();
    ArrayList<Role> resourceInfo =
        rsAd.getPermissionPerResource(regResourceNode.getRegistryResourcePath());
    ArrayList<String> string = new ArrayList<String>();
    string.addAll(
        Arrays.asList(
            regResourceNode
                .getConnectionInfo()
                .getUserManagerContent()
                .getUserManager()
                .getRoles("*")));

    table.removeAll();
    Map<String, Role> rolePermissionMap = getRolePermissionMap(resourceInfo);
    for (String roleName : string) {
      if (roleName.equals("admin")) {
        continue;
      }
      TableItem tableItem = null;
      RoleData roleData = null;
      if (rolePermissionMap.containsKey(roleName)) {
        Role role = rolePermissionMap.get(roleName);
        ArrayList<String> permissionListPerRole = role.getAssignedPermission();
        roleData = getRoleData(role.getRole(), regResourceNode.getRegistryResourcePath());

        tableItem = new TableItem(table, SWT.NULL);
        for (int j = 0; j < permissionListPerRole.size(); j++) {
          if (permissionListPerRole.get(j).equals(BaseConstants.READ)) {
            roleData.setReadPerm(true);
          }
          if (permissionListPerRole.get(j).equals(BaseConstants.WRITE)) {
            roleData.setWritePerm(true);
          }
          if (permissionListPerRole.get(j).equals(BaseConstants.DELETE)) {
            roleData.setDeletePerm(true);
          }
          if (permissionListPerRole.get(j).equals(BaseConstants.AUTHORIZE)) {
            roleData.setAuthPerm(true);
          }
        }
      } else {
        roleData = getRoleData(roleName, regResourceNode.getRegistryResourcePath());
        tableItem = new TableItem(table, SWT.NULL);
      }
      tableItem.setText(roleData.role);
      createTable(tableItem, roleData);
    }
    //		for (int i = 0; i < resourceInfo.size(); i++) {
    //
    //			string.remove(resourceInfo.get(i).getRole());
    //
    //			ArrayList<String> permissionListPerRole = resourceInfo.get(i).getAssignedPermission();
    //			RoleData roleData = getRoleData(resourceInfo.get(i).getRole(),
    //											regResourceNode.getRegistryResourcePath());
    //
    //			TableItem tableItem = new TableItem(table, SWT.NULL);
    //			tableItem.setText(resourceInfo.get(i).getRole());
    //			for (int j = 0; j < permissionListPerRole.size(); j++) {
    //				if (permissionListPerRole.get(j).equals(BaseConstants.READ)) {
    //					roleData.setReadPerm(true);
    //				}
    //				if (permissionListPerRole.get(j).equals(BaseConstants.WRITE)) {
    //					roleData.setWritePerm(true);
    //				}
    //				if (permissionListPerRole.get(j).equals(BaseConstants.DELETE)) {
    //					roleData.setDeletePerm(true);
    //				}
    //				if (permissionListPerRole.get(j).equals(BaseConstants.AUTHORIZE)) {
    //					roleData.setAuthPerm(true);
    //				}
    //
    //			}
    //			createTable(tableItem, roleData);
    //		}
    //
    //		for (Iterator iterator = string.iterator(); iterator.hasNext();) {
    //	        String string2 = (String) iterator.next();
    //	        RoleData roleData = getRoleData(string2,
    //											regResourceNode.getRegistryResourcePath());
    //	        TableItem tableItem = new TableItem(table, SWT.NULL);
    //			tableItem.setText(string2);
    //			createTable(tableItem, roleData);
    //        }
  }

  private void createTable(TableItem tableItem, RoleData roleData) {

    tableItem.setData(roleData);
    createCheckBoxes(1, tableItem, 0, roleData);
    createCheckBoxes(2, tableItem, 1, roleData);
    createCheckBoxes(3, tableItem, 2, roleData);
    createCheckBoxes(4, tableItem, 3, roleData);
  }

  /**
   * get role data
   *
   * @param roleName
   * @param resourcePath
   * @return
   */
  private RoleData getRoleData(String roleName, String resourcePath) {
    return new RoleData(roleName, resourcePath);
  }

  /**
   * create check boxes
   *
   * @param tableIndex
   * @param tabItem
   * @param type
   * @param roleData
   */
  private void createCheckBoxes(int tableIndex, TableItem tabItem, int type, RoleData roleData) {
    TableEditor editor = new TableEditor(table);
    boolean value = false;
    String permission = "";

    if (roleData.role.equals(BaseConstants.ADMIN)) {
      check = new Button(table, SWT.CHECK | SWT.READ_ONLY);
      value = true;
      if (type == 0) {
        permission = BaseConstants.READ;
      }
      if (type == 1) {
        permission = BaseConstants.WRITE;
      }
      if (type == 2) {
        permission = BaseConstants.DELETE;
      }
      if (type == 3) {
        permission = BaseConstants.AUTHORIZE;
      }
    } else {
      check = new Button(table, SWT.CHECK);
      if (type == 0) {
        permission = BaseConstants.READ;
        value = roleData.readPerm;
      }
      if (type == 1) {
        permission = BaseConstants.WRITE;
        value = roleData.writePerm;
      }
      if (type == 2) {
        permission = BaseConstants.DELETE;
        value = roleData.deletePerm;
      }
      if (type == 3) {
        permission = BaseConstants.AUTHORIZE;
        value = roleData.authPerm;
      }
    }
    check.setBackground(table.getBackground());
    editor.grabHorizontal = true;
    editor.setEditor(check, tabItem, tableIndex);
    check.setText(permission);
    check.setSelection(value);
    editor.layout();

    check.addSelectionListener(new RolePermissionSelectionListener(roleData));
  }

  /** RolePermissionSelectionListener inner class */
  public class RolePermissionSelectionListener implements SelectionListener {
    RoleData roleData;
    int type;

    /**
     * RolePermissionSelectionListener constructor set the type variable according to the permission
     * type
     *
     * @param roleData
     */
    public RolePermissionSelectionListener(RoleData roleData) {
      this.roleData = roleData;
      int type;
      if (roleData.readPerm) {
        type = 0;
      } else if (roleData.writePerm) {
        type = 1;
      } else if (roleData.deletePerm) {
        type = 2;
      } else if (roleData.authPerm) {
        type = 3;
      } else {
        type = -1;
      }
    }

    /** triggered when check box is selected or de-selected */
    public void widgetSelected(SelectionEvent event) {

      boolean b = ((Button) (event.widget)).getSelection();
      String permission = ((Button) (event.widget)).getText();

      if (permission == BaseConstants.READ) {
        roleData.setReadPerm(b);
        type = 0;
      } else if (permission == BaseConstants.WRITE) {
        roleData.setWritePerm(b);
        type = 1;
      } else if (permission == BaseConstants.DELETE) {
        roleData.setDeletePerm(b);
        type = 2;
      } else if (permission == BaseConstants.AUTHORIZE) {
        roleData.setAuthPerm(b);
        type = 3;
      }

      try {
        grantPermissionToRole(roleData);
      } catch (AxisFault e) {
        log.error(e);
      } catch (RemoteException e) {
        log.error(e);
      } catch (Exception e) {
        log.error(e);
      }
    }

    public void widgetDefaultSelected(SelectionEvent event) {}
  }

  /**
   * grant permission to the role
   *
   * @param roleData
   * @throws Exception
   */
  private void grantPermissionToRole(RoleData roleData) throws Exception {
    String permission = null;

    RegistryNode regNode = regResourceNode.getConnectionInfo();
    ResourceAdmin resourceAdmin = regNode.getResourceAdmin();
    if (roleData.isReadPerm()) {
      permission = BaseConstants.READ;
      resourceAdmin.setPermissionPerResource(
          regResourceNode.getRegistryResourcePath(), permission, roleData.role, "1");
    }

    if (roleData.isWritePerm()) {
      permission = BaseConstants.WRITE;
      resourceAdmin.setPermissionPerResource(
          regResourceNode.getRegistryResourcePath(), permission, roleData.role, "1");
    }

    if (roleData.isDeletePerm()) {
      permission = BaseConstants.DELETE;
      resourceAdmin.setPermissionPerResource(
          regResourceNode.getRegistryResourcePath(), permission, roleData.role, "1");
    }
    if (roleData.isAuthPerm()) {
      permission = BaseConstants.AUTHORIZE;
      resourceAdmin.setPermissionPerResource(
          regResourceNode.getRegistryResourcePath(), permission, roleData.role, "1");
    }
  }

  /** ok pressed event of the dialog */
  protected void okPressed() {
    super.okPressed();
  }

  /**
   * get roles for the user
   *
   * @return
   */
  public String[] getRolesPerUser() {
    UserManager um = regResourceNode.getConnectionInfo().getUserManagerContent().getUserManager();
    String[] roles = um.getRoles("*");
    return roles;
  }

  /**
   * get roles for the selected resource
   *
   * @return
   */
  public ArrayList<String> getRolesPerResource() {
    String[] allRoles = getRolesPerUser();
    ArrayList<String> validRoles = new ArrayList<String>();
    for (int i = 0; i < allRoles.length; i++) {
      if (!allRoles[i].equals("admin")) {
        validRoles.add(allRoles[i]);
      }
    }
    return validRoles;
  }

  /** inner class to represent role */
  public static class RoleData {
    public String role;
    String[] allRoles;
    String[] allPermList;
    String[] selectedPermissionList;
    RegistryNode regData;
    String resourcePath;

    private boolean readPerm = false;
    private boolean writePerm = false;
    private boolean deletePerm = false;
    private boolean authPerm = false;

    public RoleData(String role, String resourcePath) {
      this.role = role;
      this.resourcePath = resourcePath;
    }

    public String getResourcePath() {
      return resourcePath;
    }

    public void setResourcePath(String resourcePath) {
      this.resourcePath = resourcePath;
    }

    public boolean isReadPerm() {
      return readPerm;
    }

    public void setReadPerm(boolean readPerm) {
      this.readPerm = readPerm;
    }

    public boolean isWritePerm() {
      return writePerm;
    }

    public void setWritePerm(boolean writePerm) {
      this.writePerm = writePerm;
    }

    public boolean isDeletePerm() {
      return deletePerm;
    }

    public void setDeletePerm(boolean deletePerm) {
      this.deletePerm = deletePerm;
    }

    public boolean isAuthPerm() {
      return authPerm;
    }

    public void setAuthPerm(boolean authPerm) {
      this.authPerm = authPerm;
    }
  }
}
Beispiel #18
0
public final class RegistryUrlStore {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private File urlListFile;
  private List<RegistryURLInfo> urlList;
  private static RegistryUrlStore instance;

  /** RegistryUrlStore constructor */
  private RegistryUrlStore() {}

  /** */
  private void init() {
    urlList = new ArrayList<RegistryURLInfo>();
    urlListFile =
        new File(
            ResourcesPlugin.getWorkspace()
                .getRoot()
                .getLocation()
                .append(".metadata")
                .append(Activator.PLUGIN_ID)
                .append("urls.txt")
                .toOSString());
    readUrlsFromFile();
  }

  /**
   * get the instance of the RegistryUrlStore
   *
   * @return
   */
  public static RegistryUrlStore getInstance() {
    if (instance == null) {
      instance = new RegistryUrlStore();
      instance.init();
    }
    return instance;
  }

  /** read added regisrty urls from the temperary file which contains urls of added registries */
  private void readUrlsFromFile() {
    urlList.clear();
    synchronized (urlList) {
      if (!urlListFile.exists()) {
        return;
      }
      StringBuilder contents = new StringBuilder();

      try {
        BufferedReader input = new BufferedReader(new FileReader(urlListFile));
        try {
          String line = null; // not declared within while loop
          while ((line = input.readLine()) != null) {
            int i = line.indexOf(" ");
            if (i > 0) {
              String url = line.substring(0, i).trim();
              String state_uname_path = line.substring(i).trim();
              i = state_uname_path.indexOf(" ");
              if (i > 0) {
                String state = state_uname_path.substring(0, i).trim();
                String uname_path = state_uname_path.substring(i).trim();
                i = uname_path.indexOf(" ");
                if (i > 0) {
                  String uname = uname_path.substring(0, i).trim();
                  String path = uname_path.substring(i).trim();
                  RegistryURLInfo registryURLInfo = new RegistryURLInfo();
                  registryURLInfo.setPersist(false);
                  registryURLInfo.setUrl(new URL(url));
                  registryURLInfo.setPath(path);
                  registryURLInfo.setUsername(uname);
                  registryURLInfo.setEnabled(state.equalsIgnoreCase("true"));
                  urlList.add(registryURLInfo);
                  registryURLInfo.setPersist(true);
                }
              }
            }
            contents.append(line);
            contents.append(System.getProperty("line.separator"));
          }
        } finally {
          input.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }

  /** save newly added registry url to the url file */
  private void saveUrlsToFile() {
    if (urlListFile.exists()) {
      urlListFile.delete();
    }
    if (!urlListFile.getParentFile().exists()) {
      urlListFile.getParentFile().mkdirs();
    }
    Writer output = null;
    try {
      output = new BufferedWriter(new FileWriter(urlListFile));
      for (RegistryURLInfo registryURLInfo : urlList) {
        try {
          output.write(
              registryURLInfo.getUrl().toString()
                  + " "
                  + Boolean.toString(registryURLInfo.isEnabled())
                  + " "
                  + registryURLInfo.getUsername()
                  + " "
                  + registryURLInfo.getPath()
                  + "\n");
        } catch (IOException e) {
          log.error(e);
        }
      }
    } catch (IOException e) {
      log.error(e);
    } finally {
      if (output != null)
        try {
          output.close();
        } catch (IOException e) {
          log.error(e);
        }
    }
  }

  /**
   * get all registryUrls
   *
   * @return
   */
  public List<RegistryURLInfo> getAllRegistryUrls() {
    return urlList;
  }

  /**
   * add Registry url to url list and save it to the file
   *
   * @param registryUrl
   * @param username
   * @param path
   * @return
   */
  public RegistryURLInfo addRegistryUrl(URL registryUrl, String username, String path) {
    createRegistryPropertyFile(registryUrl.getHost() + "." + registryUrl.getPort());
    RegistryURLInfo info = new RegistryURLInfo();
    info.setUrl(registryUrl);
    info.setPath(path);
    info.setUsername(username);
    if (!urlList.contains(info)) {
      urlList.add(info);
      saveUrlsToFile();
    }
    return info;
  }

  public void modifyRegistryUrl(String registryUrl, String username, String oldUser) {

    Iterator<RegistryURLInfo> iterator = urlList.iterator();
    while (iterator.hasNext()) {
      RegistryURLInfo reginfo = iterator.next();
      if (registryUrl.equals(reginfo.getUrl().toString())
          && (oldUser == null || oldUser.equals(reginfo.getUsername()))) {
        reginfo.setUsername(username);
      }
    }
    saveUrlsToFile();
  }

  /**
   * remove Registry url to url list and update the file
   *
   * @param info
   */
  public void removeRegistryUrl(RegistryURLInfo info) {
    if (urlList.contains(info)) {
      urlList.remove(info);
      saveUrlsToFile();
      removeRegistryPropertyFile(info.getUrl().getHost() + "." + info.getUrl().getPort());
    }
  }

  /** keep track of previously added registries */
  public void persist() {
    saveUrlsToFile();
  }

  private void createRegistryPropertyFile(String serverUrl) {
    File regiistryNodeFile =
        new File(
            ResourcesPlugin.getWorkspace()
                .getRoot()
                .getLocation()
                .append(".tmp")
                .append(Activator.PLUGIN_ID)
                .append(serverUrl.concat(".txt"))
                .toOSString());
    if (regiistryNodeFile.exists()) {
      FileUtils.deleteQuietly(regiistryNodeFile);
    }
    if (!regiistryNodeFile.getParentFile().exists()) {
      regiistryNodeFile.getParentFile().mkdirs();
    }
    try {
      regiistryNodeFile.createNewFile();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  private void removeRegistryPropertyFile(String serverUrl) {
    File regiistryNodeFile =
        new File(
            ResourcesPlugin.getWorkspace()
                .getRoot()
                .getLocation()
                .append(".tmp")
                .append(Activator.PLUGIN_ID)
                .append(serverUrl.concat(".txt"))
                .toOSString());
    if (regiistryNodeFile.exists()) {
      FileUtils.deleteQuietly(regiistryNodeFile);
    }
  }
}
public class ProxyServiceModel extends ProjectDataModel {

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private ArtifactTemplate selectedTemplate;
  private List<OMElement> availablePSList;
  private IContainer proxyServiceSaveLocation;
  private String proxyServiceName = "";
  private String endPointUrl = "";
  private String endPointKey = "";
  private String secPolicy = "";
  private String wsdlUri = "";
  private String wsdlService = "";
  private String wsdlPort = "";
  private boolean publishSameService;
  private String requestLogLevel = "none";
  private String responseLogLevel = "none";
  private String requestXSLT = "";
  private String responseXSLT = "";
  private boolean transformResponses;
  private boolean predefinedEP;
  private String predefinedEndPoint;
  List<OMElement> selectedProxyList = new ArrayList<OMElement>();
  private TargetEPType targetEPType = TargetEPType.URL;

  public Object getModelPropertyValue(String key) {
    Object modelPropertyValue = super.getModelPropertyValue(key);
    if (modelPropertyValue == null) {
      if (key.equals(PsArtifactConstants.WIZARD_OPTION_PS_TYPE)) {
        modelPropertyValue = getSelectedTemplate();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_SAVE_LOCATION)) {
        IContainer container = getProxyServiceSaveLocation();
        if (container != null && container instanceof IFolder) {
          IFolder proxyFolder =
              container
                  .getProject()
                  .getFolder("src")
                  .getFolder("main")
                  .getFolder("synapse-config")
                  .getFolder("proxy-services");
          modelPropertyValue = proxyFolder;
        } else {
          modelPropertyValue = container;
        }
      } else if (key.equals("proxy.target.ep.type")) {
        modelPropertyValue = getTargetEPType();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPURL)) {
        modelPropertyValue = getEndPointUrl();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPKEY)) {
        modelPropertyValue = getEndPointkey();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_SECURE_PS_SECPOLICY)) {
        modelPropertyValue = getSecPolicy();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLURL)) {
        modelPropertyValue = getWsdlUri();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLSERVICE)) {
        modelPropertyValue = getWsdlService();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLPORT)) {
        modelPropertyValue = getWsdlPort();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_PUBLISHSAME)) {
        modelPropertyValue = isPublishSameService();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_LOGGING_PS_REQLOGLEVEL)) {
        modelPropertyValue = getRequestLogLevel();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_LOGGING_PS_RESLOGLEVEL)) {
        modelPropertyValue = getResponseLogLevel();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_XSLT)) {
        modelPropertyValue = getRequestXSLT();
      } else if (key.equals(
          PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_TRANSFORMRESPONSES)) {
        modelPropertyValue = isTransformResponses();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_RESXSLT)) {
        modelPropertyValue = getResponseXSLT();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_PREDEFINED)) {
        modelPropertyValue = predefinedEP;
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPLIST)) {
        modelPropertyValue = getPredefinedEndPoint();
      } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_AVAILABLE_PS)) {
        if (selectedProxyList != null) {
          modelPropertyValue = selectedProxyList.toArray();
        }
      }
    }
    return modelPropertyValue;
  }

  public boolean setModelPropertyValue(String key, Object data) throws ObserverFailedException {
    boolean returnResult = super.setModelPropertyValue(key, data);
    if (key.equals(PsArtifactConstants.WIZARD_OPTION_IMPORT_FILE)) {
      if (getImportFile() != null && !getImportFile().toString().equals("")) {
        try {
          List<OMElement> availableProxies = new ArrayList<OMElement>();
          if (SynapseFileUtils.isSynapseConfGiven(
              getImportFile(), SynapseEntryType.PROXY_SERVICE)) {
            availableProxies =
                SynapseFileUtils.synapseFileProcessing(
                    getImportFile().getPath(), SynapseEntryType.PROXY_SERVICE);
            setAvailablePSList(availableProxies);
          } else {
            setAvailablePSList(new ArrayList<OMElement>());
          }
          returnResult = false;
        } catch (OMException e) {
          log.error("Error reading object model", e);
        } catch (XMLStreamException e) {
          log.error("XML stream error", e);
        } catch (IOException e) {
          log.error("I/O error has occurred", e);
        } catch (Exception e) {
          log.error("An unexpected error has occurred", e);
        }
      }
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_PS_TYPE)) {
      ArtifactTemplate template = (ArtifactTemplate) data;
      setSelectedTemplate(template);
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_SAVE_LOCATION)) {
      IContainer container = (IContainer) data;
      if (container != null && container instanceof IFolder) {
        IFolder proxyFolder =
            container
                .getProject()
                .getFolder("src")
                .getFolder("main")
                .getFolder("synapse-config")
                .getFolder("proxy-services");
        setProxyServiceSaveLocation(proxyFolder);
      } else {
        setProxyServiceSaveLocation(container);
      }
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_CREATE_ESB_PROJECT)) {
      Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
      IProject esbProject = ESBProjectUtils.createESBProject(shell, getLocation());
      if (esbProject != null) {
        setProxyServiceSaveLocation(esbProject);
      }
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_PS_NAME)) {
      setProxyServiceName(data.toString());
    } else if (key.equals("proxy.target.ep.type")) {
      setTargetEPType((TargetEPType) data);
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPURL)) {
      setEndPointUrl(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPKEY)) {
      setEndPointKey(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_SECURE_PS_SECPOLICY)) {
      setSecPolicy(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLURL)) {
      setWsdlUri(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLSERVICE)) {
      setWsdlService(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_WSDLPORT)) {
      setWsdlPort(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_WSDL_PS_PUBLISHSAME)) {
      setPublishSameService((Boolean) data);
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_LOGGING_PS_REQLOGLEVEL)) {
      setRequestLogLevel(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_LOGGING_PS_RESLOGLEVEL)) {
      setResponseLogLevel(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_XSLT)) {
      setRequestXSLT(data.toString());
    } else if (key.equals(
        PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_TRANSFORMRESPONSES)) {
      setTransformResponses((Boolean) data);
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_TRANSFORMER_PS_RESXSLT)) {
      setResponseXSLT(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_TEMPL_COMMON_PS_EPLIST)) {
      setPredefinedEndPoint(data.toString());
    } else if (key.equals(PsArtifactConstants.WIZARD_OPTION_AVAILABLE_PS)) {
      Object[] selectedEPs = (Object[]) data;
      if (selectedProxyList != null) selectedProxyList.clear();
      for (Object object : selectedEPs) {
        if (object instanceof OMElement) {
          selectedProxyList.add((OMElement) object);
        }
      }
      setSelectedProxyList(selectedProxyList);
    }
    return returnResult;
  }

  public void setEndPointUrl(String endPointUrl) {
    this.endPointUrl = endPointUrl;
  }

  public String getEndPointUrl() {
    return this.endPointUrl;
  }

  public void setEndPointKey(String endPointKey) {
    this.endPointKey = endPointKey;
  }

  public String getEndPointkey() {
    return endPointKey;
  }

  public void setSecPolicy(String secPolicy) {
    this.secPolicy = secPolicy;
  }

  public String getSecPolicy() {
    return secPolicy;
  }

  public void setWsdlUri(String wsdlUri) {
    this.wsdlUri = wsdlUri;
  }

  public String getWsdlUri() {
    return wsdlUri;
  }

  public void setWsdlService(String wsdlservice) {
    this.wsdlService = wsdlservice;
  }

  public String getWsdlService() {
    return wsdlService;
  }

  public void setWsdlPort(String wsdlPort) {
    this.wsdlPort = wsdlPort;
  }

  public String getWsdlPort() {
    return wsdlPort;
  }

  public void setPublishSameService(boolean publishSameService) {
    this.publishSameService = publishSameService;
  }

  public boolean isPublishSameService() {
    return publishSameService;
  }

  public void setRequestLogLevel(String requestLogLevel) {
    this.requestLogLevel = requestLogLevel;
  }

  public String getRequestLogLevel() {
    return requestLogLevel.toLowerCase();
  }

  public void setResponseLogLevel(String responseLogLevel) {
    this.responseLogLevel = responseLogLevel;
  }

  public String getResponseLogLevel() {
    return responseLogLevel.toLowerCase();
  }

  public void setRequestXSLT(String requestXSLT) {
    this.requestXSLT = requestXSLT;
  }

  public String getPredefinedEndPoint() {
    return predefinedEndPoint;
  }

  public void setPredefinedEndPoint(String predefinedEndPoint) {
    this.predefinedEndPoint = predefinedEndPoint;
  }

  public String getRequestXSLT() {
    return requestXSLT;
  }

  public void setTransformResponses(boolean transformResponses) {
    this.transformResponses = transformResponses;
  }

  public boolean isTransformResponses() {
    return transformResponses;
  }

  public void setSelectedTemplate(ArtifactTemplate selectedTemplate) {
    this.selectedTemplate = selectedTemplate;
  }

  public ArtifactTemplate getSelectedTemplate() {
    return selectedTemplate;
  }

  public void setAvailablePSList(List<OMElement> availablePSList) {
    this.availablePSList = availablePSList;
  }

  public List<OMElement> getAvailablePSList() {
    return availablePSList;
  }

  public void setProxyServiceSaveLocation(IContainer proxyServiceSaveLocation) {
    this.proxyServiceSaveLocation = proxyServiceSaveLocation;
  }

  public void setProxyServiceSaveLocation(String proxyServiceSaveLocation) {
    this.proxyServiceSaveLocation =
        ResourcesPlugin.getWorkspace()
            .getRoot()
            .getContainerForLocation(new Path(proxyServiceSaveLocation));
  }

  public IContainer getProxyServiceSaveLocation() {
    return proxyServiceSaveLocation;
  }

  public void setLocation(File location) {
    super.setLocation(location);
    File absolutionPath = getLocation();
    if (getProxyServiceSaveLocation() == null && absolutionPath != null) {
      IContainer newEndpointSaveLocation =
          getContainer(absolutionPath, PsArtifactConstants.ESB_PROJECT_NATURE);
      setProxyServiceSaveLocation(newEndpointSaveLocation);
    }
  }

  public static IContainer getContainer(File absolutionPath, String projectNature) {
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    int length = 0;
    IProject currentSelection = null;
    for (IProject project : projects) {
      try {
        if (project.isOpen() && project.hasNature(projectNature)) {
          File projectLocation = project.getLocation().toFile();
          int projectLocationLength = projectLocation.toString().length();
          if (projectLocationLength > length
              && projectLocationLength <= absolutionPath.toString().length()) {
            if (absolutionPath.toString().startsWith(projectLocation.toString())) {
              length = projectLocationLength;
              currentSelection = project;
            }
          }
        }
      } catch (CoreException e) {
        e.printStackTrace();
      }
    }
    IContainer newProxyServiceSaveLocation = null;
    if (currentSelection != null) {
      String path =
          absolutionPath
              .toString()
              .substring(currentSelection.getLocation().toFile().toString().length());

      if (path.equals("")) {
        newProxyServiceSaveLocation = currentSelection;
      } else {
        newProxyServiceSaveLocation = currentSelection.getFolder(path);
      }
    }
    return newProxyServiceSaveLocation;
  }

  public void setProxyServiceName(String psName) {
    this.proxyServiceName = psName;
  }

  public String getProxyServiceName() {
    return proxyServiceName;
  }

  public void setSelectedProxyList(List<OMElement> selectedProxyList) {
    this.selectedProxyList = selectedProxyList;
  }

  public List<OMElement> getSelectedProxyList() {
    return selectedProxyList;
  }

  public void setTargetEPType(TargetEPType targetEPType) {
    this.targetEPType = targetEPType;
  }

  public TargetEPType getTargetEPType() {
    return targetEPType;
  }

  public String getResponseXSLT() {
    return responseXSLT;
  }

  public void setResponseXSLT(String responseXSLT) {
    this.responseXSLT = responseXSLT;
  }

  public enum TargetEPType {
    URL,
    PREDEFINED,
    REGISTRY
  }
}
@SuppressWarnings("restriction")
public final class CarbonServerManager implements IServerManager {
  private static final String CARBON_SERVER_TYPE_REMOTE =
      "org.wso2.developerstudio.eclipse.carbon.server.remote";
  private static final String RESOURCE = "resource";
  private static final String RESOURCE_CHANGE_KIND = "resourceChangeKind";

  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private static List<IServer> servers;
  private static Map<String, ICarbonOperationManager> serverPlugins;
  private static Map<String, String> serverRuntimePlugins;

  private static CarbonServerManager instance;
  private static Map<IServer, CarbonServerInformation> appServerInformation;
  private static CarbonServerLifeCycleListener carbonServerLifeCycleListener;

  private static boolean isServerAdded;
  private IProject rootProject;
  private int resourceChngeKind;

  private CarbonServerManager() {
    init();
  }

  public static CarbonServerManager getInstance() {
    if (instance == null) instance = new CarbonServerManager();
    return instance;
  }

  private static Map<String, ICarbonOperationManager> getServerPlugin() {
    if (serverPlugins == null) serverPlugins = new HashMap<String, ICarbonOperationManager>();
    if (serverRuntimePlugins == null) serverRuntimePlugins = new HashMap<String, String>();
    return serverPlugins;
  }

  private static Map<String, String> getServerRuntimeIdPlugin() {
    if (serverRuntimePlugins == null) serverRuntimePlugins = new HashMap<String, String>();
    return serverRuntimePlugins;
  }

  public static List<IServer> getServers() {
    if (servers == null) servers = new ArrayList<IServer>();
    return servers;
  }

  public static void serverAdded(IServer server) {
    ICarbonOperationManager serverOperationManager = getServerOperationManager(server);
    if (serverOperationManager != null) {
      getServers().add(server);
      isServerAdded = true;
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVER_PORTS);
      Object r;
      CarbonServerInformation serverInformation = new CarbonServerInformation();
      serverInformation.setServerId(server.getId());
      ServerPort[] wsasPorts = new ServerPort[] {};
      try {
        r = wsasServerManager.executeOperationOnServer(server, operationParameters);
        if (r instanceof ServerPort[]) wsasPorts = (ServerPort[]) r;
        CarbonServerUtils.setServicePath(server);
      } catch (NoSuchCarbonOperationDefinedException e) {
        // ports cannot be retrieved
      } catch (Exception e) {
        log.error(e);
      }
      serverInformation.setServerPorts(wsasPorts);
      // The localrepo path is for now is the bin distribution path. this
      // needs to be fixed in order to be set inside the workspace path
      // String workspaceRootPath =
      // ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
      // String serverPath=FileUtils.addNodesToPath(workspaceRootPath, new
      // String[]{".metadata",".carbon",server.getId()});
      IPath serverHome = getServerHome(server);
      if (serverHome != null) {
        String serverPath = serverHome.toOSString();
        (new File(serverPath)).mkdirs();
        serverInformation.setServerLocalWorkspacePath(serverPath);
      }
      getAppServerInformation().put(server, serverInformation);
      try {
        initializeServerConfigurations(server);
      } catch (Exception e) {
        log.error(e);
      }
    }
  }

  public static void serverRemoved(IServer server) {
    if (getServers().contains(server)) {
      try {
        cleanupServerConfigurations(server);
      } catch (Exception e) {
        log.error(e);
      }
      getServers().remove(server);
      if (getAppServerInformation().containsKey(server)) getAppServerInformation().remove(server);
    }
  }

  public static void serverStateChanged(IServer server) {}

  public static void registerAppServerPlugin(String serverId, ICarbonOperationManager opManager) {
    if (!getServerPlugin().containsKey(serverId)) {
      getServerPlugin().put(serverId, opManager);
      getServerRuntimeIdPlugin().put(opManager.getRuntimeId(), serverId);
      addExistingServers();
    }
  }

  public static void unregisterAppServerPlugin(String serverId) {
    if (getServerPlugin().containsKey(serverId)) serverPlugins.remove(serverId);
  }

  public static ICarbonOperationManager getServerOperationManager(IServer server) {
    return getServerOperationManager(server.getId());
  }

  public static ICarbonOperationManager getServerOperationManager(String serverId) {
    IServer server = getServer(serverId);
    if (getServerPlugin().containsKey(server.getServerType().getId()))
      return getServerPlugin().get(server.getServerType().getId());
    else {
      return null;
    }
  }

  public static ICarbonOperationManager getServerOperationManagerByServerType(String serverTypeId) {
    if (getServerPlugin().containsKey(serverTypeId)) return getServerPlugin().get(serverTypeId);
    else {
      return null;
    }
  }

  public Object executeOperationOnServer(IServer server, Map<String, Object> operation)
      throws Exception {
    return executeOperationOnServer(server.getId(), operation);
  }

  public Object executeOperationOnServer(String serverId, Map<String, Object> operation)
      throws Exception {
    ICarbonOperationManager serverOperationManager = getServerOperationManager(serverId);
    if (!operation.containsKey(ICarbonOperationManager.PARAMETER_SERVER))
      addServerToParameters(operation, getServer(serverId));
    if (serverOperationManager == null) return null;
    else return serverOperationManager.executeOperation(operation);
  }

  public static IServer getServer(String serverId) {
    IServer server = null;
    for (IServer s : getServers()) {
      if (s.getId().equalsIgnoreCase(serverId)) {
        server = s;
        break;
      }
    }
    if (server == null) {
      IServer[] s = ServerCore.getServers();
      for (IServer aserver : s) {
        if (aserver.getId().equals(serverId)) {
          server = aserver;
          break;
        }
      }
    }
    return server;
  }

  public IProject[] getProjectsUsedByRuntime(String serverId) {
    return null;
  }

  public String getRuntimeServerIdForProject(IProject project) {
    // for(IServer server:getServers()){
    // for(IModule module:server.getModules()){
    // if (module.getProject()==project){
    // break;
    // }
    // }
    // }
    return null;
  }

  public static String[] getServerIdForProject(IProject project) {
    List<String> serverIds = new ArrayList<String>();
    IServer[] serversForProject = getServersForProject(project);
    for (IServer server : serversForProject) {
      serverIds.add(server.getId());
    }
    return serverIds.toArray(new String[] {});
  }

  public static IServer[] getServersForProject(IProject project) {
    List<IServer> serverIds = new ArrayList<IServer>();
    for (IServer server : getServers()) {
      for (IModule module : server.getModules()) {
        if (module.getProject() == project) {
          serverIds.add(server);
        }
      }
    }
    return serverIds.toArray(new IServer[] {});
  }

  public IPath getServerHome(String serverId) {
    IServer server = getServer(serverId);
    return getServerHome(server);
  }

  public static IPath getServerHome(IServer server) {
    IPath location = null;
    if (server != null) {
      IServerManager wsasServerManager = getInstance();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVER_HOME);
      Object r;
      try {
        r = wsasServerManager.executeOperationOnServer(server, operationParameters);
        if (r instanceof IPath) location = (IPath) r;
      } catch (NoSuchCarbonOperationDefinedException e) {
        return null;
      } catch (Exception e) {
        log.error(e);
      }
    }

    return location;
  }

  public int getServerStatus(String serverId) {
    IServer server = getServer(serverId);
    if (server == null) return 0;
    else return server.getServerState();
  }

  public boolean restartServer(String serverId) {
    IServer server = getServer(serverId);
    if (server == null) return false;
    else {
      // TODO the restart a server
      return false;
    }
  }

  public boolean startServer(String serverId, Object shell) {
    IServer server = getServer(serverId);
    if (server == null) return false;
    else {
      try {
        if (server.getServerState() != IServer.STATE_STARTING) {
          server.start("run", (IProgressMonitor) null);
        }
        if (shell == null) return true;
        else {
          if (shell instanceof Shell) return waitUntilTheServerStarts(server, (Shell) shell);
          else return true;
        }
      } catch (CoreException e) {
        return false;
      }
    }
  }

  public static IServer getRunningServer() {
    IServer server = null;
    for (IServer s : getServers()) {
      if (s.getServerState() == IServer.STATE_STARTED) {
        server = s;
        break;
      }
    }
    return server;
  }

  public boolean stopServer(String serverId) {
    IServer server = getServer(serverId);
    if (server == null) return false;
    else {
      server.stop(false);
      return true;
    }
  }

  public static void initiateAppServerManagementOperations() {
    carbonServerLifeCycleListener = new CarbonServerLifeCycleListener();
    ServerCore.addServerLifecycleListener(carbonServerLifeCycleListener);
  }

  public static void deInitiateAppServerManagementOperations() {
    if (carbonServerLifeCycleListener != null) {
      ServerCore.removeServerLifecycleListener(carbonServerLifeCycleListener);
    }
  }

  private static void addExistingServers() {
    IServer[] s = ServerCore.getServers();
    for (IServer server : s) {
      if (!getServers().contains(server)) serverAdded(server);
    }
  }

  public String[] getServerIds() {
    List<String> list = new ArrayList<String>();
    for (IServer server : getServers()) {
      list.add(server.getId());
    }
    return list.toArray(new String[] {});
  }

  public String[] getServerLibraryPaths(String serverId) throws Exception {
    IServer server = getServer(serverId);
    return getServerLibraryPaths(server);
  }

  public static String[] getServerLibraryPaths(IServer server) throws Exception {
    String[] result = null;
    if (server != null) {
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
      Object r =
          wsasServerManager.executeOperationOnServer(
              server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
      if (r instanceof String[]) {
        result = (String[]) r;
        IPath serverLocation = getServerHome(server);
        for (int i = 0; i < result.length; i++) {
          result[i] = FileUtils.addAnotherNodeToPath(serverLocation.toOSString(), result[i]);
        }
      }
    }
    return result;
  }

  public static URL getServiceWSDLUrl(IServer server, String serviceName) throws Exception {
    URL result = null;
    if (server != null) {
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVICE_WSDL_URL);
      operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
      Object r =
          wsasServerManager.executeOperationOnServer(
              server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
      if (r instanceof URL) {
        result = (URL) r;
      }
    }
    return result;
  }

  public static URL getServiceTryItUrl(IServer server, String serviceName) throws Exception {
    URL result = null;
    if (server != null) {
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVICE_TRY_IT_URL);
      operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
      Object r =
          wsasServerManager.executeOperationOnServer(
              server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
      if (r instanceof URL) {
        result = (URL) r;
      }
    }
    return result;
  }

  public static Map<IServer, CarbonServerInformation> getAppServerInformation() {
    if (appServerInformation == null)
      appServerInformation = new HashMap<IServer, CarbonServerInformation>();
    return appServerInformation;
  }

  public ServerPort[] getServerPorts(IServer server) {
    GenericServer gserver = (GenericServer) server.getAdapter(GenericServer.class);
    return gserver.getServerPorts();
  }

  public static String getServerLocalWorkspacePath(IServer server) {
    if (getAppServerInformation().containsKey(server)) {
      return getAppServerInformation().get(server).getServerLocalWorkspacePath();
    } else return null;
  }

  public Map<String, Integer> getServerPorts(String serverId) throws Exception {
    Map<String, Integer> result = new HashMap<String, Integer>();
    IServer server = getServer(serverId);
    if (server != null) {
      ServerPort[] serverPorts2 = getServerPorts(server);
      if (serverPorts2 != null)
        for (ServerPort s : serverPorts2) {
          result.put(s.getProtocol(), s.getPort());
        }
    }
    return result;
  }

  public static void addServerToParameters(Map<String, Object> properties, IServer server) {
    properties.put(ICarbonOperationManager.PARAMETER_SERVER, server);
  }

  public static boolean isOperationSupported(IServer server, int operation) throws Exception {
    IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_SUPPORTED_OPERATIONS);
    operationParameters.put(ICarbonOperationManager.PARAMETER_OP_TYPES, operation);
    Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);
    if (r instanceof Boolean) {
      return (Boolean) r;
    }
    return false;
  }

  public static void initializeServerConfigurations(IServer server) throws Exception {
    IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_INITIALIZE_SERVER_CONFIGURATIONS);
    wsasServerManager.executeOperationOnServer(server, operationParameters);
  }

  public static void cleanupServerConfigurations(IServer server) throws Exception {
    IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_CLEANUP_SERVER_CONFIGURATIONS);
    wsasServerManager.executeOperationOnServer(server, operationParameters);
  }

  public boolean publishServiceModule(String serverId, String webTempPath, String projectName) {
    IServer server = getServer(serverId);
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_PUBLISH_MODULE);
    operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
    try {
      wsasServerManager.executeOperationOnServer(server, operationParameters);
      return true;
    } catch (Exception e) {
      log.error(e);
      return false;
    }
  }

  public boolean hotUpdateServiceModule(String serverId, String webTempPath, String projectName) {
    IServer server = getServer(serverId);
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    CarbonServerManager wsasServerManager = this;
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_HOT_UPDATE_MODULE);
    operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
    try {
      wsasServerManager.executeOperationOnServer(server, operationParameters);
      return true;
    } catch (Exception e) {
      log.error(e);
      return false;
    }
  }

  public boolean hotUpdateWebApp(String serverId, IResource resource, String projectName) {

    IServer server = getServer(serverId);
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    CarbonServerManager wsasServerManager = this;
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_HOT_UPDATE_MODULE);
    operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, "");
    operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
    operationParameters.put(RESOURCE, resource);
    operationParameters.put(RESOURCE_CHANGE_KIND, new Integer(resourceChngeKind));
    try {
      wsasServerManager.executeOperationOnServer(server, operationParameters);
      return true;
    } catch (Exception e) {
      log.error(e);
      return false;
    }
  }

  public boolean redeployServiceModule(String serverId, String webTempPath, String projectName) {
    IServer server = getServer(serverId);
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    CarbonServerManager wsasServerManager = this;
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_REDEPLOY_MODULE);
    operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
    try {
      wsasServerManager.executeOperationOnServer(server, operationParameters);
      return true;
    } catch (Exception e) {
      log.error(e);
      return false;
    }
  }

  public boolean unpublishServiceModule(String serverId, String webTempPath, String projectName) {
    IServer server = getServer(serverId);
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    CarbonServerManager wsasServerManager = this;
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_UNPUBLISH_MODULE);
    operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
    try {
      wsasServerManager.executeOperationOnServer(server, operationParameters);
      return true;
    } catch (Exception e) {
      log.error(e);
      return false;
    }
  }

  public static boolean waitForServerToChangeState(
      IServer server, Shell shell, int changeStateFrom, int changeStateTo, String msg) {
    ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(shell);
    CarbonServerStateChange serverStateChange =
        new CarbonServerStateChange(server, changeStateFrom, changeStateTo, 180000, msg);
    progressMonitorDialog.setBlockOnOpen(false);
    try {
      progressMonitorDialog.run(true, true, serverStateChange);
      return progressMonitorDialog.getReturnCode() != ProgressMonitorDialog.CANCEL;
    } catch (InvocationTargetException e) {
      log.error(e);
    } catch (InterruptedException e) {
      log.error(e);
    }
    return false;
  }

  public static boolean waitUntilTheServerStarts(IServer server, Shell shell) {
    return waitForServerToChangeState(
        server,
        shell,
        IServer.STATE_STOPPED,
        IServer.STATE_STARTED,
        "Starting WSAS Server " + server.getId() + "...");
  }

  public Map<IFolder, IProject> getPublishedPaths(String serverId) {
    return getPublishedPaths(getServer(serverId));
  }

  public static Map<IFolder, IProject> getPublishedPaths(IServer server) {
    if (server == null) return null;
    IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_GET_PUBLISHED_SERVICES);
    try {
      Object result = wsasServerManager.executeOperationOnServer(server, operationParameters);
      if (result instanceof Map) {
        return (Map<IFolder, IProject>) result;
      }
      return null;
    } catch (Exception e) {
      log.error(e);
      return null;
    }
  }

  public IProject[] getPublishedProjects(String serverId) {
    return null;
  }

  public IProject[] getPublishedProjectsFromAllServers() {
    return null;
  }

  public String getServerRuntimeId(String serverId) {
    return getServerOperationManager(serverId).getRuntimeId();
  }

  public boolean isRuntimeIdPresent(String runtimeId) {
    return getServerRuntimeIdPlugin().containsKey(runtimeId);
  }

  public String getServerTypeIdForRuntimeId(String runtimeId) {
    if (getServerRuntimeIdPlugin().containsKey(runtimeId))
      return getServerRuntimeIdPlugin().get(runtimeId);
    else return null;
  }

  public String[] getServerRelativeLibraryPaths(String serverTypeId) throws Exception {
    String[] result = null;
    ICarbonOperationManager serverOperationManager =
        getServerOperationManagerByServerType(serverTypeId);
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
    Object r = serverOperationManager.executeOperation(operationParameters);
    if (r instanceof String[]) {
      result = (String[]) r;
    }
    return result;
  }

  public String[] getServerCodegenLibraries(String serverId) throws Exception {

    IServer server = getServer(serverId);
    return getServerCodegenLibraries(server);
  }

  public static String[] getServerCodegenLibraries(IServer server) throws Exception {
    String[] result = null;
    if (server != null) {
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
      Object r =
          wsasServerManager.executeOperationOnServer(
              server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
      if (r instanceof String[]) {
        result = (String[]) r;
      }
    }
    return result;
  }

  public String[] getServerAxis2Libraries(String serverTypeId, String wsasHome) throws Exception {
    String[] result = null;
    ICarbonOperationManager serverOperationManager =
        getServerOperationManagerByServerType(serverTypeId);
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_GET_AXIS2_LIBRARIES);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, wsasHome);
    Object r = serverOperationManager.executeOperation(operationParameters);
    if (r instanceof String[]) {
      result = (String[]) r;
    }
    return result;
  }

  private void init() {
    createWorkspaceListener();
  }

  private void createWorkspaceListener() {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();

    IResourceChangeListener listener =
        new IResourceChangeListener() {
          public void resourceChanged(IResourceChangeEvent event) {
            IResourceDelta projectDelta;
            if (isServerAdded) {
              IResourceDelta resourceDelta = event.getDelta();
              for (IResourceDelta modifideResourceDelta : resourceDelta.getAffectedChildren()) {
                rootProject = (IProject) modifideResourceDelta.getResource();
                projectDelta = modifideResourceDelta;
                IResourceDeltaVisitor visitor =
                    new IResourceDeltaVisitor() {
                      public boolean visit(IResourceDelta delta) throws CoreException {
                        IResource resource = delta.getResource();
                        resourceChngeKind = delta.getKind();
                        if (resource.getType() == IResource.FILE
                            || resource.getType() == IResource.FOLDER) {
                          IServer[] serversForProject = getServersForProject(rootProject);
                          for (IServer server : serversForProject) {
                            if (!CARBON_SERVER_TYPE_REMOTE.equalsIgnoreCase(
                                server.getServerType().getId())) {
                              CarbonServerInformation serverInformation =
                                  getAppServerInformation().get(server);
                              if (!serverInformation.getChangedProjects().contains(rootProject)) {
                                serverInformation.getChangedProjects().add(rootProject);
                                hotUpdateWebApp(server.getId(), resource, rootProject.getName());
                              }
                            }
                          }
                        }
                        return true;
                      }
                    };
                try {
                  projectDelta.accept(visitor);
                } catch (CoreException e) {
                  log.error(" adding IResourceDeltaVisitor to projectDelta was failed " + e);
                }
              }
            }
          }
        };
    workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_BUILD);
  }

  public String[] getServerCodegenLibrariesFromRuntimeId(String runtimeId, String runtimePath)
      throws Exception {
    String serverTypeId = getServerTypeIdForRuntimeId(runtimeId);
    String[] result = null;
    HashMap<String, Object> operationParameters = new HashMap<String, Object>();
    operationParameters.put(
        ICarbonOperationManager.PARAMETER_TYPE,
        ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
    operationParameters.put(ICarbonOperationManager.PARAMETER_RUNTIME, runtimeId);
    operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, runtimePath);
    ICarbonOperationManager wsasOperationManager =
        getServerOperationManagerByServerType(serverTypeId);
    Object r =
        wsasOperationManager.executeOperation(
            operationParameters); // getWSDLConversionResultUrl(resourceFile);
    if (r instanceof String[]) {
      result = (String[]) r;
    }
    return result;
  }

  public static ICredentials getServerCredentials(IServer server) throws Exception {
    Map<String, String> result = null;
    if (server != null) {
      IServerManager esbServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVER_CREDENTIALS);
      Object r =
          esbServerManager.executeOperationOnServer(
              server, operationParameters); // getWSDLConversionResultUrl(resourceFile);
      if (r instanceof Map) {
        result = (Map<String, String>) r;
      }
    }
    Credentials credentials = null;
    if (result != null) {
      credentials = new Credentials(result.get("esb.username"), result.get("esb.password"));
    }
    return credentials;
  }

  public static URL getServerURL(IServer server) throws Exception {
    if (server != null) {
      IServerManager esbServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_SERVER_URL);
      Object serverURL = esbServerManager.executeOperationOnServer(server, operationParameters);
      if (serverURL instanceof URL) {
        String serverId = server.getServerType().getId();
        URL urlWithContextRoot = (URL) serverURL;
        if (!CARBON_SERVER_TYPE_REMOTE.equals(serverId)) {
          urlWithContextRoot =
              new URL(urlWithContextRoot, CarbonServerUtils.getWebContextRoot(server));
        }
        return urlWithContextRoot;
      }
    }
    return null;
  }

  public static String getServerAuthenticatedCookie(IServer server, String httpsPort)
      throws Exception {
    String result = null;
    if (server != null) {
      IServerManager esbServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE,
          ICarbonOperationManager.OPERATION_GET_SERVER_AUTHENTICATED_COOKIE);
      operationParameters.put(ICarbonOperationManager.PARAMETER_SERVER_PORT, httpsPort);
      Object r = esbServerManager.executeOperationOnServer(server, operationParameters);
      if (r instanceof String) {
        result = (String) r;
      }
    }
    return result;
  }

  public static String getServerAuthenticatedCookie(IServer server) throws Exception {
    String result = null;
    if (server != null) {
      ServerPort[] serverPorts = getInstance().getServerPorts(server);
      String httpsPort = "9443";
      for (ServerPort port : serverPorts) {
        if (port.getProtocol().equalsIgnoreCase("https")) {
          httpsPort = Integer.toString(port.getPort());
        }
      }
      result = getServerAuthenticatedCookie(server, httpsPort);
    }
    return result;
  }

  public static String getServerCarbonVersion(IServer server) {
    String result = null;
    if (server != null) {
      IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
      HashMap<String, Object> operationParameters = new HashMap<String, Object>();
      operationParameters.put(
          ICarbonOperationManager.PARAMETER_TYPE, ICarbonOperationManager.OPERATION_SERVER_VERSION);
      Object r = null;
      try {
        r = wsasServerManager.executeOperationOnServer(server, operationParameters);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } // getWSDLConversionResultUrl(resourceFile);
      result = (String) r;
    }
    return result;
  }
}
public class WSASRuntimeUtils {
  private static IDeveloperStudioLog log = Logger.getLog(WebServiceWSASCorePlugin.PLUGIN_ID);

  public static final int ZIP = 0, UNZIP = 1;
  protected static int mode = UNZIP;
  static ZipFile zipFile;
  protected static byte[] b;
  static SortedSet createdDirs;
  static String outputPath;

  public static String copyWSASWar(IProgressMonitor monitor, String wsasHome)
      throws FileNotFoundException, IOException {
    String tempWarFile = null;
    String tempWarLocation = null;
    String tempUnzipLocation = null;
    try {
      if (new File(WSASCoreUtils.tempWSASDirectory()).isDirectory()) {
        tempWarLocation =
            WSASCoreUtils.addAnotherNodeToPath(
                WSASCoreUtils.tempWSASDirectory(), WSASCoreUIMessages.DIR_TEMPWAR);
        File tempWarLocationFile = new File(tempWarLocation);
        if (tempWarLocationFile.exists()) {
          FileUtils.deleteDirectories(tempWarLocationFile);
        }
        tempWarLocationFile.mkdirs();
        tempWarFile =
            WSASCoreUtils.addAnotherNodeToPath(tempWarLocation, WSASCoreUIMessages.FILE_WSAS_WAR);
        new File(tempWarFile).createNewFile();
        Properties properties = new Properties();
        //			properties.load(new FileInputStream(WSASCoreUtils.tempWSASWebappFileLocation()));
        //				if (properties.containsKey(WSASCoreUIMessages.PROPERTY_KEY_PATH)){
        if (ServerModel.getWsasServerPath() != null) {
          String wsasWarFile =
              WSASCoreUtils.addAnotherNodeToPath(
                  (ServerModel.getWsasServerPath() != null)
                      ? ServerModel.getWsasServerPath()
                      : properties.getProperty(WSASCoreUIMessages.PROPERTY_KEY_PATH),
                  WSASCoreUIMessages.FILE_WSAS_WAR);
          FileChannel srcChannel = new FileInputStream(wsasWarFile).getChannel();
          FileChannel dstChannel = new FileOutputStream(tempWarFile).getChannel();
          // Copy file contents from source to destination
          dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
          // Close the channels
          srcChannel.close();
          dstChannel.close();

          // unzip this into another foulder
          tempUnzipLocation =
              FileUtils.addAnotherNodeToPath(tempWarLocation, WSASCoreUIMessages.DIR_UNZIP);
          File tempUnzipLocationFile = new File(tempUnzipLocation);
          if (!tempUnzipLocationFile.exists()) {
            tempUnzipLocationFile.mkdirs();
          }
          unzipWSASWar(tempWarFile, tempUnzipLocation);
        }

      } else {
        // Throws an error message
      }
    } catch (FileNotFoundException e) {
      throw e;
    } catch (IOException e) {
      throw e;
    }

    return tempUnzipLocation;
  }

  private static void unzipWSASWar(String fileName, String outputPath) {
    b = new byte[8092];
    setOutputPath(outputPath);
    if (fileName.endsWith(".war")) unZip(fileName);
    else throw new IllegalStateException("Wrong file type" + fileName);
  }

  /** For a given Zip file, process each entry. */
  public static void unZip(String fileName) {

    createdDirs = new TreeSet();
    try {
      zipFile = new ZipFile(fileName);
      Enumeration all = zipFile.entries();
      while (all.hasMoreElements()) {
        unzipFile((ZipEntry) all.nextElement());
      }
    } catch (IOException e) {
      log.error(e);
    }
  }

  protected static void unzipFile(ZipEntry e) throws IOException {

    boolean warnedMkDir = false;
    String zipName = e.getName();
    switch (mode) {
      case UNZIP:
        if (zipName.startsWith("/")) {
          if (!warnedMkDir) warnedMkDir = true;
          zipName = zipName.substring(1);
        }
        if (zipName.endsWith("/")) {
          return;
        }
        int ix = zipName.lastIndexOf('/');
        if (ix > 0) {
          String dirName = zipName.substring(0, ix);
          if (!createdDirs.contains(dirName)) {
            File d = new File(getOutputPath() + File.separator + dirName);
            if (!(d.exists() && d.isDirectory())) {
              if (!d.mkdirs()) {
                throw new IllegalStateException("Warning: unable to mkdir " + dirName);
              }
              createdDirs.add(dirName);
            }
          }
        }
        FileOutputStream os = new FileOutputStream(getOutputPath() + File.separator + zipName);
        InputStream is = zipFile.getInputStream(e);
        int n = 0;
        while ((n = is.read(b)) > 0) os.write(b, 0, n);
        is.close();
        os.close();
        break;
      default:
        throw new IllegalStateException("mode value (" + mode + ") bad");
    }
  }

  public static String getOutputPath() {
    return outputPath;
  }

  public static void setOutputPath(String outputPath) {
    WSASRuntimeUtils.outputPath = outputPath;
  }
}
public class ChangePermissionWizardPage2 extends WizardPage {
  private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

  private ChangePermissionWizardPage1 changePermissionWizPage1;
  public ArrayList<RoleData> selectedPermissions;
  private String[] permissionList = {"Read", "Write", "Delete", "Authorize"};
  private RegistryUserRole regUserRole;
  private RoleData roleData;
  public static final String READ = "Read";
  public static final String WRITE = "Write";
  public static final String DELETE = "Delete";
  public static final String AUTHORIZE = "Authorize";
  private ArrayList<RegistryResourceNode> selectedIemList;
  private ArrayList<Button> checkBoxes;

  Text textArea;
  Button check;
  List list;

  protected ChangePermissionWizardPage2(
      String pageName, RegistryUserRole regUsrRole, ChangePermissionWizardPage1 wizPage1) {
    super(pageName);
    setPageComplete(true);
    setDescription("Select permissions you want to grant");
    this.regUserRole = regUsrRole;
    this.changePermissionWizPage1 = wizPage1;
    setImageDescriptor(ImageUtils.getImageDescriptor(ImageUtils.ACTION_MODIFY_PERMISSION_ROLE));
  }

  public void createControl(Composite parent) {
    selectedPermissions = new ArrayList<RoleData>();
    GridData gd;
    Composite container = new Composite(parent, SWT.NULL);
    checkBoxes = new ArrayList<Button>();
    GridLayout layout = new GridLayout();
    container.setLayout(layout);
    layout.numColumns = 1;
    layout.verticalSpacing = 10;
    gd = new GridData(GridData.FILL_HORIZONTAL);
    try {
      loadData();
    } catch (RemoteException e) {
      log.error(e);
    } catch (Exception e) {
      log.error(e);
    }
    for (int i = 0; i < permissionList.length; i++) {
      if (roleData != null) {
        createCheckbox(permissionList[i], gd, container, i, roleData);
      }
    }

    gd = new GridData(GridData.FILL_HORIZONTAL);
    Label label = new Label(container, SWT.NULL);
    label.setText("Selected Resource paths");
    label.setLayoutData(gd);
    list = new List(container, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
    gd = new GridData(GridData.FILL_BOTH);
    list.setLayoutData(gd);
    selectedIemList = new ArrayList<RegistryResourceNode>();
    fillTextArea(selectedIemList);
    setControl(container);
  }

  private RoleData getRoleData(String roleName, String resourcePath) {
    return new RoleData(roleName, resourcePath);
  }

  public void loadData() throws RemoteException, Exception {
    ResourceAdmin rsAd =
        regUserRole
            .getRegistryUserRoleContent()
            .getRegistryUserManagerContainer()
            .getRegistryData()
            .getResourceAdmin();
    if (changePermissionWizPage1 != null) {
      ArrayList<RegistryResourceNode> list = changePermissionWizPage1.selectedItemList();
      for (int i = 0; i < list.size(); i++) {
        ArrayList<Role> resourceInfo =
            rsAd.getPermissionPerResource(list.get(i).getRegistryResourcePath());
        for (int j = 0; j < resourceInfo.size(); j++) {
          roleData =
              getRoleData(resourceInfo.get(j).getRole(), list.get(i).getRegistryResourcePath());
          ArrayList<String> permissionListPerRole = resourceInfo.get(j).getAssignedPermission();
          for (int k = 0; k < permissionListPerRole.size(); k++) {

            if (permissionListPerRole.get(k).equals("Read")) {
              roleData.setReadPerm(true);
            }
            if (permissionListPerRole.get(k).equals("Write")) {
              roleData.setWritePerm(true);
            }
            if (permissionListPerRole.get(k).equals("Delete")) {
              roleData.setDeletePerm(true);
            }
            if (permissionListPerRole.get(k).equals("Authorize")) {
              roleData.setAuthPerm(true);
            }
          }
        }
      }
    }
  }

  private void createCheckbox(
      String textString, GridData gd, Composite container, int type, RoleData roleData) {
    boolean value = false;
    String permission = "";

    check = new Button(container, SWT.CHECK);
    if (!checkBoxes.contains(check)) {
      checkBoxes.add(check);
    }
    if (type == 0) {
      permission = READ;
      value = roleData.isReadPerm();
    }
    if (type == 1) {
      permission = WRITE;
      value = roleData.isWritePerm();
    }
    if (type == 2) {
      permission = DELETE;
      value = roleData.isDeletePerm();
    }
    if (type == 3) {
      permission = AUTHORIZE;
      value = roleData.isAuthPerm();
    }

    check.setText(textString);
    check.setSelection(value);

    check.addSelectionListener(
        new SelectionListener() {

          public void widgetSelected(SelectionEvent event) {
            int readCount = 0;
            int writeCount = 0;
            int deleteCount = 0;
            int authCount = 0;

            String selectedRole = regUserRole.getUserRoleName();
            if (changePermissionWizPage1 != null) {
              ArrayList<RegistryResourceNode> list = changePermissionWizPage1.selectedItemList();
              if (!selectedPermissions.isEmpty()) {
                for (int c = 0; c < selectedPermissions.size(); c++) {
                  RoleData roleD = selectedPermissions.get(c);
                  if (roleD.isReadPerm()) {
                    readCount++;
                  }
                  if (roleD.isWritePerm()) {
                    writeCount++;
                  }
                  if (roleD.isDeletePerm()) {
                    deleteCount++;
                  }
                  if (roleD.isAuthPerm()) {
                    authCount++;
                  }
                }
              }

              String permission = ((Button) (event.widget)).getText();
              boolean g = ((Button) (event.widget)).getSelection();
              for (int i = 0; i < selectedPermissions.size(); i++) {
                RoleData roleData = selectedPermissions.get(i);

                if (g) {
                  if (permission.equals(READ)) {
                    roleData.setReadPerm(true);
                    readCount++;
                  } else if (permission.equals(WRITE)) {
                    roleData.setWritePerm(true);
                    writeCount++;
                  } else if (permission.equals(DELETE)) {
                    roleData.setDeletePerm(true);
                    deleteCount++;
                  } else {
                    roleData.setAuthPerm(true);
                    authCount++;
                  }
                } else {
                  if (permission.equals(READ)) {
                    roleData.setReadPerm(false);
                    readCount--;
                  } else if (permission.equals(WRITE)) {
                    roleData.setWritePerm(false);
                    writeCount--;
                  } else if (permission.equals(DELETE)) {
                    roleData.setDeletePerm(false);
                    deleteCount--;
                  } else {
                    roleData.setAuthPerm(false);
                    authCount--;
                  }
                }
                selectedPermissions.remove(i);
                selectedPermissions.add(i, roleData);
              }

              if (readCount != 0 && readCount != list.size()) {
                setGrayedCheckBox(event);
              } else if (readCount == list.size()) {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Read")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(true);
                  }
                }
              } else {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Read")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(false);
                  }
                }
              }

              if (writeCount != 0 && writeCount != list.size()) {
                setGrayedCheckBox(event);
              } else if (writeCount == list.size()) {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Write")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(true);
                  }
                }
              } else {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Write")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(false);
                  }
                }
              }

              if (deleteCount != 0 && deleteCount != list.size()) {
                setGrayedCheckBox(event);
              } else if (deleteCount == list.size()) {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Delete")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(true);
                  }
                }
              } else {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Delete")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(false);
                  }
                }
              }

              if (authCount != 0 && authCount != list.size()) {
                setGrayedCheckBox(event);
              } else if (authCount == list.size()) {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Authorize")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(true);
                  }
                }
              } else {
                for (int k = 0; k < checkBoxes.size(); k++) {
                  if (checkBoxes.get(k).getText().equals("Authorize")) {
                    checkBoxes.get(k).setGrayed(false);
                    checkBoxes.get(k).setSelection(false);
                  }
                }
              }
            }
          }

          public void widgetDefaultSelected(SelectionEvent arg0) {}
        });
  }

  public void setGrayedCheckBox(SelectionEvent event) {
    boolean g = ((Button) (event.widget)).getGrayed();
    boolean s = ((Button) (event.widget)).getSelection();
    ((Button) (event.widget)).setSelection(s ^ g);
    ((Button) (event.widget)).setGrayed(s && !g);
  }

  public boolean canFlipToNextPage() {
    selectedIemList = changePermissionWizPage1.selectedItemList();
    fillTextArea(selectedIemList);
    try {
      setAssignedPermissionsToRole();
    } catch (Exception e) {
      log.error(e);
    }
    return false;
  }

  public void setAssignedPermissionsToRole() throws Exception {
    int readCount = 0;
    int writeCount = 0;
    int deleteCount = 0;
    int authCount = 0;
    String selectedRole = regUserRole.getUserRoleName();
    ResourceAdmin rsAd =
        regUserRole
            .getRegistryUserRoleContent()
            .getRegistryUserManagerContainer()
            .getRegistryData()
            .getResourceAdmin();
    if (changePermissionWizPage1 != null) {
      ArrayList<RegistryResourceNode> list = changePermissionWizPage1.selectedItemList();
      for (int i = 0; i < list.size(); i++) {
        ArrayList<String> permissionAssigned =
            rsAd.getPermissionListPerResource(list.get(i).getRegistryResourcePath(), selectedRole);
        RoleData roleD = new RoleData(selectedRole, list.get(i).getRegistryResourcePath());
        for (int j = 0; j < permissionAssigned.size(); j++) {
          if (permissionAssigned.get(j).equals("Read")) {
            readCount++;
            roleD.setReadPerm(true);
          }

          if (permissionAssigned.get(j).equals("Write")) {
            writeCount++;
            roleD.setWritePerm(true);
          }

          if (permissionAssigned.get(j).equals("Delete")) {
            deleteCount++;
            roleD.setDeletePerm(true);
          }

          if (permissionAssigned.get(j).equals("Authorize")) {
            authCount++;
            roleD.setAuthPerm(true);
          }
        }
        if (selectedPermissions.isEmpty()) {
          selectedPermissions.add(roleD);
        } else {
          for (int j = 0; j < selectedPermissions.size(); j++) {
            if (selectedPermissions
                .get(j)
                .getResourcePath()
                .equals(list.get(i).getRegistryResourcePath())) {
              selectedPermissions.remove(j);
              selectedPermissions.add(j, roleD);
            } else {
              selectedPermissions.add(roleD);
            }
          }
        }
      }
      if (readCount == list.size()) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Read")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(true);
          }
        }
      } else if (readCount == 0) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Read")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(false);
          }
        }

      } else {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Read")) {
            checkBoxes.get(k).setGrayed(true);
            checkBoxes.get(k).setSelection(true);
          }
        }
      }

      if (writeCount == list.size()) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Write")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(true);
          }
        }
      } else if (writeCount == 0) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Write")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(false);
          }
        }
      } else {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Write")) {
            checkBoxes.get(k).setGrayed(true);
            checkBoxes.get(k).setSelection(true);
          }
        }
      }

      if (deleteCount == list.size()) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Delete")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(true);
          }
        }
      } else if (deleteCount == 0) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Delete")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(false);
          }
        }

      } else {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Delete")) {
            checkBoxes.get(k).setGrayed(true);
            checkBoxes.get(k).setSelection(true);
          }
        }
      }

      if (authCount == list.size()) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Authorize")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(true);
          }
        }
      } else if (authCount == 0) {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Authorize")) {
            checkBoxes.get(k).setGrayed(false);
            checkBoxes.get(k).setSelection(false);
          }
        }
      } else {
        for (int k = 0; k < checkBoxes.size(); k++) {
          if (checkBoxes.get(k).getText().equals("Authorize")) {
            checkBoxes.get(k).setGrayed(true);
            checkBoxes.get(k).setSelection(true);
          }
        }
      }
    }
  }

  public void fillTextArea(ArrayList<RegistryResourceNode> itemsList) {
    if (changePermissionWizPage1 != null) {
      if (!itemsList.isEmpty()) {
        list.removeAll();
        for (int i = 0; i < itemsList.size(); i++) {
          list.add(itemsList.get(i).getRegistryResourcePath());
        }
      }
    }
  }
}