/**
   * Creates a new Server object.
   *
   * @param sqlDriver JDBC driver
   * @param dbURL JDBC connection url
   * @param dbLogin database login
   * @param dbPasswd database password
   */
  private Server(ServerConfig config) {
    Server.instance = this;
    this.connections = new ArrayList();
    this.services = new ArrayList();
    this.port = config.getPort();
    this.socket = null;
    this.dbLayer = null;

    try {
      dbLayer = DatabaseAbstractionLayer.createLayer(config);
      Logging.getLogger().finer("dbLayer   : " + dbLayer);

      this.store = new Store(config);
    } catch (Exception ex) {
      Logging.getLogger().severe("#Err > Unable to connect to the database : " + ex.getMessage());
      ex.printStackTrace();
      System.exit(1);
    }

    try {
      this.serverIp = InetAddress.getLocalHost().getHostAddress();
      this.socket = new ServerSocket(this.port);
    } catch (IOException e) {
      Logging.getLogger().severe("#Err > Unable to listen on the port " + port + ".");
      e.printStackTrace();
      System.exit(1);
    }

    loadInternalServices();
  }
Exemple #2
0
  void test(String[] opts, String className) throws Exception {
    count++;
    System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className);
    Path testSrcDir = Paths.get(System.getProperty("test.src"));
    Path testClassesDir = Paths.get(System.getProperty("test.classes"));
    Path classes = Paths.get("classes." + count);
    classes.createDirectory();

    Context ctx = new Context();
    PathFileManager fm = new JavacPathFileManager(ctx, true, null);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> options = new ArrayList<String>();
    options.addAll(Arrays.asList(opts));
    options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString()));
    Iterable<? extends JavaFileObject> compilationUnits =
        fm.getJavaFileObjects(testSrcDir.resolve(className + ".java"));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    JavaCompiler.CompilationTask t =
        compiler.getTask(out, fm, null, options, null, compilationUnits);
    boolean ok = t.call();
    System.err.println(sw.toString());
    if (!ok) {
      throw new Exception("compilation failed");
    }

    File expect = new File("classes." + count + "/" + className + ".class");
    if (!expect.exists()) throw new Exception("expected file not found: " + expect);
    long expectedSize = new File(testClassesDir.toString(), className + ".class").length();
    long actualSize = expect.length();
    if (expectedSize != actualSize)
      throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize);
  }
Exemple #3
0
  @Override
  public boolean loadLibrary(String libname, boolean ignoreError, ClassLoader cl) {
    try {
      for (Entry<String, String> nativeEntry : platformNativeIndex.entrySet()) {
        if (nativeEntry.getKey().contains(libname)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Loading mapped entry: [{}] [{}] [{}]",
                libname,
                nativeEntry.getKey(),
                nativeEntry.getValue());
          }
          File nativeLibCopy =
              extractJarEntry(
                  nativeEntry.getValue(),
                  nativeEntry.getKey(),
                  System.getProperty(JAVA_TMP_DIR),
                  String.format("%s.jni", libname));
          System.load(nativeLibCopy.getAbsolutePath());
          return true;
        }
      }
    } catch (Exception e) {
      log.error("Unable to load native library [{}] - {}", libname, e);
    }

    if (log.isDebugEnabled()) {
      log.debug("No mapped library match for [{}]", libname);
    }
    return false;
  }
  /**
   * Main Method
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    // init logging
    try {
      Logging.init("lucane.log", "ALL");
    } catch (IOException ioe) {
      System.err.println("Unable to init logging, exiting.");
      System.exit(1);
    }

    Server server = null;
    ServerConfig config = null;

    try {
      config = new ServerConfig(CONFIG_FILE);
    } catch (Exception e) {
      Logging.getLogger().severe("Unable to read or parse the config file.");
      e.printStackTrace();
      System.exit(1);
    }

    // Server creation
    server = new Server(config);
    server.generateKeys();
    Logging.getLogger().info("Server is ready.");
    server.run();
  }
Exemple #5
0
 /** Creates a new JAR file. */
 void create(OutputStream out, Manifest manifest) throws IOException {
   ZipOutputStream zos = new JarOutputStream(out);
   if (flag0) {
     zos.setMethod(ZipOutputStream.STORED);
   }
   if (manifest != null) {
     if (vflag) {
       output(getMsg("out.added.manifest"));
     }
     ZipEntry e = new ZipEntry(MANIFEST_DIR);
     e.setTime(System.currentTimeMillis());
     e.setSize(0);
     e.setCrc(0);
     zos.putNextEntry(e);
     e = new ZipEntry(MANIFEST_NAME);
     e.setTime(System.currentTimeMillis());
     if (flag0) {
       crc32Manifest(e, manifest);
     }
     zos.putNextEntry(e);
     manifest.write(zos);
     zos.closeEntry();
   }
   for (File file : entries) {
     addFile(zos, file);
   }
   zos.close();
 }
