import java.io.*;

public class FixJaxWsWsdlResource {

   private static final String GETRESOURCE = "DrConfigService.class.getResource(\".\");";
   private static final String RES_PART = "\".\"";

   private static final String REPLACE_STRING = "DrConfigService.class.getSimpleName() + \".class\"";

   /**
    * Replaces the "." in getResource with a class reference so the wsdl files
    * can be found relative to the DrConfigServiceClass.
    *
    * @param drConfigServiceFilePath
    */
   private static void fixResourceLocation(String drConfigServiceFilePath) {
      File svcFile = null;
      File destSvcFile = null;


      boolean resourceReset = false;
      try (BufferedReader svcClassReader = new BufferedReader(new FileReader(svcFile));
           BufferedWriter svcClassWriter = new BufferedWriter(new FileWriter(destSvcFile))) {
         svcFile = new File(drConfigServiceFilePath);
         if (!svcFile.exists()) {
            System.out.println("DrConfigService file not found : " + drConfigServiceFilePath);
            return;
         }

         String destSvcFilePath = drConfigServiceFilePath + ".tmp";
         destSvcFile = new File(destSvcFilePath);
         if (destSvcFile.exists() && !destSvcFile.delete()) {
            System.out.println("Unable to delete temporary file : " + destSvcFilePath);
            return;
         }
         if (destSvcFile.createNewFile() && destSvcFile.setReadable(true) && destSvcFile.setWritable(true)) {
            String line = null;
            do {
               line = svcClassReader.readLine();
               if (line != null) {
                  if (line.contains(GETRESOURCE)) {
                     // Replace "." with "DrConfigService.class.getSimpleName() + ".class"
                     line = line.replace(RES_PART, REPLACE_STRING);
                  }
                  svcClassWriter.write(line);
                  svcClassWriter.newLine();
               }
            } while (line != null);
            resourceReset = true;
         }
      } catch (IOException ioe) {
         System.out.println("Error reading DrConfigService file : " + drConfigServiceFilePath);
      } catch (Exception e) {
         System.out.println("Error reading DrConfigService file : " + drConfigServiceFilePath);
      } finally {
         if (resourceReset) {
          svcFile.delete();
          destSvcFile.renameTo(svcFile);
       }
      }
   }

   /**
    * @param args
    */
   public static void main(String[] args) {
      if (args == null || args.length == 0 || args.length != 1) {
         System.out.println("Usage: java FixJaxWsWsdlResource.class path/to/DrConfigService.java.\n   Fully Qualified Service class java file path required");
         return;
      }

      fixResourceLocation(args[0]);
   }

}
