private String getSuffixPath(String clientName) {
   if (CodeGenUtil.isEmptyString(clientName)) {
     return GEN_CLIENT_CONFIG_DIR + File.separatorChar + CodeGenConstants.DEFAULT_CLIENT_NAME;
   } else {
     return GEN_CLIENT_CONFIG_DIR + File.separatorChar + clientName;
   }
 }
  private InvocationOptionConfig defaultInvocationOptions(CodeGenContext codeGenCtx) {

    String prefDataBinding = "XML";
    InputOptions inputOptions = codeGenCtx.getInputOptions();

    InvocationOptionConfig defaultInvOptions = new InvocationOptionConfig();
    // if consumerId is set then it should be used else invocation Use
    if (!CodeGenUtil.isEmptyString(codeGenCtx.getInputOptions().getConsumerId()))
      defaultInvOptions.setConsumerId(codeGenCtx.getInputOptions().getConsumerId());
    else defaultInvOptions.setInvocationUseCase(codeGenCtx.getServiceAdminName() + "Client");

    PreferredTransportConfig prefTransportCfg = new PreferredTransportConfig();
    if (inputOptions.getServiceLocation() != null
        && inputOptions.getServiceLocation().startsWith("http")) {
      prefTransportCfg.setName(SOAConstants.TRANSPORT_HTTP_11);
    } else {
      prefTransportCfg.setName(SOAConstants.TRANSPORT_LOCAL);
    }

    // TransportOptionConfig transportOptCfg = new TransportOptionConfig();
    // transportOptCfg.setTransportName(CodeGenConstants.PREF_TRANSPORT_BINDING);
    // transportOptCfg.setNumRetries(Integer.valueOf(CodeGenConstants.NUM_OF_CONN_RETRIES));
    // prefTransportCfg.setOverrideOptions(transportOptCfg);

    defaultInvOptions.setPreferredTransport(prefTransportCfg);

    defaultInvOptions.setRequestDataBinding(prefDataBinding);
    defaultInvOptions.setResponseDataBinding(prefDataBinding);

    return defaultInvOptions;
  }
  private ClientConfig createClientConfig(CodeGenContext codeGenCtx) {

    InputOptions inputOptions = codeGenCtx.getInputOptions();

    ClientConfig clientConfig = new ClientConfig();
    clientConfig.setGroup(inputOptions.getClientCfgGroupName());
    // put serviceNametag in cc.xml only if pre 2.4 consumer
    if (codeGenCtx.getInputOptions().isServiceNameRequired())
      clientConfig.setServiceName(codeGenCtx.getServiceQName().toString());
    String svcInterfaceName =
        CodeGenUtil.toQualifiedClassName(codeGenCtx.getServiceInterfaceClassName());
    clientConfig.setServiceInterfaceClassName(svcInterfaceName);
    if (inputOptions.getSvcCodeGenDefType() == null) {
      clientConfig.setServiceLocation(inputOptions.getServiceLocation());
      clientConfig.setWsdlLocation(inputOptions.getWSDLLocation());
    } else {
      ServiceCodeGenDefType svcCodeGenDef = inputOptions.getSvcCodeGenDefType();
      clientConfig.setServiceLocation(svcCodeGenDef.getServiceInfo().getServiceLocation());
      clientConfig.setWsdlLocation(svcCodeGenDef.getServiceInfo().getWsdlLocation());
    }

    ClientGroupConfig clientGrpCfg = createClientGroupConfig(codeGenCtx);
    clientConfig.setClientInstanceConfig(clientGrpCfg);

    return clientConfig;
  }
  public static void generateClientConfigXml(
      ClientConfigList clientCfgList, String destLoc, String configFileName)
      throws CodeGenFailedException {

    Writer fileWriter = null;
    try {
      fileWriter = CodeGenUtil.getFileWriter(destLoc, configFileName);

      JavaXmlBinder javaXmlBinder = JavaXmlBindingFactory.getInstance();
      javaXmlBinder.generateClientConfigXml(clientCfgList, fileWriter);

    } catch (Exception ex) {
      throw new CodeGenFailedException("Failed to generate Client Config xml file", ex);
    } finally {
      CodeGenUtil.closeQuietly(fileWriter);
    }
  }
  public static void generateSecurityPolicyXml(
      ServiceSecurityConfig securityPolicyConfig, String destLoc, String configFileName)
      throws CodeGenFailedException {

    Writer fileWriter = null;
    try {
      fileWriter = CodeGenUtil.getFileWriter(destLoc, configFileName);

      JavaXmlBinder javaXmlBinder = JavaXmlBindingFactory.getInstance();
      javaXmlBinder.generateSecurityPolicyXml(securityPolicyConfig, fileWriter);

    } catch (Exception ex) {
      throw new CodeGenFailedException("Failed to generate Security Policy Config xml file", ex);
    } finally {
      CodeGenUtil.closeQuietly(fileWriter);
    }
  }
  public static String getQualifiedClassName(String javaFilePath, String srcLocation) {
    int pkgStartPos = javaFilePath.indexOf(srcLocation);
    String qualifiedJavaFile = null;
    if (pkgStartPos > -1) {
      String normalizedSrcLoc = CodeGenUtil.normalizePath(srcLocation);
      int startPos = pkgStartPos + normalizedSrcLoc.length();
      qualifiedJavaFile = javaFilePath.substring(startPos);
    } else {
      qualifiedJavaFile = javaFilePath;
    }

    return toQualifiedClassName(qualifiedJavaFile);
  }
  public static ServiceConfig parseServiceConfig(InputStream input) throws Exception {

    ServiceConfig serviceConfig = null;

    try {
      JavaXmlBinder javaXmlBinder = JavaXmlBindingFactory.getInstance();
      serviceConfig = (ServiceConfig) javaXmlBinder.unmarshal(input, ServiceConfig.class);
    } catch (Exception ex) {
      String errMsg = "Failed to parse service config xml : " + input;
      throw new Exception(errMsg, ex);
    } finally {
      CodeGenUtil.closeQuietly(
          input); // TODO: do not close here, let the calling method close its own inputstream.
    }

    return serviceConfig;
  }
  public static ClientConfigList parseClientConfig(InputStream input) throws Exception {

    ClientConfigList clientCfgList = null;

    try {
      JavaXmlBinder javaXmlBinder = JavaXmlBindingFactory.getInstance();
      clientCfgList = (ClientConfigList) javaXmlBinder.unmarshal(input, ClientConfigList.class);
    } catch (Exception ex) {
      String errMsg = "Failed to parse client config xml : " + input;
      throw new Exception(errMsg, ex);
    } finally {
      CodeGenUtil.closeQuietly(
          input); // TODO: do not close here, let the calling method close its own inputstream.
    }

    return clientCfgList;
  }
  private void generateClientConfigXml(CodeGenContext codeGenCtx, ClientConfigList clientCfgList)
      throws CodeGenFailedException {

    Writer fileWriter = null;
    try {
      if (CodeGenUtil.isEmptyString(codeGenCtx.getClientName()))
        codeGenCtx.getInputOptions().setClientName(codeGenCtx.getServiceAdminName());
      String destFolderPath =
          CodeGenUtil.genDestFolderPath(
              codeGenCtx.getMetaSrcDestLocation(), getSuffixPath(codeGenCtx.getClientName()));
      if (!CodeGenUtil.isEmptyString(codeGenCtx.getInputOptions().getEnvironment())) {
        destFolderPath =
            destFolderPath
                + codeGenCtx.getInputOptions().getEnvironment()
                + File.separator
                + codeGenCtx.getServiceAdminName()
                + File.separator;
        destFolderPath = CodeGenUtil.toOSFilePath(destFolderPath);
      }

      String contents = getUpdatedClientConfigTemplate(codeGenCtx, clientCfgList);

      fileWriter = CodeGenUtil.getFileWriter(destFolderPath, CLIENT_CONFIG_FILE_NAME);
      fileWriter.write(contents);

      getLogger()
          .log(
              Level.INFO,
              "Successfully generated " + CLIENT_CONFIG_FILE_NAME + " under " + destFolderPath);

    } catch (Exception ex) {
      getLogger().log(Level.SEVERE, "Error " + ex.toString());
      throw new CodeGenFailedException("Failed to generate Client Config xml file", ex);
    } finally {
      CodeGenUtil.flushAndCloseQuietly(fileWriter);
    }
  }
  @Ignore
  @Test
  public void testSequenceNumberConsistency() throws Exception {
    File destDir = testingdir.getDir();
    File bin = new File(destDir.getAbsolutePath() + "/bin/");

    System.out.println(bin.getAbsoluteFile());
    File gensrc = new File(destDir, "gen-src");

    URL[] urls = {
      new URL("file:/" + destDir.getAbsolutePath() + "/bin/"),
      destDir.toURI().toURL(),
      gensrc.toURI().toURL()
    };
    URLClassLoader loader =
        new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
    Thread.currentThread().setContextClassLoader(loader);

    File wsdlpath = getProtobufRelatedInput("TestWsdlXsdTypes.wsdl");

    File file =
        new File(
            destDir.getAbsolutePath()
                + "/gen-meta-src/META-INF/soa/services/proto/CalculatorService/CalculatorService.proto");

    CodeGenUtil.deleteContentsOfDir(new File(file.getParent()));
    generateJaxbClasses(wsdlpath.getAbsolutePath(), destDir.getAbsolutePath(), bin);

    ProtoFileParser parser = ProtoFileParser.newInstance(file);
    List<Message> msg = parser.parse();

    List<String> listofMessageName = new ArrayList<String>();
    Map<String, List<String>> msgMap2 = null;
    for (int i = 0; i < 5; i++) {

      parser = ProtoFileParser.newInstance(file);
      msg = parser.parse();

      Map<String, List<String>> msgMap1 = getMessageInfo(msg);
      CodeGenUtil.deleteContentsOfDir(new File(file.getParent()));
      generateJaxbClasses(wsdlpath.getAbsolutePath(), destDir.getAbsolutePath(), bin);

      ProtoFileParser parser1 = ProtoFileParser.newInstance(file);
      List<Message> msg2 = parser1.parse();

      msgMap2 = getMessageInfo(msg);

      for (Message m1 : msg2) {
        listofMessageName.add(m1.getMessageName());
        List<String> fieldsInfo1 = msgMap1.get(m1.getMessageName());
        List<String> fieldsInfo2 = msgMap2.get(m1.getMessageName());

        Assert.assertTrue(fieldsInfo1.containsAll(fieldsInfo2));
      }
      // check pmd info is consistent:
      List<String> list1 = FileUtil.readFileAsLines(file);
      List<String> onlyPMD = new ArrayList<String>();
      for (String s : list1) {
        if (s.trim().startsWith("//PMD")) {
          onlyPMD.add(s);
        }
      }
      List<PMDInfo> list = parser.parsePMDData(onlyPMD);

      Map<String, List<String>> msgMap3 = new HashMap<String, List<String>>();
      for (String msgName : listofMessageName) {
        List<String> pmd = new ArrayList<String>();
        for (PMDInfo info : list) {
          if (info.getMessageName().trim().equals(msgName.trim())) {

            pmd.add(info.getFieldName() + info.getSequenceNumber());
          }
        }
        msgMap3.put(msgName, pmd);
      }

      for (String msgName : listofMessageName) {
        List<String> fieldsInfo2 = msgMap2.get(msgName);
        List<String> fieldsInfo3 = msgMap3.get(msgName);
        Assert.assertTrue(fieldsInfo2.containsAll(fieldsInfo3));
      }
    }
  }
  public String getFilePath(String serviceAdminName, String interfaceName) {

    return CodeGenUtil.toOSFilePath(getSuffixPath(serviceAdminName)) + CLIENT_CONFIG_FILE_NAME;
  }
  private String getUpdatedClientConfigTemplate(
      CodeGenContext codeGenCtx, ClientConfigList clientCfgList) throws CodeGenFailedException {
    try {
      if (clientCfgList == null || clientCfgList.getClientConfig().size() == 0) {
        throw new CodeGenFailedException("The content of 'ClientConfigList' is empty.");
      }

      String contents = CodeGenUtil.getTemplateContent(CLIENT_CONFIG_TEMPLATE);
      ClientConfig clientConfig = clientCfgList.getClientConfig().get(0);

      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents, CONFIG_GROUP_NAME, clientConfig.getGroup(), CONFIG_GROUP_NAME_ATTR);

      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents,
              CONFIG_SERVICE_NAME,
              clientConfig.getServiceName(),
              CONFIG_SERVICE_NAME_ATTR);
      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents,
              SERVICE_INT_NAME,
              clientConfig.getServiceInterfaceClassName(),
              SERVICE_INT_NAME_NODE);
      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents, WSDL_LOCATION, clientConfig.getWsdlLocation(), WSDL_LOCATION_NODE);
      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents, SERVICE_LOCATION, clientConfig.getServiceLocation(), SERVICE_LOCATION_NODE);

      ClientGroupConfig clientInstanceConfig = clientConfig.getClientInstanceConfig();
      InvocationOptionConfig invocationOptions = null;
      PreferredTransportConfig preferredTransport = null;

      if (clientInstanceConfig != null) {
        invocationOptions = clientConfig.getClientInstanceConfig().getInvocationOptions();
      }
      if (invocationOptions != null) {
        preferredTransport = invocationOptions.getPreferredTransport();

        contents =
            CodeGenConfigUtil.replaceTemplate(
                contents,
                REQ_DATA_BINDING,
                invocationOptions.getRequestDataBinding(),
                REQ_DATA_BINDING_NODE);
        contents =
            CodeGenConfigUtil.replaceTemplate(
                contents,
                RESP_DATA_BINDING,
                invocationOptions.getResponseDataBinding(),
                RESP_DATA_BINDING_NODE);
        contents =
            CodeGenConfigUtil.replaceTemplate(
                contents, CONSUMER_ID, invocationOptions.getConsumerId(), CONSUMER_ID_NODE);
        contents =
            CodeGenConfigUtil.replaceTemplate(
                contents,
                INVOCATION_USE_CASE,
                invocationOptions.getInvocationUseCase(),
                INVOCATION_USE_CASE_NODE);
      }

      String transportName = null;
      if (preferredTransport != null) {
        transportName = preferredTransport.getName();
      }
      contents =
          CodeGenConfigUtil.replaceTemplate(
              contents, PREFERRED_TRANSPORT_NAME, transportName, PREFERRED_TRANSPORT_NAME_ATTR);
      return contents;
    } catch (Throwable e) {
      throw new CodeGenFailedException(
          "Failed in retriveing the client config template "
              + CLIENT_CONFIG_TEMPLATE
              + e.getMessage(),
          e);
    }
  }