Exemple #6
0
 private void addCreatedBy(Manifest m) {
   Attributes global = m.getMainAttributes();
   if (global.getValue(new Attributes.Name("Created-By")) == null) {
     String javaVendor = System.getProperty("java.vendor");
     String jdkVersion = System.getProperty("java.version");
     global.put(new Attributes.Name("Created-By"), jdkVersion + " (" + javaVendor + ")");
   }
 }
Exemple #7
0
  // -creatediff -applydiff -debug -output file
  public static void main(String[] args) throws IOException {
    boolean diff = true;
    boolean minimal = true;
    String outputFile = "out.jardiff";

    for (int counter = 0; counter < args.length; counter++) {
      // for backward compatibilty with 1.0.1/1.0
      if (args[counter].equals("-nonminimal") || args[counter].equals("-n")) {
        minimal = false;
      } else if (args[counter].equals("-creatediff") || args[counter].equals("-c")) {
        diff = true;
      } else if (args[counter].equals("-applydiff") || args[counter].equals("-a")) {
        diff = false;
      } else if (args[counter].equals("-debug") || args[counter].equals("-d")) {
        _debug = true;
      } else if (args[counter].equals("-output") || args[counter].equals("-o")) {
        if (++counter < args.length) {
          outputFile = args[counter];
        }
      } else if (args[counter].equals("-applydiff") || args[counter].equals("-a")) {
        diff = false;
      } else {
        if ((counter + 2) != args.length) {
          showHelp();
          System.exit(0);
        }
        if (diff) {
          try {
            OutputStream os = new FileOutputStream(outputFile);

            JarDiff.createPatch(args[counter], args[counter + 1], os, minimal);
            os.close();
          } catch (IOException ioe) {
            try {
              System.out.println(getResources().getString("jardiff.error.create") + " " + ioe);
            } catch (MissingResourceException mre) {
            }
          }
        } else {
          try {
            OutputStream os = new FileOutputStream(outputFile);

            new JarDiffPatcher().applyPatch(null, args[counter], args[counter + 1], os);
            os.close();
          } catch (IOException ioe) {
            try {
              System.out.println(getResources().getString("jardiff.error.apply") + " " + ioe);
            } catch (MissingResourceException mre) {
            }
          }
        }
        System.exit(0);
      }
    }
    showHelp();
  }
Exemple #8
0
 public static void main(String[] args) throws Exception {
   if (args.length != 2) {
     System.err.println("Usage: java -jar jar2jad [jarfile] [jadfile]");
     System.exit(1);
   }
   if (!extractJarDir(args[0], args[1])) {
     System.out.println("Error: Could not find manifest in Jar.");
     System.exit(1);
   } else {
     System.out.println("Jad created.");
   }
 }
Exemple #9
0
 public static void ensureJavaVersion() {
   Class<?> nio;
   try {
     nio = Util.class.getClassLoader().loadClass("java.nio.charset.StandardCharsets");
     if (nio == null) {
       System.out.println(
           "Could not load NIO!  Are we running on Java 7 or greater?  Sorry, exiting...");
       System.exit(1);
     }
   } catch (java.lang.ClassNotFoundException e) {
     System.out.println(
         "Could not load NIO!  Are we running on Java 7 or greater?  Sorry, exiting...");
     System.exit(1);
   }
 }
