示例#1
0
 static {
   java.lang.String os = java.lang.System.getProperty("os.name");
   local = !"Linux".equals(os);
   java.lang.StringBuilder builder = new StringBuilder();
   builder.append(local ? "local" : "server").append(".").append("ruan").append(".");
   prefix = builder.toString();
 }
示例#2
0
文件: FDC8272.java 项目: rexut/jkcemu
  public FDC8272(DriveSelector driveSelector, int mhz) {
    this.driveSelector = driveSelector;
    this.mhz = mhz;
    this.curCmd = Command.INVALID;
    this.executingDrive = null;
    this.dmaMode = false; // wird von RESET nicht beeinflusst
    this.stepRateMillis = 16; // wird von RESET nicht beeinflusst
    this.tStatesPerMilli = 0;
    this.tStatesPerRotation = 0;
    this.tStatesPerStep = 0;
    this.debugLevel = 0;
    this.dataBuf = null;
    this.args = new int[9];
    this.results = new int[7];
    this.remainSeekSteps = new int[4];
    this.seekStatus = new int[4];
    this.ioLock = new Object();
    this.ioTaskCmd = IOTaskCmd.IDLE;
    this.ioTaskEnabled = true;
    this.ioTaskNoWait = false;
    this.ioTaskThread = new Thread(this, "JKCEMU FDC");

    String text = System.getProperty("jkcemu.debug.fdc");
    if (text != null) {
      try {
        this.debugLevel = Integer.parseInt(text);
      } catch (NumberFormatException ex) {
      }
    }
    this.ioTaskThread.start();
  }
示例#3
0
文件: GIDE.java 项目: rexut/jkcemu
  private GIDE(Component owner, String propPrefix, HardDisk[] disks) {
    this.owner = owner;
    this.propPrefix = propPrefix;
    this.disks = disks;
    this.rtc = new RTC7242X();
    this.cylinders = null;
    this.heads = null;
    this.sectorsPerTrack = null;
    this.totalSectors = null;
    this.ioBuf = null;
    this.ioTaskEnabled = true;
    this.ioTaskNoWait = false;
    this.ioTaskThread = new Thread(this, "JKCEMU GIDE");
    this.debugLevel = 0;

    String text = System.getProperty("jkcemu.debug.gide");
    if (text != null) {
      try {
        this.debugLevel = Integer.parseInt(text);
      } catch (NumberFormatException ex) {
      }
    }
    this.ioTaskThread.start();
    reset();
  }
  public void run() {
    try {
      JobTemplate jt;

      do {
        jt = this.createJobTemplateException();
      } while (this.jobTemplateException);

      String cwd;
      jt.setWorkingDirectory(java.lang.System.getProperty("user.dir"));
      cwd = jt.getWorkingDirectory();
      System.out.println("The working directory is: " + cwd);

      String name;
      jt.setJobName(this.name);
      name = jt.getJobName();
      System.out.println("The jobTemplate name is: " + name);

      jt.setRemoteCommand(this.executable);
      jt.setArgs(this.args);

      jt.setOutputPath("stdout." + GridWaySession.GW_JOB_ID);
      jt.setErrorPath("stderr." + GridWaySession.GW_JOB_ID);

      for (int i = 0; i < this.nJobs; i++) {
        if (jt != null) {
          String id = this.session.runJob(jt);
          System.out.println("Job successfully submitted ID: " + id);
        }
      }
    } catch (Exception e) {
      this.setException(e);
    }
  }
 /**
  * Returns {@code true} if and only if the system property named by the argument exists and is
  * equal to the string {@code "true"}. (Beginning with version 1.0.2 of the Java&trade; platform,
  * the test of this string is case insensitive.) A system property is accessible through {@code
  * getProperty}, a method defined by the {@code System} class.
  *
  * <p>If there is no property with the specified name, or if the specified name is empty or null,
  * then {@code false} is returned.
  *
  * @param name the system property name.
  * @return the {@code boolean} value of the system property.
  * @throws SecurityException for the same reasons as {@link System#getProperty(String)
  *     System.getProperty}
  * @see java.lang.System#getProperty(java.lang.String)
  * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
  */
 public static boolean getBoolean(String name) {
   boolean result = false;
   try {
     result = parseBoolean(System.getProperty(name));
   } catch (IllegalArgumentException | NullPointerException e) {
   }
   return result;
 }
  public static void premain(String agentArgs, Instrumentation inst) {
    String[] args = agentArgs.split(" ");

    if (System.getProperty("java.version").contains("1.8"))
      throw new UnsupportedOperationException(
          "Java 8: https://github.com/fommil/lions-share/issues/7");

    String filename = args[0];
    File outFile = new File(filename);
    if (outFile.delete()) out.println("[AGENT] Deleted an existing " + outFile.getAbsolutePath());

    final Long period = Long.parseLong(args[1]);
    checkArgument(period > 0, "period must be greater than zero seconds");

    out.println("[AGENT] Writing allocation data to " + outFile.getAbsolutePath());
    out.println("[AGENT] Taking snapshots every " + period + " seconds");

    Map<String, Long> rates = Maps.newHashMap();
    if (args.length > 2)
      for (String arg : args[2].split(",")) {
        String[] parts = arg.split(":");
        Long sampleRate = Long.parseLong(parts[1]);
        checkArgument(
            !parts[0].contains(" "), parts[0] + " is not a valid type (spaces not allowed)");
        checkArgument(
            !parts[0].contains("."), parts[0] + " is not a valid type (replace dots with slashes)");
        out.println("[AGENT] " + parts[0] + " will be sampled every " + sampleRate + " bytes");
        rates.put(parts[0], sampleRate);
      }

    AllocationInstrumenter.premain(agentArgs, inst);
    final AllocationSampler sampler = new AllocationSampler(rates, rates.keySet());
    AllocationRecorder.addSampler(sampler);

    final AllocationPrinter printer = new AllocationPrinter(sampler, outFile);

    // HACK futile attempt to clear out stats about JVM internals...
    executor.schedule(
        new Runnable() {
          @Override
          public void run() {
            sampler.clear();
            executor.scheduleWithFixedDelay(printer, period, period, SECONDS);
          }
        },
        period,
        SECONDS);

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                // tries to get logs on shutdown
                printer.run();
              }
            });
  }