Exemple #10
0
  private void updateLinuxServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      Properties props = new Properties();
      String ctpHome = dir.getAbsolutePath();
      cp.appendln(Color.black, "...CTP_HOME: " + ctpHome);
      ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\");
      props.put("CTP_HOME", ctpHome);
      File javaHome = new File(System.getProperty("java.home"));
      String javaBin = (new File(javaHome, "bin")).getAbsolutePath();
      cp.appendln(Color.black, "...JAVA_BIN: " + javaBin);
      javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\");
      props.put("JAVA_BIN", javaBin);

      File linux = new File(dir, "linux");
      File install = new File(linux, "ctpService-ubuntu.sh");
      cp.appendln(Color.black, "Linux service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      bat = replace(bat, props); // do the substitutions
      bat = bat.replace("\r", "");
      setFileText(install, bat);

      // If this is an ISN installation, put the script in the correct place.
      String osName = System.getProperty("os.name").toLowerCase();
      if (programName.equals("ISN") && !osName.contains("windows")) {
        install = new File(linux, "ctpService-red.sh");
        cp.appendln(Color.black, "ISN service installer:");
        cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
        bat = getFileText(install);
        bat = replace(bat, props); // do the substitutions
        bat = bat.replace("\r", "");
        File initDir = new File("/etc/init.d");
        File initFile = new File(initDir, "ctpService");
        if (initDir.exists()) {
          setOwnership(initDir, "edge", "edge");
          setFileText(initFile, bat);
          initFile.setReadable(true, false); // everybody can read //Java 1.6
          initFile.setWritable(true); // only the owner can write //Java 1.6
          initFile.setExecutable(true, false); // everybody can execute //Java 1.6
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the Linux service ctpService.sh file");
    }
  }
  private static void setupJurisdictionPolicies() throws Exception {
    String javaHomeDir = System.getProperty("java.home");
    String sep = File.separator;
    String pathToPolicyJar = javaHomeDir + sep + "lib" + sep + "security" + sep;

    File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
    File importJar = new File(pathToPolicyJar, "local_policy.jar");
    URL jceCipherURL = ClassLoader.getSystemResource("javax/crypto/Cipher.class");

    if ((jceCipherURL == null) || !exportJar.exists() || !importJar.exists()) {
      throw new SecurityException("Cannot locate policy or framework files!");
    }

    // Read jurisdiction policies.
    CryptoPermissions defaultExport = new CryptoPermissions();
    CryptoPermissions exemptExport = new CryptoPermissions();
    loadPolicies(exportJar, defaultExport, exemptExport);

    CryptoPermissions defaultImport = new CryptoPermissions();
    CryptoPermissions exemptImport = new CryptoPermissions();
    loadPolicies(importJar, defaultImport, exemptImport);

    // Merge the export and import policies for default applications.
    if (defaultExport.isEmpty() || defaultImport.isEmpty()) {
      throw new SecurityException("Missing mandatory jurisdiction " + "policy files");
    }
    defaultPolicy = defaultExport.getMinimum(defaultImport);

    // Merge the export and import policies for exempt applications.
    if (exemptExport.isEmpty()) {
      exemptPolicy = exemptImport.isEmpty() ? null : exemptImport;
    } else {
      exemptPolicy = exemptExport.getMinimum(exemptImport);
    }
  }
Exemple #12
0
  protected InputStream getManifest() throws IOException {
    String m =
        "Manifest-Version: 1.0\n"
            + "Created-By: "
            + System.getProperty("java.runtime.version")
            + " ("
            + System.getProperty("java.vm.specification.vendor")
            + ")\n"
            + "Built-By: "
            + System.getProperty("user.name")
            + " (WSC-"
            + VersionInfo.VERSION
            + ")\n";

    return new ByteArrayInputStream(m.getBytes("UTF-8"));
  }
  private JarFile getCachedJarFile(URL url) {
    JarFile result = (JarFile) fileCache.get(url);

    /* if the JAR file is cached, the permission will always be there */
    if (result != null) {
      Permission perm = getPermission(result);
      if (perm != null) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
          try {
            sm.checkPermission(perm);
          } catch (SecurityException se) {
            // fallback to checkRead/checkConnect for pre 1.2
            // security managers
            if ((perm instanceof java.io.FilePermission)
                && perm.getActions().indexOf("read") != -1) {
              sm.checkRead(perm.getName());
            } else if ((perm instanceof java.net.SocketPermission)
                && perm.getActions().indexOf("connect") != -1) {
              sm.checkConnect(url.getHost(), url.getPort());
            } else {
              throw se;
            }
          }
        }
      }
    }
    return result;
  }