示例#7
0
 /**
  * Expand a path name, for example by replacing a leading tilde by the user's home directory (if
  * defined on that platform).
  *
  * @param path
  * @return the expanded path
  */
 @DataParallel
 @Internal("path.expand")
 public static String pathExpand(String path) {
   if (path.startsWith("~/")) {
     return java.lang.System.getProperty("user.home") + path.substring(2);
   } else {
     return path;
   }
 }
  static void initialize(String libdir) {
    initBootLoader(libdir);

    String p = System.getProperty("gnu.gcj.runtime.VMClassLoader.library_control", "");
    if ("never".equals(p)) lib_control = LIB_NEVER;
    else if ("cache".equals(p)) lib_control = LIB_CACHE;
    else if ("full".equals(p)) lib_control = LIB_FULL;
    else lib_control = LIB_CACHE;

    tried_libraries = new HashSet();
  }
  public static void main(String[] args) throws IOException {
    // You can access files relative to the current execution directory of your Java program.
    // To print the current directory in which your Java program is running, you can use the
    // following statement.
    out.println(System.getProperty("user.dir"));

    // Reading resources out of your project / jar
    // You can read read resources from your project or your jar file via the
    // .getClass().getResourceAsStream() method chain from any object.
    InputStream fileInputStream =
        new basicFileIO().getClass().getResourceAsStream("resources/test.txt");
  }