Exemple #14
0
  public void run() throws Exception {
    File rtDir = new File("rt.dir");
    File javaHome = new File(System.getProperty("java.home"));
    if (javaHome.getName().equals("jre")) javaHome = javaHome.getParentFile();
    File rtJar = new File(new File(new File(javaHome, "jre"), "lib"), "rt.jar");
    expand(rtJar, rtDir);

    String[] rtDir_opts = {
      "-bootclasspath", rtDir.toString(),
      "-classpath", "",
      "-sourcepath", "",
      "-extdirs", ""
    };
    test(rtDir_opts, "HelloPathWorld");

    if (isJarFileSystemAvailable()) {
      String[] rtJar_opts = {
        "-bootclasspath", rtJar.toString(),
        "-classpath", "",
        "-sourcepath", "",
        "-extdirs", ""
      };
      test(rtJar_opts, "HelloPathWorld");

      String[] default_opts = {};
      test(default_opts, "HelloPathWorld");

      // finally, a non-trivial program
      test(default_opts, "CompileTest");
    } else System.err.println("jar file system not available: test skipped");
  }
Exemple #15
0
  public GLBootstrap() throws Exception {

    System.setProperty("jogamp.gluegen.UseTempJarCache", "false");

    log.info(
        "Initializing native JOGL jar dependencies for platform [{}]. Temp jar cache disabled.",
        PlatformPropsImpl.os_and_arch);

    String nativeJarName = String.format("%s-%s", NATIVES, PlatformPropsImpl.os_and_arch);
    String[] classpathEntries =
        System.getProperty(JAVA_CLASSPATH).split(System.getProperty(JAVA_SEPARATOR));

    for (String jarPath : classpathEntries) {

      if (jarPath.contains(nativeJarName)) {

        if (log.isDebugEnabled()) {
          log.debug("Applicable platform jar: [{}]", jarPath);
        }

        JarFile jf = new JarFile(jarPath);

        try {
          Enumeration<JarEntry> jarEntries = jf.entries();

          while (jarEntries.hasMoreElements()) {

            JarEntry je = jarEntries.nextElement();

            if (!je.isDirectory() && !je.getName().contains(JAVA_META_INF)) {
              if (log.isDebugEnabled()) {
                log.debug("Mapping jar entry [{}] -> [{}]", je.getName(), jarPath);
              }
              if (log.isDebugEnabled() && platformNativeIndex.containsKey(je.getName())) {
                log.debug("Duplicate jar entry: [{}]", je.getName());
                log.debug("Mapped at: [{}]", platformNativeIndex.get(je.getName()));
                log.debug("Also at: [{}]", jarPath);
              }
              platformNativeIndex.put(je.getName(), jarPath);
            }
          }
        } finally {
          closeJar(jf);
        }
      }
    }
  }
Exemple #16
0
  public static void premain(String args, Instrumentation inst) throws Exception {
    try {
      String[] agentArgs;
      if (args == null) agentArgs = new String[] {""};
      else agentArgs = args.split(",");
      if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0];
      BaseClassTransformer rct = null;
      rct = new BaseClassTransformer();
      if (agentArgs[0].equals("instrumenting")) {
        initVMClasses = new HashSet<String>();
        for (Class<?> c : inst.getAllLoadedClasses()) {
          ((Set<String>) initVMClasses).add(c.getName());
        }
      }
      if (!agentArgs[0].equals("instrumenting")) {

        inst.addTransformer(rct);
        Tracer.setLocals(new CounterThreadLocal());
        Tracer.overrideAll(true);
        for (Class<?> c : inst.getAllLoadedClasses()) {
          try {
            if (c.isInterface()) continue;
            if (c.isArray()) continue;
            byte[] bytes = rct.getBytes(c.getName());
            if (bytes == null) {
              continue;
            }
            inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)});
          } catch (Throwable e) {
            synchronized (System.err) {
              System.err.println("" + c + " failed...");
              e.printStackTrace();
            }
          }
        }
        Runtime.getRuntime()
            .addShutdownHook(
                new Thread() {
                  public void run() {
                    Tracer.mark();
                    try {
                      PrintStream ps = new PrintStream("bailout.txt");
                      ps.println("Bailouts: " + Tracer.getBailoutCount());
                      ps.close();
                    } catch (Exception e) {
                    }
                    Tracer.unmark();
                  }
                });
        if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  protected static Object[] extractMockArguments(Object[] args) {
    int i = 7;

    if (args.length > i) {
      Object[] mockArgs = new Object[args.length - i];
      System.arraycopy(args, i, mockArgs, 0, mockArgs.length);
      return mockArgs;
    }

    return EMPTY_ARGS;
  }
Exemple #18
0
 private void addIndex(JarIndex index, ZipOutputStream zos) throws IOException {
   ZipEntry e = new ZipEntry(INDEX_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     CRC32OutputStream os = new CRC32OutputStream();
     index.write(os);
     os.updateEntry(e);
   }
   zos.putNextEntry(e);
   index.write(zos);
   zos.closeEntry();
 }
 public String getClasspath() {
   final StringBuilder sb = new StringBuilder();
   boolean firstPass = true;
   final Enumeration<File> componentEnum = this.pathComponents.elements();
   while (componentEnum.hasMoreElements()) {
     if (!firstPass) {
       sb.append(System.getProperty("path.separator"));
     } else {
       firstPass = false;
     }
     sb.append(componentEnum.nextElement().getAbsolutePath());
   }
   return sb.toString();
 }
  /** Generates server's keys for signature */
  public void generateKeys() {
    Logging.getLogger().info("Generating keypair");

    try {
      String[] pair = KeyGenerator.generateKeyPair();
      myConnectInfo =
          new ConnectInfo("server", this.serverIp, this.serverIp, this.port, pair[1], "Server");
      this.connections.add(myConnectInfo);
      this.signer = new Signer(pair[0]);
    } catch (SignatureException e) {
      Logging.getLogger().severe("Unable to generate keypair : " + e);
      System.exit(1);
    }
  }
Exemple #21
0
  public static void unzipInteralZip(
      ClassLoader classLoader, String resourcePath, File libDir, boolean debug) {
    if (debug) System.out.println("Extracting " + resourcePath);
    libDir.mkdir();
    URL resource = classLoader.getResource(resourcePath);
    if (resource == null) {
      System.err.println("Could not find the " + resourcePath + " on classpath!");
      System.exit(1);
    }
    class PrintDot extends TimerTask {
      public void run() {
        System.out.print(".");
      }
    }
    Timer timer = new Timer();
    PrintDot task = new PrintDot();
    timer.schedule(task, 0, 2000);

    try {

      BufferedInputStream bis = new BufferedInputStream(resource.openStream());
      JarInputStream jis = new JarInputStream(bis);
      JarEntry je = null;
      while ((je = jis.getNextJarEntry()) != null) {
        java.io.File f =
            new java.io.File(libDir.toString() + java.io.File.separator + je.getName());
        if (je.isDirectory()) {
          f.mkdir();
          continue;
        }
        File parentDir = new File(f.getParent());
        if (!parentDir.exists()) {
          parentDir.mkdir();
        }
        FileOutputStream fileOutStream = new FileOutputStream(f);
        writeStreamTo(jis, fileOutStream, 8 * KB);
        if (f.getPath().endsWith("pack.gz")) {
          unpack(f);
          fileOutStream.close();
          f.delete();
        }
      }

    } catch (Exception exc) {
      task.cancel();
      exc.printStackTrace();
    }
    task.cancel();
  }
Exemple #22
0
  public AppFrame() {
    super();
    GlobalData.oFrame = this;
    this.setSize(this.width, this.height);
    this.toolkit = Toolkit.getDefaultToolkit();

    Dimension w = toolkit.getScreenSize();
    int fx = (int) w.getWidth();
    int fy = (int) w.getHeight();

    int wx = (fx - this.width) / 2;
    int wy = (fy - this.getHeight()) / 2;

    setLocation(wx, wy);

    this.tracker = new MediaTracker(this);
    String sHost = "";
    try {

      localAddr = InetAddress.getLocalHost();
      if (localAddr.isLoopbackAddress()) {
        localAddr = LinuxInetAddress.getLocalHost();
      }
      sHost = localAddr.getHostAddress();
    } catch (UnknownHostException ex) {
      sHost = "你的IP地址错误";
    }
    //
    this.textLines[0] = "服务器正在运行.";
    this.textLines[1] = "";
    this.textLines[2] = "你的IP地址: " + sHost;
    this.textLines[3] = "";
    this.textLines[4] = "请打开你的手机客户端";
    this.textLines[5] = "";
    this.textLines[6] = "输入屏幕上显示的IP地址.";
    //
    try {
      URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation();
      String sBase = fileURL.toString();
      if ("jar".equals(sBase.substring(sBase.length() - 3, sBase.length()))) {
        jar = new JarFile(new File(fileURL.toURI()));

      } else {
        basePath = System.getProperty("user.dir") + "\\res\\";
      }
    } catch (Exception ex) {
      this.textLines[1] = "exception: " + ex.toString();
    }
  }