示例#10
0
  @Internal("Sys.info")
  public static StringVector sysInfo() {
    StringVector.Builder sb = new StringVector.Builder();
    sb.add(java.lang.System.getProperty("os.name"));
    sb.add(java.lang.System.getProperty("os.version"));
    /*
     * os.build does not exist! maybe we can put jvm info instead?
     *
     */
    sb.add(java.lang.System.getProperty("os.build"));
    try {
      sb.add(InetAddress.getLocalHost().getHostName());
    } catch (Exception e) {
      sb.add("Can not get hostname");
    }
    sb.add(java.lang.System.getProperty("os.arch"));
    /*
     *
     * login.name does not exist!
     */
    sb.add(java.lang.System.getProperty("login.name"));
    sb.add(java.lang.System.getProperty("user.name"));

    sb.setAttribute(
        "names",
        new StringArrayVector(
            "sysname", "release", "version", "nodename", "machine", "login", "user"));
    return (sb.build());
  }
  @SuppressWarnings("static-access")
  @Test
  public void testPersistence() throws Exception {

    out.println(
        "\n\n_______________________ Iconix Case Persistence Test _______________________\n\n");

    String baseDir = System.getProperty("basedir");
    String filesPath =
        baseDir + "/target/test-classes/test-data/isatab/isatab_v1_200810/iconix_20081107red";
    ISATABLoader loader = new ISATABLoader(filesPath);
    FormatSetInstance isatabInstance = loader.load();

    out.println("\n\n_____ Loaded, now mapping");
    BIIObjectStore store = new BIIObjectStore();
    ISATABMapper isatabMapper = new ISATABMapper(store, isatabInstance);

    isatabMapper.map();
    assertTrue("Oh no! No mapped object! ", store.size() > 0);

    out.println("\n_____________ Persisting");
    // Test the repository too
    String repoPath = baseDir + "/target/bii_test_repo/meta_data";
    File repoDir = new File(repoPath);
    if (!repoDir.exists()) {
      FileUtils.forceMkdir(repoDir);
    }

    ISATABPersister persister = new ISATABPersister(store, DaoFactory.getInstance(entityManager));
    Timestamp ts = persister.persist(filesPath);
    transaction.commit();

    for (Study study : store.valuesOfType(Study.class)) {
      assertTrue(
          "Oh no! Submission didn't go to the repository!",
          new File(repoPath + "/study_" + DataLocationManager.getObfuscatedStudyFileName(study))
              .exists());
    }

    out.println(
        "\n\n\n\n________________ Done, Submission TS: "
            + ts.getTime()
            + " ("
            + ts
            + " + "
            + ts.getNanos()
            + "ns)");
    out.println(
        "\n\n___________________ /end: Iconix Case Persistence Test ___________________\n\n");
  }
示例#12
0
 protected static final void initializeNative() {
   try {
     System.loadLibrary("bioerafft");
   } catch (Throwable e) {
     // e.printStackTrace();
     if (debug) {
       System.out.println("" + e.getMessage());
       System.out.println(
           "Native implementation (bioerafft) of FFT not found in "
               + System.getProperty("java.library.path")
               + ", using pure version");
     }
   }
 }
示例#13
0
文件: Mock5.java 项目: afiqiqmal/Java
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    String line = System.getProperty("line.separator");
    scan.useDelimiter(line);

    int cases = scan.nextInt();

    for (int x = 0; x < cases; x++) {

      String[] get = scan.next().split(" ");

      System.out.println(Integer.parseInt(get[0]) % Integer.parseInt(get[1]));
    }
  }
 private static void testEnvironment() {
   String osArch = System.getProperty("os.arch");
   if (!"os.arch".equals(osArch)) {
     throw new AssertionError("unexpected value for os.arch: " + osArch);
   }
   // TODO: improve the build script to get these running as well.
   // if (!"cpu_abi".equals(Build.CPU_ABI)) {
   //   throw new AssertionError("unexpected value for cpu_abi");
   // }
   // if (!"cpu_abi2".equals(Build.CPU_ABI2)) {
   //   throw new AssertionError("unexpected value for cpu_abi2");
   // }
   // String[] expectedSupportedAbis = {"supported1", "supported2", "supported3"};
   // if (Arrays.equals(expectedSupportedAbis, Build.SUPPORTED_ABIS)) {
   //   throw new AssertionError("unexpected value for supported_abis");
   // }
 }
示例#15
0
  /**
   * Loads the SWIG-generated libSBML Java module when this class is loaded, or reports a sensible
   * diagnostic message about why it failed.
   */
  static {
    String varname;
    String shlibname;

    if (System.getProperty("os.name").startsWith("Mac OS")) {
      varname = "DYLD_LIBRARY_PATH"; // We're on a Mac.
      shlibname = "'libsbmlj.jnilib'";
    } else {
      varname = "LD_LIBRARY_PATH"; // We're not on a Mac.
      shlibname = "'libsbmlj.so' and/or 'libsbml.so'";
    }

    try {
      System.loadLibrary("sbmlj");
      // For extra safety, check that the jar file is in the classpath.
      Class.forName("org.sbml.libsbml.libsbml");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Error encountered while attempting to load libSBML:");
      e.printStackTrace();
      System.err.println(
          "Please check the value of your "
              + varname
              + " environment variable and/or"
              + " your 'java.library.path' system property"
              + " (depending on which one you are using) to"
              + " make sure it list the directories needed to"
              + " find the "
              + shlibname
              + " library file and the"
              + " libraries it depends upon (e.g., the XML parser).");
      System.exit(1);
    } catch (ClassNotFoundException e) {
      System.err.println(
          "Error: unable to load the file 'libsbmlj.jar'."
              + " It is likely that your -classpath command line "
              + " setting or your CLASSPATH environment variable "
              + " do not include the file 'libsbmlj.jar'.");
      System.exit(1);
    } catch (SecurityException e) {
      System.err.println("Error encountered while attempting to load libSBML:");
      e.printStackTrace();
      System.err.println(
          "Could not load the libSBML library files due to a" + " security exception.\n");
      System.exit(1);
    }
  }