Exemple #23
0
 private void fixRSNAROOT(Element server) {
   if (programName.equals("ISN")) {
     Element ssl = getFirstNamedChild(server, "SSL");
     if (ssl != null) {
       if (System.getProperty("os.name").contains("Windows")) {
         ssl.setAttribute(
             "keystore", ssl.getAttribute("keystore").replace("RSNA_HOME", "RSNA_ROOT"));
         ssl.setAttribute(
             "truststore", ssl.getAttribute("truststore").replace("RSNA_HOME", "RSNA_ROOT"));
       } else {
         ssl.setAttribute("keystore", "${RSNA_ROOT}/conf/keystore.jks");
         ssl.setAttribute("truststore", "${RSNA_ROOT}/conf/truststore.jks");
       }
     }
   }
 }
  /** Loads internal services */
  private void loadInternalServices() {
    try {
      Iterator services;
      String servicename;
      String baseURL = System.getProperty("user.dir") + "/" + APPLICATIONS_DIRECTORY;

      LucaneClassLoader loader = LucaneClassLoader.getInstance();
      services = store.getServiceStore().getAllServices();

      while (services.hasNext()) {
        ServiceConcept service = (ServiceConcept) services.next();
        servicename = service.getName();
        try {
          loader.addUrl(new URL("jar:file:///" + baseURL + servicename + ".jar!/"));
          String className =
              (new JarFile(baseURL + servicename + ".jar"))
                  .getManifest()
                  .getMainAttributes()
                  .getValue("Service-Class");

          if (className == null) continue;

          Service serv = (Service) Class.forName(className, true, loader).newInstance();
          this.services.add(serv);
          serv.init(this);

          if (!service.isInstalled()) {
            serv.install();
            service.setInstalled();
            store.getServiceStore().updateService(service);
          }

          Logging.getLogger().info("Service '" + servicename + "' loaded.");
          this.connections.add(
              new ConnectInfo(servicename, serverIp, serverIp, port, "nokey", "service"));
        } catch (Exception e) {
          Logging.getLogger().warning("Unable to load service '" + servicename);
        }
      }
    } catch (Exception e) {
      Logging.getLogger().warning("Unable to load internal services : " + e);
      e.printStackTrace();
    }
  }
Exemple #25
0
 private void adjustConfiguration(Element root, File dir) {
   // If this is an ISN installation and the Edge Server
   // keystore and truststore files do not exist, then set the configuration
   // to use the keystore.jks and truststore.jks files instead of the ones
   // in the default installation. If the Edge Server files do exist, then
   // delete the keystore.jks and truststore.jks files, just to avoid
   // confusion.
   if (programName.equals("ISN")) {
     Element server = getFirstNamedChild(root, "Server");
     Element ssl = getFirstNamedChild(server, "SSL");
     String rsnaroot = System.getenv("RSNA_ROOT");
     rsnaroot = (rsnaroot == null) ? "/usr/local/edgeserver" : rsnaroot.trim();
     String keystore = rsnaroot + "/conf/keystore.jks";
     String truststore = rsnaroot + "/conf/truststore.jks";
     File keystoreFile = new File(keystore);
     File truststoreFile = new File(truststore);
     cp.appendln(Color.black, "Looking for " + keystore);
     if (keystoreFile.exists() || truststoreFile.exists()) {
       cp.appendln(Color.black, "...found it [This is an EdgeServer installation]");
       // Delete the default files, just to avoid confusion
       File ks = new File(dir, "keystore.jks");
       File ts = new File(dir, "truststore.jks");
       boolean ksok = ks.delete();
       boolean tsok = ts.delete();
       if (ksok && tsok) cp.appendln(Color.black, "...Unused default SSL files were removed");
       else {
         if (!ksok) cp.appendln(Color.black, "...Unable to delete " + ks);
         if (!tsok) cp.appendln(Color.black, "...Unable to delete " + ts);
       }
     } else {
       cp.appendln(Color.black, "...not found [OK, this is a non-EdgeServer installation]");
       ssl.setAttribute("keystore", "keystore.jks");
       ssl.setAttribute("keystorePassword", "edge1234");
       ssl.setAttribute("truststore", "truststore.jks");
       ssl.setAttribute("truststorePassword", "edge1234");
       cp.appendln(
           Color.black, "...SSL attributes were updated for a non-EdgeServer installation");
     }
   }
 }
Exemple #26
0
 // If this is a new installation, ask the user for a
 // port for the server; otherwise, return the negative
 // of the configured port. If the user selects an illegal
 // port, return zero.
 private int getPort() {
   // Note: directory points to the parent of the CTP directory.
   File ctp = new File(directory, "CTP");
   if (suppressFirstPathElement) ctp = ctp.getParentFile();
   File config = new File(ctp, "config.xml");
   if (!config.exists()) {
     // No config file - must be a new installation.
     // Figure out whether this is Windows or something else.
     String os = System.getProperty("os.name").toLowerCase();
     int defPort = ((os.contains("windows") && !programName.equals("ISN")) ? 80 : 1080);
     int userPort = 0;
     while (userPort == 0) {
       String port =
           JOptionPane.showInputDialog(
               null,
               "This is a new "
                   + programName
                   + " installation.\n\n"
                   + "Select a port number for the web server.\n\n",
               Integer.toString(defPort));
       try {
         userPort = Integer.parseInt(port.trim());
       } catch (Exception ex) {
         userPort = -1;
       }
       if ((userPort < 80) || (userPort > 32767)) userPort = 0;
     }
     return userPort;
   } else {
     try {
       Document doc = getDocument(config);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       String port = server.getAttribute("port");
       return -Integer.parseInt(port);
     } catch (Exception ex) {
     }
   }
   return 0;
 }
Exemple #27
0
 private boolean updateManifest(Manifest m, ZipOutputStream zos) throws IOException {
   addVersion(m);
   addCreatedBy(m);
   if (ename != null) {
     addMainClass(m, ename);
   }
   if (pname != null) {
     if (!addProfileName(m, pname)) {
       return false;
     }
   }
   ZipEntry e = new ZipEntry(MANIFEST_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     crc32Manifest(e, m);
   }
   zos.putNextEntry(e);
   m.write(zos);
   if (vflag) {
     output(getMsg("out.update.manifest"));
   }
   return true;
 }
  public static void testOutofDate() throws Exception {
    Workspace ws = Workspace.getWorkspace(new File("test/ws"));
    Project project = ws.getProject("p3");
    File bnd = new File("test/ws/p3/bnd.bnd");
    assertTrue(bnd.exists());

    project.clean();
    File pt = project.getTarget();
    if (!pt.exists() && !pt.mkdirs()) {
      throw new IOException("Could not create directory " + pt);
    }
    try {
      // Now we build it.
      File[] files = project.build();
      System.err.println(project.getErrors());
      System.err.println(project.getWarnings());
      assertTrue(project.isOk());
      assertNotNull(files);
      assertEquals(1, files.length);

      // Now we should not rebuild it
      long lastTime = files[0].lastModified();
      files = project.build();
      assertEquals(1, files.length);
      assertTrue(files[0].lastModified() == lastTime);

      Thread.sleep(2000);

      project.updateModified(System.currentTimeMillis(), "Testing");
      files = project.build();
      assertEquals(1, files.length);
      assertTrue("Must have newer files now", files[0].lastModified() > lastTime);
    } finally {
      project.clean();
    }
  }