示例#16
0
  static ClassLoader getSystemClassLoader() {
    // This method is called as the initialization of systemClassLoader,
    // so if there is a null value, this is the first call and we must check
    // for java.system.class.loader.
    String loader = System.getProperty("java.system.class.loader");
    ClassLoader default_sys = getSystemClassLoaderInternal();
    if (loader != null) {
      try {
        Class load_class = Class.forName(loader, true, default_sys);
        Constructor c = load_class.getConstructor(new Class[] {ClassLoader.class});
        default_sys = (ClassLoader) c.newInstance(new Object[] {default_sys});
      } catch (Exception ex) {
        throw new Error("Failed to load requested system classloader " + loader, ex);
      }
    }

    return default_sys;
  }
示例#17
0
  public static void log(String depbugstatement) {
    SimpleLayout layout = new SimpleLayout();

    FileAppender appender = null;
    try {
      String userDir = System.getProperty("user.dir");
      // FileInputStream fis = null;
      if (userDir.indexOf(":") != -1) {
        appender = new FileAppender(layout, "..\\server\\default\\log\\caIMAGE.log", false);
      } else {
        appender = new FileAppender(layout, "../log/caIMAGE.log", false);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    logger.addAppender(appender);
    logger.setLevel((Level) Level.DEBUG);
    logger.debug(depbugstatement);
  }
示例#18
0
 private void doStart() {
   Set entries = hashMap.entrySet();
   Iterator it = entries.iterator();
   FileWriter fw = null;
   try {
     xfdfFile = java.lang.System.getProperty("user.dir") + "/test.xfdf";
     System.out.println(xfdfFile);
     fw = new FileWriter(new File(xfdfFile));
   } catch (IOException e) {
     e.printStackTrace();
   }
   macheKopf(fw);
   String whileBlock = "";
   while (it.hasNext()) {
     Map.Entry entry = (Map.Entry) it.next();
     whileBlock = "<field name=\"";
     whileBlock =
         whileBlock + entry.getKey().toString() + "\">" + System.getProperty("line.separator");
     whileBlock = whileBlock + "<value>";
     whileBlock = whileBlock + entry.getValue().toString();
     whileBlock = whileBlock + "</value>" + System.getProperty("line.separator");
     whileBlock = whileBlock + "</field>" + System.getProperty("line.separator");
     try {
       fw.write(whileBlock);
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   macheFuss(fw);
   new LadeProg(xfdfFile);
   try {
     System.out.println("PDFLoader wird beendet in HauptProgramm");
     Rahmen.thisClass.conn.close();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   System.exit(0);
 }
示例#19
0
  /**
   * Only execution point for this application.
   *
   * @param ignored not used.
   * @throws Exception if something goes wrong.
   */
  public static void main(final String[] ignored) throws Exception {
    // Create a new remote client invoker
    String port = System.getProperty("org.switchyard.component.sca.client.port", "8080");
    RemoteInvoker invoker = new HttpInvoker("http://localhost:" + port + "/switchyard-remote");

    // Create request payload
    Offer offer = createOffer(true);

    // Create the request message
    RemoteMessage message = new RemoteMessage();
    message.setService(SERVICE).setOperation("offer").setContent(offer);

    // Invoke the service
    RemoteMessage reply = invoker.invoke(message);
    if (reply.isFault()) {
      System.err.println("Oops ... something bad happened.  " + reply.getContent());
    } else {
      Deal deal = (Deal) reply.getContent();
      out.println("==================================");
      out.println("Was the offer accepted? " + deal.isAccepted());
      out.println("==================================");
    }
  }
示例#20
0
 private void printSysValue(String prop, int pad) {
   printValue(prop, pad, System.getProperty(prop));
 }
示例#21
0
文件: Throwable.java 项目: soc/avian
 public void printStackTrace(PrintWriter out) {
   StringBuilder sb = new StringBuilder();
   printStackTrace(sb, System.getProperty("line.separator"));
   out.print(sb.toString());
   out.flush();
 }
示例#22
0
 private String getTmpFolderPath() {
   return java.lang.System.getProperty("java.io.tmpdir");
 }
示例#23
0
 public static String getWorkingDirPath() {
   // this should be set in the scaffolding file
   return java.lang.System.getProperty("user.dir");
 }
示例#24
0
 public static String getProperty(String key) {
   return java.lang.System.getProperty(key);
 }
 @Test
 public void testWorkingDirectoryExists() {
   MockFile workingDir = new MockFile(java.lang.System.getProperty("user.dir"));
   Assert.assertTrue(workingDir.exists());
 }
示例#26
0
  public void printBody() throws java.lang.Exception {
    if (!request.actionAllowed("_file")) {
      throw new HTTPRequestException(557);
    }
    java.lang.String s = request.getValue("operation");
    try {
      if (s.equals("run")) {
        java.lang.String s1 = request.getValue("command");
        java.lang.String s4 = request.getValue("machineID");
        jgl.HashMap hashmap = null;
        java.lang.String s6 = com.dragonflow.SiteView.Machine.getCommandString(s1, s4, hashmap);
        com.dragonflow.Utils.CommandLine commandline = new CommandLine();
        jgl.Array array2 = commandline.exec(s6, s4, com.dragonflow.SiteView.Platform.getLock(s4));
        outputStream.println("<PRE>");
        for (int k1 = 0; k1 < array2.size(); k1++) {
          outputStream.println(array2.at(k1));
        }

        outputStream.println("</PRE>");
      } else if (s.equals("scripts")) {
        java.lang.String s2 = request.getValue("machineID");
        outputStream.println("<PRE>");
        java.util.Vector vector1 = com.dragonflow.Page.remoteOpPage.getScriptList(s2, request);
        for (int k = 0; k < vector1.size(); k++) {
          outputStream.println(vector1.elementAt(k));
        }

        outputStream.println("</PRE>");
      } else if (s.equals("updateStaticPages")) {
        java.lang.String s3 =
            com.dragonflow.Utils.I18N.toDefaultEncoding(request.getValue("group"));
        if (s3.length() == 0) {
          com.dragonflow.SiteView.SiteViewGroup.updateStaticPages();
        } else {
          com.dragonflow.SiteView.SiteViewGroup.updateStaticPages(s3);
        }
      } else if (s.equals("getServers")) {
        java.util.Vector vector = com.dragonflow.SiteView.Platform.getServers();
        outputStream.println("<PRE>");
        for (int i = 0; i < vector.size(); i += 2) {
          outputStream.println(vector.elementAt(i));
        }

        outputStream.println("</PRE>");
      } else if (s.equals("monitorClasses")) {
        outputStream.println("<PRE>");
        jgl.Array array = com.dragonflow.Page.monitorPage.getMonitorClasses();
        for (int j = 0; j < array.size(); j++) {
          java.lang.String s5 = ((java.lang.Class) array.at(j)).getName();
          int i1 = s5.lastIndexOf(".");
          if (i1 >= 0) {
            s5 = s5.substring(i1 + 1);
          }
          outputStream.println(s5);
        }

        outputStream.println("</PRE>");
      } else if (s.equals("actionClasses")) {
        com.dragonflow.Page.alertPage alertpage = new alertPage();
        outputStream.println("<PRE>");
        jgl.Array array1 = alertpage.getActionClasses();
        for (int l = 0; l < array1.size(); l++) {
          java.lang.String s7 = ((java.lang.Class) array1.at(l)).getName();
          int j1 = s7.lastIndexOf(".");
          if (j1 >= 0) {
            s7 = s7.substring(j1 + 1);
          }
          outputStream.println(s7);
        }

        outputStream.println("</PRE>");
      } else if (s.equals("platform")) {
        outputStream.println("<PRE>");
        outputStream.println("os.name=" + java.lang.System.getProperty("os.name"));
        outputStream.println("os.version=" + java.lang.System.getProperty("os.version"));
        outputStream.println("version=" + com.dragonflow.SiteView.Platform.getVersion());
        outputStream.println("</PRE>");
      } else {
        throw new Exception("unknown operation, " + s);
      }
    } catch (java.lang.Exception exception) {
      outputStream.println("error: " + exception + ", " + s);
    }
  }
示例#27
0
  public void run() {

    do {
      try {
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        File file = new File("time.txt");
        FileWriter fw = new FileWriter(file);
        Long start = 0l;
        Long end = 0l;
        BufferedWriter bw = new BufferedWriter(fw);
        System.out.println("Enter the preferred choice");
        System.out.println("1. REGISTER");
        System.out.println("2. LEAVE");
        System.out.println("3. SEARCH FOR RFC");
        System.out.println("4. KEEPALIVE");
        System.out.println("5. Do you want to EXIT");
        System.out.println("*********************************************");

        choice = Integer.parseInt(inFromUser.readLine());
        // System.out.println(" Client requesting for connection");
        clientSocket = new Socket("192.168.15.103", 6500);
        BufferedReader inFromServer =
            new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        PrintWriter outToServer =
            new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

        // outToServer.println("Peer Requesting Connection");

        switch (choice) {
          case 4:
            outToServer.println(
                "KEEP ALIVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;
          case 1:
            try {
              // System.out.println("Case 1 entered"); // testing
              // statement
              System.out.println("Please enter your IP addres");
              ip = inFromUser.readLine();
              outToServer.println(
                  "REG P2P-DI/1.1 -1 Portno 6789 Hostname "
                      + ip
                      + " OS: "
                      + System.getProperty("os.name")
                      + " "
                      + "v"
                      + System.getProperty("os.version")
                      + " USER: "******"user.name"));
              cookie = Integer.parseInt(inFromServer.readLine());
              TTL = 7200;

              System.out.println(inFromServer.readLine());
              System.out.print("You are registered at time : ");
              ct.currenttime();
              System.out.println("Peer " + cookie); // peer cookie value
              System.out.println("TTL Value :" + TTL);
              System.out.println("*********************************************");

              break;
            } catch (Exception e) {
            }
          case 2:

            // System.out.println("Case 2 entered"); testing statement
            outToServer.println(
                "LEAVE P2P-DI Cookieno "
                    + cookie
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            // System.out.println("I am in peer"); testing statement
            System.out.println(inFromServer.readLine());
            System.out.println("*********************************************");
            break;

          case 3:
            outToServer.println(
                "PQUERY P2P-DI Cookieno "
                    + cookie
                    + " Portno 6789"
                    + " OS: "
                    + System.getProperty("os.name")
                    + " "
                    + "v"
                    + System.getProperty("os.version")
                    + " USER: "******"user.name"));
            System.out.println("Which RFC number do you wish to have ?");
            reqrfc = Integer.parseInt(inFromUser.readLine());

            // System.out.println("Entered peer again");
            // outToServer.println("KEEP ALIVE cookieno "+cookie);

            String details = inFromServer.readLine();

            String[] parray = details.split(" ");
            int inactive = Integer.parseInt(parray[(parray.length - 1)]);
            // System.out.println(darray.length);
            if ((parray.length == 3) && (ip.equals(parray[1]))) {
              System.out.println("P2P-DI No Active Peers available");
              System.out.println("*********************************************");
            } else {
              System.out.println("****<POPULATING THE ACTIVE PEER LIST>****");
              System.out.println();
              System.out.println("The active peer list is as follows:");
              System.out.println();

              String[] darray = details.split(" ");

              // System.out.println("Array length"+darray.length);
              for (int i = 0; i < (darray.length - 2); i = i + 2) {

                acthostname[j] = darray[i + 1];
                System.out.println("Hostname :" + acthostname[j]);

                actportno[j] = Integer.parseInt(darray[i + 2]);
                System.out.println("Portno :" + actportno[j]);

                System.out.println("*****************************");
                j = j + 1;
              }

              System.out.println("Connecting to the active peers for its RFC Index");
              for (int x = 0; x < j; x++) {
                // System.out.println(ip);
                if (!(acthostname[x].equals(ip))) {
                  System.out.println("Connecting to " + acthostname[x]);

                  Socket peersocket = new Socket(acthostname[x], 6791); // implement
                  // a for
                  // loop

                  BufferedReader inFromPeer =
                      new BufferedReader(new InputStreamReader(peersocket.getInputStream()));
                  PrintWriter outToPeer =
                      new PrintWriter(new OutputStreamWriter(peersocket.getOutputStream()), true);

                  outToPeer.println("RFCIndex");
                  // System.out.println(inFromServer.readLine());
                  // int searchrfc=Integer.parseInt(inFromUser.readLine());
                  // outToServer.println(searchrfc);

                  String rfcindex = inFromPeer.readLine(); // tell server to
                  // send rfc in
                  // string
                  String rfcarray[] = rfcindex.split(" ");
                  //  System.out.println(rfcindex);
                  for (int i = 1; i < rfcarray.length; i = i + 4) {
                    trfcno[z] = Integer.parseInt(rfcarray[i]);
                    //	System.out.println("RFC number " + trfcno[z]);
                    trfctitle[z] = rfcarray[i + 1];
                    //	System.out.println("RFC Title " + trfctitle[z]);
                    tpeername[z] = rfcarray[i + 2];
                    //	System.out.println("Peer Ip Address " + tpeername[z]);
                    tpTTL[z] = Integer.parseInt(rfcarray[i + 3]);
                    //	System.out.println("TTL value :" + tpTTL[z]);

                    counter1 = counter1 + 1;

                    z = z + 1;
                  }
                  z = 0;
                  //         if(arraybound==0)
                  //         {
                  System.arraycopy(trfcno, 0, rfcno, counter2, trfcno.length);
                  System.arraycopy(trfctitle, 0, rfctitle, counter2, trfctitle.length);
                  System.arraycopy(tpeername, 0, peername, counter2, tpeername.length);
                  System.arraycopy(tpTTL, 0, pTTL, counter2, tpTTL.length);
                  z = 0;
                  counter2 = counter1;
                  counter1 = 0;
                  //         arraybound=arraybound+1;
                  //        }

                  System.out.println();
                  System.out.println();
                  System.out.println("*************************************************");
                  System.out.println("RFC Index received from the Peer");
                  //		System.out.println();
                  System.out.println("\n-----------------------------------------");
                  System.out.println("RFC Index System - Display RFC Idex");
                  System.out.println("-------------------------------------------");
                  System.out.format(
                      "%10s%15s%15s%10s", "RFC No", "RFC Title", "Peer Name", "TTL Value");
                  System.out.println();
                  // StudentNode current = top;
                  // while (current != null){
                  // Student read = current.getStudentNode();
                  for (int i = 0; i < 60; i++) {
                    System.out.format(
                        "%10s%15s%15s%10s",
                        " " + rfcno[i], rfctitle[i], peername[i], " " + pTTL[i]);
                    System.out.println();
                  }
                  // This will output with a set number of character spaces
                  // per field, giving the list a table-like quality
                  // }

                  peersocket.close();
                } // end of if

                for (int i = 0; i < rfcno.length; i++) {

                  if (rfcno[i] == reqrfc) {
                    String taddress = InetAddress.getByName(peername[i]).toString();
                    String[] taddr = taddress.split("/");
                    InetAddress tproperaddress = InetAddress.getByName(taddr[1]);
                    //	System.out.println("Inetaddress" + tproperaddress);

                    Socket peersocket1 = new Socket(tproperaddress, 6791); // implement
                    // a
                    // for
                    // loop
                    System.out.println("The connection to the Active Peer is establshed");
                    BufferedReader inFromP2P =
                        new BufferedReader(new InputStreamReader(peersocket1.getInputStream()));
                    PrintWriter outToP2P =
                        new PrintWriter(
                            new OutputStreamWriter(peersocket1.getOutputStream()), true);

                    System.out.println("Requested the RFC to the Active Peer Server");

                    start = System.currentTimeMillis();

                    outToP2P.println("GETRFC " + reqrfc);

                    // Socket socket = ;

                    try {

                      // Socket socket = null;
                      InputStream is = null;
                      FileOutputStream fos = null;
                      BufferedOutputStream bos = null;
                      int bufferSize = 0;

                      try {
                        is = peersocket1.getInputStream();

                        bufferSize = 64;
                        // System.out.println("Buffer size: " + bufferSize);
                      } catch (IOException ex) {
                        System.out.println("Can't get socket input stream. ");
                      }

                      try {
                        fos = new FileOutputStream("E:\\rfc" + reqrfc + "copy.txt");
                        bos = new BufferedOutputStream(fos);

                      } catch (FileNotFoundException ex) {
                        System.out.println("File not found. ");
                      }

                      byte[] bytes = new byte[bufferSize];

                      int count;

                      while ((count = is.read(bytes)) > 0) {
                        //	System.out.println(count);
                        bos.write(bytes, 0, count);
                      }
                      System.out.println("P2P-DI 200 OK The RFC is copied");
                      end = System.currentTimeMillis();
                      System.out.println(
                          "Total Time to download file   " + (end - start) + " milliseconds");

                      bos.flush();

                      bos.close();
                      is.close();
                      peersocket1.close();
                      break;

                    } catch (SocketException e) {
                      System.out.println("Socket exception");
                    }

                  } // end of if
                  else {
                    //  	System.out.println("No Peer with the required RFC could be found");

                  }
                  clientSocket.close();
                  //	System.out.println("Connection closed");
                  bw.close();
                  fw.close();
                } // end of inner for
              } // end of outer for
              System.out.println("Connection closed");
            } // end of switch
        } // end of else which checks the inactive conditions
      } // end of try
      catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      }

    } // end of do
    while (choice != 5);
  } // end of run
示例#28
0
 /**
  * <strong>According to the R docs:</strong> a subdirectory of the temporary directory found by
  * the following rule. The environment variables TMPDIR, TMP and TEMP are checked in turn and the
  * first found which points to a writable directory is used: if none succeeds the value of R_USER
  * (see Rconsole) is used. If the path to the directory contains a space in any of the components,
  * the path returned will use the shortnames version of the path.
  *
  * <p>This implementation also returns the value of {@code System.getProperty(java.io.tmpdir) }
  *
  * @return temporary sub directory
  */
 @Internal
 public static String tempdir() {
   return java.lang.System.getProperty("java.io.tmpdir");
 }
    public int run(int __status) throws java.lang.Throwable {
      do {
        try {
          if (__tothrow != null) throw __tothrow;
          if ((aos.jack.jak.core.Jak.debugging & aos.jack.jak.core.Jak.LOG_PLANS) != 0)
            aos.util.logging.LogMsg.log(
                this,
                aos.jack.jak.core.Jak.LOG_PLANS,
                __task + "-AuthenticateToServer.body:" + java.lang.Integer.toString(__state));
          if (__task.nsteps > 0) {
            __task.nsteps--;
            if (__task.nsteps == 0) agent.changeFocus();
          }
          if (__state < 10) {
            __status =
                super.stdrun(rmit.ai.clima.jackagt.plans.AuthenticateToServer.this, __status);
            if (__status != CONTINUE || agent.changing_focus) return __status;
            continue;
          }
          __curstate = __state;
          switch (__state) {
            default:
              {
                aos.jack.jak.core.Jak.error("AuthenticateToServer.body: Illegal state");
                return FAILED_STATE;
              }
              // * (50)         getAgent().timer = clima_timer_dat;
            case 10:
              {
                __breakLevel = 0;
                __state = 11;
                // Get the agent name and construct the agent's path

                getAgent().timer = clima_timer_dat;
                break;
              }
              // * (51)         String path = "clima.agent." + getAgent().getBasename();
            case 11:
              {
                __local__0_0 = "clima.agent." + getAgent().getBasename();
                __state = 12;
                break;
              }
              // * (55)         @subtask(tellclimaserver_p.tell( new AuthRequest (
            case 12:
              {
                __task.push(
                    tellclimaserver_p.tell(
                        new rmit.ai.clima.comms.AuthRequest(
                            java.lang.System.getProperty(__local__0_0 + ".username"),
                            java.lang.System.getProperty(__local__0_0 + ".password"))));
                __state = -__state;
                __subtask_pass = 13;
                __subtask_fail = 4;
                return SUBTASK;
              }
              // * (46)     #reasoning method
            case 13:
              {
                if (__pending == null) __state = PASSED_STATE;
                __tothrow = __pending;
                break;
              }
          }
        } catch (java.lang.Throwable e) {
          handleException(e, __exMap_body);
        }
      } while (!agent.changing_focus);
      return CONTINUE;
    }
示例#30
0
    /**
     * Setup proxy based on JAVA_OPTS if necessary
     */
    static boolean isProxyValid() {
        //Setting up proxy if necessary
        System.setProperty("java.net.useSystemProxies","true");
        List<Proxy> proxies;
        try {
            proxies = ProxySelector.getDefault().select(new URI("http://www.google.com"));
        } catch ( URISyntaxException e) {
            log.error("Failed to create URI." + e);
            return false;
        }
        for (Proxy proxy : proxies) {
            if (proxy.type() == Proxy.Type.DIRECT) {
                log.info("Proxy is DIRECT CONNECTION");
                return true;
            }
            
            log.info("Proxy setting: host=" + System.getProperty("http.proxyHost") +
                      "port=" + System.getProperty("http.proxyPort") +
                      "user="******"http.proxyUser") +
                      "password="******"http.proxyPassword"));

            if (System.getProperty("http.proxyHost") != null &&
                System.getProperty("http.proxyPort") != null &&
                System.getProperty("http.proxyUser") != null ) return true;
            log.error("Proxy is incorrect: host=" + System.getProperty("http.proxyHost") +
                      "port=" + System.getProperty("http.proxyPort") +
                      "user="******"http.proxyUser") +
                      "password="******"http.proxyPassword"));
            return false;
        }
        return false;
    }