Exemple #29
0
  /**
   * Class constructor; creates a new Installer object, displays a JFrame introducing the program,
   * allows the user to select an install directory, and copies files from the jar into the
   * directory.
   */
  public Installer(String args[]) {
    // Inputs are --install-dir INSTALL_DIR
    for (int k = 0; k < args.length; k = k + 2) {

      switch (args[k]) {
        case "--install-dir":
          directory = new File(args[k + 1]);
          System.out.println(directory);
          break;
        case "--port":
          port = Integer.parseInt(args[k + 1]);
          break;
      }
    }

    cp = new Stream();

    // Find the installer program so we can get to the files.
    installer = getInstallerProgramFile();
    String name = installer.getName();
    programName = (name.substring(0, name.indexOf("-"))).toUpperCase();

    // Get the installation information
    thisJava = System.getProperty("java.version");
    thisJavaBits = System.getProperty("sun.arch.data.model") + " bits";

    // Find the ImageIO Tools and get the version
    String javaHome = System.getProperty("java.home");
    File extDir = new File(javaHome);
    extDir = new File(extDir, "lib");
    extDir = new File(extDir, "ext");
    File clib = getFile(extDir, "clibwrapper_jiio", ".jar");
    File jai = getFile(extDir, "jai_imageio", ".jar");
    imageIOTools = (clib != null) && clib.exists() && (jai != null) && jai.exists();
    if (imageIOTools) {
      Hashtable<String, String> jaiManifest = getManifestAttributes(jai);
      imageIOVersion = jaiManifest.get("Implementation-Version");
    }

    // Get the CTP.jar parameters
    Hashtable<String, String> manifest = getJarManifestAttributes("/CTP/libraries/CTP.jar");
    programDate = manifest.get("Date");
    buildJava = manifest.get("Java-Version");

    // Get the util.jar parameters
    Hashtable<String, String> utilManifest = getJarManifestAttributes("/CTP/libraries/util.jar");
    utilJava = utilManifest.get("Java-Version");

    // Get the MIRC.jar parameters (if the plugin is present)
    Hashtable<String, String> mircManifest = getJarManifestAttributes("/CTP/libraries/MIRC.jar");
    if (mircManifest != null) {
      mircJava = mircManifest.get("Java-Version");
      mircDate = mircManifest.get("Date");
      mircVersion = mircManifest.get("Version");
    }

    // Set up the installation information for display
    if (imageIOVersion.equals("")) {
      imageIOVersion = "<b><font color=\"red\">not installed</font></b>";
    } else if (imageIOVersion.startsWith("1.0")) {
      imageIOVersion = "<b><font color=\"red\">" + imageIOVersion + "</font></b>";
    }
    if (thisJavaBits.startsWith("64")) {
      thisJavaBits = "<b><font color=\"red\">" + thisJavaBits + "</font></b>";
    }
    boolean javaOK = (thisJava.compareTo(buildJava) >= 0);
    javaOK &= (thisJava.compareTo(utilJava) >= 0);
    javaOK &= (thisJava.compareTo(mircJava) >= 0);
    if (!javaOK) {
      thisJava = "<b><font color=\"red\">" + thisJava + "</font></b>";
    }

    if (directory == null) exit();

    // Point to the parent of the directory in which to install the program.
    // so the copy process works correctly for directory trees.
    //
    // If the user has selected a directory named "CTP",
    // then assume that this is the directory in which
    // to install the program.
    //
    // If the directory is not CTP, see if it is called "RSNA" and contains
    // the Launcher program, in which case we can assume that it is an
    // installation that was done with Bill Weadock's all-in-one installer for Windows.
    //
    // If neither of those cases is true, then this is already the parent of the
    // directory in which to install the program
    if (directory.getName().equals("CTP")) {
      directory = directory.getParentFile();
    } else if (directory.getName().equals("RSNA")
        && (new File(directory, "Launcher.jar")).exists()) {
      suppressFirstPathElement = true;
    }

    // Cleanup old releases
    cleanup(directory);

    // Get a port for the server.
    if (port < 0) {
      if (checkServer(-port, false)) {
        System.err.println(
            "CTP appears to be running.\nPlease stop CTP and run the installer again.");
        System.exit(0);
      }
    }

    // Now install the files and report the results.
    int count =
        unpackZipFile(installer, "CTP", directory.getAbsolutePath(), suppressFirstPathElement);
    if (count > 0) {
      // Create the service installer batch files.
      updateWindowsServiceInstaller();
      updateLinuxServiceInstaller();

      // If this was a new installation, set up the config file and set the port
      installConfigFile(port);

      // Make any necessary changes in the config file to reflect schema evolution
      fixConfigSchema();

      System.out.println("Installation complete.");
      System.out.println(programName + " has been installed successfully.");
      System.out.println(count + " files were installed.");
    } else {
      System.err.println("Installation failed.");
      System.err.println(programName + " could not be fully installed.");
    }
    if (!programName.equals("ISN") && startRunner(new File(directory, "CTP"))) System.exit(0);
  }
Exemple #30
0
 private static void exit() {
   System.exit(0);
 }