private void sendProcessingError(Throwable t, ServletResponse response) {

    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {

      try {

        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    }
  }
 /** ** Main client thread loop */
 public void run() {
   this.setRunStatus(THREAD_RUNNING);
   this.threadStarted();
   try {
     this.openSocket();
     this.inputThread = new InputThread(this.socket, this.readTimeout, this.ioThreadLock);
     this.outputThread = new OutputThread(this.socket, this.ioThreadLock);
     this.inputThread.start();
     this.outputThread.start();
     synchronized (this.ioThreadLock) {
       while (this.inputThread.isRunning() || this.outputThread.isRunning()) {
         try {
           this.ioThreadLock.wait();
         } catch (Throwable t) {
         }
       }
     }
   } catch (NoRouteToHostException nrthe) {
     Print.logInfo("Client:ControlThread - Unable to reach " + this.host + ":" + this.port);
     nrthe.printStackTrace();
   } catch (Throwable t) {
     Print.logInfo("Client:ControlThread - " + t);
     t.printStackTrace();
   } finally {
     this.closeSocket();
   }
   this.setRunStatus(THREAD_STOPPED);
   this.threadStopped();
 }
  public void runPreProcess() {

    Authorization auth = new glguerin.authkit.imp.macosx.MacOSXAuthorization();
    Privilege priv = new Privilege("system.privilege.admin");
    // see kAuthorizationRightExecute in the AuthorizationTags.h from Security.framework
    int count = 0;
    boolean succeed = false;
    do {
      try {
        auth.authorize(priv, true);
        succeed = true;
        break;
      } catch (Throwable t) {
        System.out.println("Throwable " + t);
      }
      count++;
    } while (count <= 3);

    if (succeed) {
      String preinstallPath = createTemporaryPreinstallFile();
      if (preinstallPath == null) return;
      String[] progArray = {preinstallPath, System.getProperty("user.name")};
      try {
        Process p = auth.execPrivileged(progArray);
        Thread.sleep(1000L);
      } catch (Throwable t) {
        System.out.println("Throwable " + t);
        t.printStackTrace();
      }
    }
  }
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
Example #5
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
  public static void main(String[] args) {
    try {
      COConfigurationManager.initialise();

      boolean v6 = true;

      // Test connectivity.
      if (true) {
        // System.out.println( "UDP:  " + getSingleton().getExternalIpAddressUDP(null,0,v6));
        // System.out.println( "TCP:  " + getSingleton().getExternalIpAddressTCP(null,0,v6));
        // System.out.println( "HTTP: " + getSingleton().getExternalIpAddressHTTP(v6));
      }

      Map data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (pre-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (pre-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");

      System.out.println();
      System.out.print("Initialising core... ");

      /**
       * Suppress all of these errors being displayed in the output.
       *
       * <p>These things should be temporary...
       */
      AzureusCoreImpl.SUPPRESS_CLASSLOADER_ERRORS = true;
      DownloadManagerStateImpl.SUPPRESS_FIXUP_ERRORS = true;

      AzureusCore core = AzureusCoreFactory.create();
      core.start();
      System.out.println("done.");
      System.out.println();
      System.out.println("-----------");

      data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (post-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (post-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");
      System.out.println();

      System.out.print("Shutting down core... ");
      core.stop();
      System.out.println("done.");

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
 boolean _error(Throwable t) throws MongoException {
   if (_allHosts != null) {
     System.out.println("paired mode, switching master b/c of: " + t);
     t.printStackTrace();
     _pickCurrent();
   }
   return true;
 }
  private String lookupFarm() {
    if (Response != null) {

      if (Response.isStillValid()) {

        return Response.getFarmID();
      }

      Response = null;
    }

    try {
      InetAddress CDPServer;
      DatagramSocket Socket;
      CDPQuery Query;
      byte[] Buffer;
      DatagramPacket Packet;

      /* Get the IP address of the CDP servers. */
      CDPServer = InetAddress.getByName(CDPServerName);

      /* Create a UDP socket for the CDP query. */
      Socket = new DatagramSocket();
      Socket.setSoTimeout(CDPTimeout);

      /* Build the CDP query. */
      Query = new CDPQuery(Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);
      Buffer = Query.getBytes();
      Packet = new DatagramPacket(Buffer, Buffer.length, CDPServer, CDPPort);

      /* Send the query to the CDP server. */
      Socket.send(Packet);

      /* Receive the CDP response. */
      Buffer = new byte[CDPResponse.MaxSize];
      Packet.setData(Buffer);
      Socket.receive(Packet);
      if (Packet.getAddress() != CDPServer || Packet.getPort() != CDPPort)
        throw (new Exception("CDP server address mismatch on response"));

      /* Parse the CDP response. */
      Response = new CDPResponse(Packet.getData());

      /* Return the farmID from the CDP response. */
      return Response.getFarmID();
    } catch (Throwable Excpt) {

      if (Excpt instanceof UnknownHostException) {

      } else {

        Excpt.printStackTrace();
      }

      return "default";
    }
  }
  protected void log(String str, Throwable e) {
    if (device_manager == null) {

      System.out.println(str);

      e.printStackTrace();

    } else {

      device_manager.log("TiVo: " + str, e);
    }
  }
Example #10
0
  /**
   * Fired when a control is clicked. This is the equivalent of
   * ActionListener.actionPerformed(ActionEvent e).
   */
  protected void actionPerformed(GuiButton par1GuiButton) {
    if (par1GuiButton.enabled) {
      if (par1GuiButton.id == 5) {
        if (Minecraft.getOs() == EnumOS.MACOS) {
          try {
            this.mc.getLogAgent().logInfo(this.fileLocation);
            Runtime.getRuntime().exec(new String[] {"/usr/bin/open", this.fileLocation});
            return;
          } catch (IOException var7) {
            var7.printStackTrace();
          }
        } else if (Minecraft.getOs() == EnumOS.WINDOWS) {
          String var2 =
              String.format(
                  "cmd.exe /C start \"Open file\" \"%s\"", new Object[] {this.fileLocation});

          try {
            Runtime.getRuntime().exec(var2);
            return;
          } catch (IOException var6) {
            var6.printStackTrace();
          }
        }

        boolean var8 = false;

        try {
          Class var3 = Class.forName("java.awt.Desktop");
          Object var4 =
              var3.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]);
          var3.getMethod("browse", new Class[] {URI.class})
              .invoke(
                  var4,
                  new Object[] {(new File(Minecraft.getMinecraftDir(), "texturepacks")).toURI()});
        } catch (Throwable var5) {
          var5.printStackTrace();
          var8 = true;
        }

        if (var8) {
          this.mc.getLogAgent().logInfo("Opening via system class!");
          Sys.openURL("file://" + this.fileLocation);
        }
      } else if (par1GuiButton.id == 6) {
        this.mc.displayGuiScreen(this.guiScreen);
      } else {
        this.guiTexturePackSlot.actionPerformed(par1GuiButton);
      }
    }
  }
Example #11
0
  private String[] store(String names[], long size, int i, NameValueRecord nvr) {
    // store file
    boolean error1 = false;
    while (true) {
      boolean error = false;
      try {
        names = createFileAndStore(names, size, binary, metadata, nvr, true, times, 0);
        // nvr = retrieveMetadata(names[1], times, 0);
      } catch (HoneycombTestException e) {
        flex("store size=" + size + " name=" + (names == null ? "null" : names[0]), e);
        log.log("store problem: " + e.getMessage());
        // e.printStackTrace();
        error = true;
      } catch (Throwable t) {
        flex("store size=" + size + " name=" + (names == null ? "null" : names[0]), t);
        log.log("store: got throwable");
        t.printStackTrace();
        error = true;
      }
      if (error) {
        error1 = true;
        store_retries++;
        sleep(SLEEP);
        continue;
      }
      break;
    }
    if (error1) flog("#E ok\n");

    // save info
    total_files++;
    total_bytes += size;
    store_bytes += size;
    time_store += times[0];
    total_store_time += times[0];

    oids[i] = names[1];
    shas[i] = names[2];
    if (fo != null) {
      String s =
          "" + size + '\t' + names[0] + '\t' + // filename
              names[1] + '\t' + // oid
              names[2] + '\t' + // sha1
              names[3] + '\t' + // store date
              binary + '\t' + metadata + '\t' + times[0] + '\n';
      flog(s);
    }
    return names;
  }
Example #12
0
 /**
  * Try to execute given method on given object. Handles invocation target exceptions. XXX nearly
  * duplicates tryMethod in JGEngine.
  *
  * @return null means method does not exist or returned null/void
  */
 static Object tryMethod(Object o, String name, Object[] args) {
   try {
     Method met = JREEngine.getMethod(o.getClass(), name, args);
     if (met == null) return null;
     return met.invoke(o, args);
   } catch (InvocationTargetException ex) {
     Throwable ex_t = ex.getTargetException();
     ex_t.printStackTrace();
     return null;
   } catch (IllegalAccessException ex) {
     System.err.println("Unexpected exception:");
     ex.printStackTrace();
     return null;
   }
 }
  public static String getStackTrace(Throwable t) {

    String stackTrace = null;

    try {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      t.printStackTrace(pw);
      pw.close();
      sw.close();
      stackTrace = sw.getBuffer().toString();
    } catch (Exception ex) {
    }
    return stackTrace;
  }
  public static void main(String[] args) {
    try {
      TOTorrent torrent =
          TOTorrentFactory.deserialiseFromBEncodedFile(new File("C:\\temp\\test.torrent"));

      CachePeer[] peers = new CLCacheDiscovery().lookup(torrent);

      System.out.println("peers=" + peers.length);

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

        System.out.println("    cache: " + peers[i].getAddress() + ":" + peers[i].getPort());
      }
    } catch (Throwable e) {

      e.printStackTrace();
    }
  }
Example #15
0
  public static boolean exec(String cmd) throws Exception {
    int exitVal = -1;
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(new String[] {"/bin/bash", "-c", cmd});

      OutputHandler err = new OutputHandler(proc.getErrorStream(), cmd);
      err.start();

      OutputHandler out = new OutputHandler(proc.getInputStream(), cmd);
      out.start();

      exitVal = proc.waitFor();

    } catch (Throwable t) {
      t.printStackTrace();
    }
    return (exitVal == 0);
  }
Example #16
0
    public void run() {
      String command = null;
      Print.logInfo("Client:OutputThread started");

      while (true) {

        /* wait for commands */
        synchronized (this.cmdList) {
          while ((this.cmdList.size() <= 0) && (getRunStatus() == THREAD_RUNNING)) {
            try {
              this.cmdList.wait(5000L);
            } catch (Throwable t) {
              /*ignore*/
            }
          }
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          command = this.cmdList.remove(0).toString();
        }

        /* send commands */
        try {
          ClientSocketThread.socketWriteLine(this.socket, command);
        } catch (Throwable t) {
          Print.logError("Client:OutputThread - " + t);
          t.printStackTrace();
          break;
        }
      }

      if (getRunStatus() == THREAD_RUNNING) {
        Print.logWarn("Client:OutputThread stopped due to error");
      } else {
        Print.logInfo("Client:OutputThread stopped");
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logInfo("Client:OutputThread stopped");
        this.threadLock.notify();
      }
    }
Example #17
0
  //
  // The main work loop
  //
  public void run() {

    //
    // Poll the Namenode (once every 5 minutes) to find the size of the
    // pending edit log.
    //
    long period = 5 * 60; // 5 minutes
    long lastCheckpointTime = 0;
    if (checkpointPeriod < period) {
      period = checkpointPeriod;
    }

    while (shouldRun) {
      try {
        Thread.sleep(1000 * period);
      } catch (InterruptedException ie) {
        // do nothing
      }
      if (!shouldRun) {
        break;
      }
      try {
        long now = System.currentTimeMillis();

        long size = namenode.getEditLogSize();
        if (size >= checkpointSize || now >= lastCheckpointTime + 1000 * checkpointPeriod) {
          doCheckpoint();
          lastCheckpointTime = now;
        }
      } catch (IOException e) {
        LOG.error("Exception in doCheckpoint: ");
        LOG.error(StringUtils.stringifyException(e));
        e.printStackTrace();
        checkpointImage.imageDigest = null;
      } catch (Throwable e) {
        LOG.error("Throwable Exception in doCheckpoint: ");
        LOG.error(StringUtils.stringifyException(e));
        e.printStackTrace();
        Runtime.getRuntime().exit(-1);
      }
    }
  }
Example #18
0
  public static void main(String[] pArgs) {
    if (pArgs.length < 3) {
      System.out.println("usage: java Client host port boardnum");
      return;
    }

    try {
      Socket lSocket = new Socket(pArgs[0], Integer.parseInt(pArgs[1]));
      PrintWriter lOut = new PrintWriter(lSocket.getOutputStream());
      BufferedReader lIn = new BufferedReader(new InputStreamReader(lSocket.getInputStream()));

      lOut.println(pArgs[2]);
      lOut.flush();

      String lLine = lIn.readLine();

      // read number of rows
      int lNumRows = Integer.parseInt(lLine);

      // now, we should find a path from the player to any goal

      // we've found our solution
      String lMySol =
          SokobanSolver.findSolution(Matrix.tileMatrixFromBufferedReader(lIn, lNumRows));
      // these formats are also valid:
      // String lMySol="URRUULDLLULLDRRRRLDDRURUDLLUR";
      // String lMySol="0 3 3 0 0 2 1 2 2 0 2 2 1 3 3 3 3 2 1 1 3 0 3 0 1 2 2 0 3";

      // send the solution to the server
      lOut.println(lMySol);
      lOut.flush();

      // read answer from the server
      lLine = lIn.readLine();

      System.out.println(lLine);
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Example #19
0
  public void setData(String text) {
    if (text != null && text.length() > 0) {
      InputStream in = null;
      try {
        Object result = null;
        Drawing drawing = createDrawing();
        // Try to read the data using all known input formats.
        for (InputFormat fmt : drawing.getInputFormats()) {
          try {
            fmt.read(in, drawing);
            in = new ByteArrayInputStream(text.getBytes("UTF8"));
            result = drawing;
            break;
          } catch (IOException e) {
            result = e;
          }
        }
        if (result instanceof IOException) {
          throw (IOException) result;
        }

        setDrawing(drawing);
      } catch (Throwable e) {
        getDrawing().removeAllChildren();
        SVGTextFigure tf = new SVGTextFigure();
        tf.setText(e.getMessage());
        tf.setBounds(new Point2D.Double(10, 10), new Point2D.Double(100, 100));
        getDrawing().add(tf);
        e.printStackTrace();
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            ex.printStackTrace();
          }
        }
      }
    }
  }
  void insertButton(Document document, PrintWriter out) {
    String fileName = "netnow3.gif";
    String imgURLString =
        "http://home.netscape.com/comprod/products/navigator/version_3.0/images/" + fileName;

    writeImageToDisk(document, imgURLString, fileName);

    try {
      // Write the HTML for the button
      Tag anchor = new Tag("A");
      anchor.addAttribute("HREF", "http://www.netscape.com");
      Tag anchorEnd = new Tag("A", false);
      Tag img = new Tag("IMG");
      URL imgURL = new URL(document.getWorkDirectoryURL(), fileName);
      img.addAttribute("SRC", imgURL.toString());
      out.print(anchor);
      out.print(img);
      out.print(anchorEnd);
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Example #21
0
  public Integer handleError(ESXX esxx, Context cx, Throwable ex) {
    String title = "ESXX Server Error";
    int code = 500;

    if (ex instanceof ESXXException) {
      code = ((ESXXException) ex).getStatus();
    }

    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);

    out.println(esxx.getHTMLHeader());
    out.println("<h2>" + title + "</h2>");
    out.println("<h3>Unhandled exception: " + ex.getClass().getSimpleName() + "</h3>");
    if (ex instanceof ESXXException
        || ex instanceof javax.xml.stream.XMLStreamException
        || ex instanceof javax.xml.transform.TransformerException) {
      out.println("<p><tt>" + encodeXMLContent(ex.getMessage()) + "</tt></p>");
    } else if (ex instanceof RhinoException) {
      out.println("<pre>");
      out.println(ex.getClass().getSimpleName() + ": " + encodeXMLContent(ex.getMessage()));
      out.println(((RhinoException) ex).getScriptStackTrace(new ESXX.JSFilenameFilter()));
      out.println("</pre>");
    } else {
      out.println("<pre>");
      ex.printStackTrace(out);
      out.println("</pre>");
    }
    out.println(esxx.getHTMLFooter());
    out.close();

    try {
      return handleResponse(
          esxx, cx, new Response(code, "text/html; charset=UTF-8", sw.toString(), null));
    } catch (Exception ex2) {
      // Hmm
      return 20;
    }
  }
Example #22
0
  /** @param args command line arguments */
  public static void main(String[] args) {

    DConnect2 dc;

    for (String url : args) {
      try {
        System.out.println("");
        System.out.println("");
        System.out.println("########################################################");
        System.out.println("\nConnecting to " + url + "\n");
        dc = new DConnect2(url);

        System.out.println("\n- - - - - - - - - - - - - - - - - - -");

        System.out.println("Retrieving DDS:\n");
        DDS dds = dc.getDDS();
        dds.print(System.out);

        System.out.println("\n- - - - - - - - - - - - - - - - - - -");
        System.out.println("Retrieving DAS:\n");
        DAS das = dc.getDAS();
        das.print(System.out);

        System.out.println("\n- - - - - - - - - - - - - - - - - - -");
        System.out.println("Retrieving DATA:\n");
        dds = dc.getData("");
        dds.printVal(System.out, "");

        System.out.println("\n- - - - - - - - - - - - - - - - - - -");
        System.out.println("Retrieving DDX:\n");
        dds = dc.getDDX();
        dds.printXML(System.out);

      } catch (Throwable t) {
        t.printStackTrace(System.err);
      }
    }
  }
Example #23
0
  /** Stand alone testing. */
  public static void main(String[] args) {
    try {
      JFrame frame = new JFrame("JargonTree");
      JargonTree tree = new JargonTree(args, null);

      JScrollPane pane = new JScrollPane(tree);
      pane.setPreferredSize(new Dimension(800, 600));

      frame.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
              System.exit(0);
            }
          });
      frame.getContentPane().add(pane, BorderLayout.NORTH);
      frame.pack();
      frame.show();
      frame.validate();

    } catch (Throwable e) {
      e.printStackTrace();
      System.out.println(((SRBException) e).getStandardMessage());
    }
  }
Example #24
0
  private void readwrite(long s1[], long s2[], int pass) {
    // oids[] should correspond to s1[] going in, s2[] going out
    String[] names = null;
    time_retrieve = 0;
    store_bytes = 0;
    time_store = 0;

    String algorithm_id = algorithms[randIndex(algorithms.length)];
    String content_type = content_types[randIndex(content_types.length)];
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s1.length; i++) {
      String retrieved = null;
      boolean error1 = false;
      long t1 = System.currentTimeMillis();
      while (true) {
        boolean error = false;
        try {
          retrieved = retrieve(oids[i], times, 0);
          time_retrieve += times[0];
          total_retrieve_time += times[0];
        } catch (HoneycombTestException e) {
          flex("retrv " + oids[i], e);
          String s = "#e retrv " + oids[i] + ": " + e.getMessage();
          log.log(s);
          // flog(s + "\n");
          // e.printStackTrace();
          error = true;
        } catch (Throwable t) {
          flex("retrv " + oids[i], t);
          log.log("retrieve got throwable");
          t.printStackTrace();
          error = true;
        }
        if (error) {
          error1 = true;
          retrieve_retries++;
          if (System.currentTimeMillis() - t1 > GIVEUP) {
            retrieve_failures++;
            retrieved = null;
            break;
          }
          sleep(SLEEP);
          continue;
        }
        break;
      }
      if (retrieved == null) {
        failed_rtrv.add(oids[i]);
      } else {
        if (error1) flog("#E ok\n");
        dot("r");
        // compare retrieved w/ original
        File f = new File(retrieved);
        if (f.length() != s1[i]) {
          bad_file_errors++;
          String s =
              "#e size mismatch ["
                  + oids[i]
                  + "] store/retrieve: "
                  + s1[i]
                  + " / "
                  + f.length()
                  + "\n";
          flog(s);
        } else {
          String sha1sum = null;
          try {
            sha1sum = shell.sha1sum(retrieved);
          } catch (Exception e) {
            e.printStackTrace();
          }
          if (sha1sum != null && !sha1sum.equals(shas[i])) {
            bad_file_errors++;
            String s =
                "#e sha1 mismatch ["
                    + oids[i]
                    + "] store/retrieve: "
                    + shas[i]
                    + " / "
                    + sha1sum
                    + "\n";
            flog(s);
          }
        }
        deleteFile(retrieved);
      }
      // compare mdata
      t1 = System.currentTimeMillis();
      NameValueRecord nvr = null;
      error1 = false;
      while (true) {
        boolean error = false;
        try {
          nvr = retrieveMetadata(oids[i], times, 0);
          md_retrieve_time += times[0];
          md_retrieves++;
        } catch (HoneycombTestException e) {
          flex("md retrv " + oids[i], e);
          String s = "#e md retrv " + oids[i] + ": " + e.getMessage();
          log.log(s);
          // flog(s + "\n");
          // e.printStackTrace();
          error = true;
        } catch (Throwable t) {
          flex("md retrv " + oids[i], t);
          log.log("md retrieve got throwable");
          t.printStackTrace();
          error = true;
        }
        if (error) {
          error1 = true;
          md_retrieve_retries++;
          if (System.currentTimeMillis() - t1 > GIVEUP) {
            md_retrieve_failures++;
            nvr = null;
            flog("#E " + oids[i] + ": giving up\n");
            break;
          }
          sleep(SLEEP);
          continue;
        }
        break;
      }
      if (nvr == null) {
        failed_md_rtrv.add(oids[i]);
      } else {
        if (error1) flog("#E ok\n");
        SystemRecord sr = nvr.getSystemRecord();
        String stored_oid = sr.getObjectIdentifier().toString();
        if (!oids[i].equals(stored_oid)) {
          // one oid looked up another
          sb.append("#e  oid mismatch! ").append(oids[i]);
          sb.append(" / ").append(stored_oid).append("\n");
        }
        String sha2 = nvr.getString("sha1");
        if (sha2 == null) {
          sb.append("#e  no sha1 in metadata\n");
        } else if (!sha2.equals(shas[i])) {
          sb.append("#e  original/md sha:  ").append(shas[i]);
          sb.append(" / ").append(sha2).append("\n");
        }

        checkMD(sb, nvr, "cedars_subject_id", subject_id);
        checkMD(sb, nvr, "cedars_study_id", study_id);
        checkMD(sb, nvr, "cedars_species_id", species_id);
        checkMD(sb, nvr, "cedars_sample_id", sample_id);
        checkMD(sb, nvr, "cedars_collection_date", collection_date);
        checkMD(sb, nvr, "cedars_processing_date", processing_date);
        checkMD(sb, nvr, "cedars_collected_by", collected_by);
        checkMD(sb, nvr, "cedars_processed_by", processed_by);
        checkMD(sb, nvr, "cedars_sample_type", sample_type);
        checkMD(sb, nvr, "cedars_experiment_date", experiment_date);
        checkMD(sb, nvr, "cedars_experiment_number", experiment_number);

        checkMD(sb, nvr, "cedars_scan_number", Integer.toString(i));

        if (pass > 2) {
          checkMD(sb, nvr, "cedars_algorithm_id", prev_algorithm_id);
          checkMD(sb, nvr, "cedars_content_type", prev_content_type);
        }

        if (sb.length() > 0) {
          bad_md_errors++;
          flog("#e md error " + oids[i] + "\n");
          flog(sb.toString());
          sb.setLength(0);
        }
      }

      if (s2 != null) {
        // store next smaller file and save oid
        nvr = createRecord();
        nvr.put("cedars_subject_id", subject_id);
        nvr.put("cedars_study_id", study_id);
        nvr.put("cedars_species_id", species_id);

        nvr.put("cedars_sample_id", sample_id);
        nvr.put("cedars_collection_date", collection_date);
        nvr.put("cedars_processing_date", processing_date);
        nvr.put("cedars_collected_by", collected_by);
        nvr.put("cedars_processed_by", processed_by);
        nvr.put("cedars_sample_type", sample_type);

        nvr.put("cedars_experiment_date", experiment_date);
        nvr.put("cedars_experiment_number", experiment_number);

        nvr.put("cedars_pass", Long.toString(pass));
        nvr.put("cedars_scan_number", Long.toString(i));

        nvr.put("cedars_algorithm_id", algorithm_id);
        nvr.put("cedars_content_type", content_type);

        names = store(names, s2[i], i, nvr);
        oids[i] = names[1];
        dot("s");
      }
    }
    prev_algorithm_id = algorithm_id;
    prev_content_type = content_type;

    if (names != null && names[0] != null) deleteFile(names[0]);
  }
  public InputStream upload() throws ResourceUploaderException {

    try {

      try {
        URL url = new URL(target.toString().replaceAll(" ", "%20"));

        // some authentications screw up without an explicit port number here

        String protocol = url.getProtocol().toLowerCase();

        if (url.getPort() == -1) {

          int target_port;

          if (protocol.equals("http")) {

            target_port = 80;

          } else {

            target_port = 443;
          }

          try {
            String str = target.toString().replaceAll(" ", "%20");

            int pos = str.indexOf("://");

            pos = str.indexOf("/", pos + 4);

            // might not have a trailing "/"

            if (pos == -1) {

              url = new URL(str + ":" + target_port + "/");

            } else {

              url = new URL(str.substring(0, pos) + ":" + target_port + str.substring(pos));
            }

          } catch (Throwable e) {

            Debug.printStackTrace(e);
          }
        }

        url = AddressUtils.adjustURL(url);

        try {
          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, this);
          }

          for (int i = 0; i < 2; i++) {

            try {
              HttpURLConnection con;

              if (url.getProtocol().equalsIgnoreCase("https")) {

                // see ConfigurationChecker for SSL client defaults

                HttpsURLConnection ssl_con = (HttpsURLConnection) url.openConnection();

                // allow for certs that contain IP addresses rather than dns names

                ssl_con.setHostnameVerifier(
                    new HostnameVerifier() {
                      public boolean verify(String host, SSLSession session) {
                        return (true);
                      }
                    });

                con = ssl_con;

              } else {

                con = (HttpURLConnection) url.openConnection();
              }

              con.setRequestMethod("POST");

              con.setRequestProperty(
                  "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);

              con.setDoOutput(true);
              con.setDoInput(true);

              OutputStream os = con.getOutputStream();

              byte[] buffer = new byte[65536];

              while (true) {

                int len = data.read(buffer);

                if (len <= 0) {

                  break;
                }

                os.write(buffer, 0, len);
              }

              con.connect();

              int response = con.getResponseCode();

              if ((response != HttpURLConnection.HTTP_ACCEPTED)
                  && (response != HttpURLConnection.HTTP_OK)) {

                throw (new ResourceUploaderException(
                    "Error on connect for '"
                        + url.toString()
                        + "': "
                        + Integer.toString(response)
                        + " "
                        + con.getResponseMessage()));
              }

              return (con.getInputStream());

            } catch (SSLException e) {

              if (i == 0) {

                if (SESecurityManager.installServerCertificates(url) != null) {

                  // certificate has been installed

                  continue; // retry with new certificate
                }
              }

              throw (e);
            }
          }

          throw (new ResourceUploaderException("Should never get here"));

        } finally {

          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, null);
          }
        }
      } catch (java.net.MalformedURLException e) {

        throw (new ResourceUploaderException(
            "Exception while parsing URL '" + target + "':" + e.getMessage(), e));

      } catch (java.net.UnknownHostException e) {

        throw (new ResourceUploaderException(
            "Exception while initializing download of '"
                + target
                + "': Unknown Host '"
                + e.getMessage()
                + "'",
            e));

      } catch (java.io.IOException e) {

        throw (new ResourceUploaderException(
            "I/O Exception while downloading '" + target + "':" + e.toString(), e));
      }
    } catch (Throwable e) {

      ResourceUploaderException rde;

      if (e instanceof ResourceUploaderException) {

        rde = (ResourceUploaderException) e;

      } else {

        rde = new ResourceUploaderException("Unexpected error", e);
      }

      throw (rde);

    } finally {

      try {
        data.close();

      } catch (Throwable e) {

        e.printStackTrace();
      }
    }
  }
Example #26
0
  public void run() {
    // XXX - Support other IPs
    String announce = meta.getAnnounce();
    String infoHash = urlencode(meta.getInfoHash());
    String peerID = urlencode(coordinator.getID());

    long uploaded = coordinator.getUploaded();
    long downloaded = coordinator.getDownloaded();
    long left = coordinator.getLeft();

    boolean completed = (left == 0);

    try {
      boolean started = false;
      while (!started) {
        try {
          // Send start.
          TrackerInfo info =
              doRequest(announce, infoHash, peerID, uploaded, downloaded, left, STARTED_EVENT);
          Iterator it = info.getPeers().iterator();
          while (it.hasNext()) coordinator.addPeer((Peer) it.next());
          started = true;
        } catch (IOException ioe) {
          // Probably not fatal (if it doesn't last to long...)
          Snark.debug(
              "WARNING: Could not contact tracker at '" + announce + "': " + ioe, Snark.WARNING);
        }

        if (!started && !stop) {
          Snark.debug("         Retrying in one minute...", Snark.DEBUG);
          try {
            // Sleep one minutes...
            Thread.sleep(60 * 1000);
          } catch (InterruptedException interrupt) {
            // ignore
          }
        }
      }

      while (!stop) {
        try {
          // Sleep some minutes...
          Thread.sleep(SLEEP * 60 * 1000);
        } catch (InterruptedException interrupt) {
          // ignore
        }

        if (stop) break;

        uploaded = coordinator.getUploaded();
        downloaded = coordinator.getDownloaded();
        left = coordinator.getLeft();

        // First time we got a complete download?
        String event;
        if (!completed && left == 0) {
          completed = true;
          event = COMPLETED_EVENT;
        } else event = NO_EVENT;

        // Only do a request when necessary.
        if (event == COMPLETED_EVENT
            || coordinator.needPeers()
            || System.currentTimeMillis() > lastRequestTime + interval) {
          try {
            TrackerInfo info =
                doRequest(announce, infoHash, peerID, uploaded, downloaded, left, event);

            Iterator it = info.getPeers().iterator();
            while (it.hasNext()) coordinator.addPeer((Peer) it.next());
          } catch (IOException ioe) {
            // Probably not fatal (if it doesn't last to long...)
            Snark.debug(
                "WARNING: Could not contact tracker at '" + announce + "': " + ioe, Snark.WARNING);
          }
        }
      }
    } catch (Throwable t) {
      Snark.debug("TrackerClient: " + t, Snark.ERROR);
      t.printStackTrace();
    } finally {
      try {
        TrackerInfo info =
            doRequest(announce, infoHash, peerID, uploaded, downloaded, left, STOPPED_EVENT);
      } catch (IOException ioe) {
        /* ignored */
      }
    }
  }
  /**
   * Construct the default version check message.
   *
   * @return message to send
   */
  public static Map constructVersionCheckMessage(String reason) {

    // only send if anonymous-check flag is not set

    boolean send_info = COConfigurationManager.getBooleanParameter("Send Version Info");

    Map message = new HashMap();

    // always send
    message.put("appid", SystemProperties.getApplicationIdentifier());
    message.put("appname", SystemProperties.getApplicationName());
    message.put("version", Constants.AZUREUS_VERSION);

    String sub_ver = Constants.AZUREUS_SUBVER;

    if (sub_ver.length() > 0) {
      message.put("subver", sub_ver);
    }

    if (COConfigurationManager.getBooleanParameter("Beta Programme Enabled")) {

      message.put("beta_prog", "true");
    }

    message.put("ui", COConfigurationManager.getStringParameter("ui", "unknown"));
    message.put("os", Constants.OSName);
    message.put("os_version", System.getProperty("os.version"));
    message.put(
        "os_arch", System.getProperty("os.arch")); // see http://lopica.sourceforge.net/os.html

    boolean using_phe =
        COConfigurationManager.getBooleanParameter("network.transport.encrypted.require");
    message.put("using_phe", using_phe ? new Long(1) : new Long(0));

    // swt stuff
    try {
      Class c = Class.forName("org.eclipse.swt.SWT");

      String swt_platform =
          (String) c.getMethod("getPlatform", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_platform", swt_platform);

      Integer swt_version =
          (Integer) c.getMethod("getVersion", new Class[] {}).invoke(null, new Object[] {});
      message.put("swt_version", new Long(swt_version.longValue()));

      if (send_info) {
        c = Class.forName("org.gudy.azureus2.ui.swt.mainwindow.MainWindow");
        if (c != null) {
          c.getMethod("addToVersionCheckMessage", new Class[] {Map.class})
              .invoke(null, new Object[] {message});
        }
      }
    } catch (ClassNotFoundException e) {
      /* ignore */
    } catch (NoClassDefFoundError er) {
      /* ignore */
    } catch (InvocationTargetException err) {
      /* ignore */
    } catch (Throwable t) {
      t.printStackTrace();
    }

    int last_send_time = COConfigurationManager.getIntParameter("Send Version Info Last Time", -1);
    int current_send_time = (int) (SystemTime.getCurrentTime() / 1000);
    COConfigurationManager.setParameter("Send Version Info Last Time", current_send_time);

    String id = COConfigurationManager.getStringParameter("ID", null);

    if (id != null && send_info) {
      message.put("id", id);

      try {
        byte[] id2 = CryptoManagerFactory.getSingleton().getSecureID();

        message.put("id2", id2);

      } catch (Throwable e) {
      }

      if (last_send_time != -1 && last_send_time < current_send_time) {
        // time since last
        message.put("tsl", new Long(current_send_time - last_send_time));
      }

      message.put("reason", reason);

      String java_version = System.getProperty("java.version");
      if (java_version == null) {
        java_version = "unknown";
      }
      message.put("java", java_version);

      String java_vendor = System.getProperty("java.vm.vendor");
      if (java_vendor == null) {
        java_vendor = "unknown";
      }
      message.put("javavendor", java_vendor);

      long max_mem = Runtime.getRuntime().maxMemory() / (1024 * 1024);
      message.put("javamx", new Long(max_mem));

      String java_rt_name = System.getProperty("java.runtime.name");
      if (java_rt_name != null) {
        message.put("java_rt_name", java_rt_name);
      }

      String java_rt_version = System.getProperty("java.runtime.version");
      if (java_rt_version != null) {
        message.put("java_rt_version", java_rt_version);
      }

      OverallStats stats = StatsFactory.getStats();

      if (stats != null) {

        // long total_bytes_downloaded 	= stats.getDownloadedBytes();
        // long total_bytes_uploaded		= stats.getUploadedBytes();
        long total_uptime = stats.getTotalUpTime();

        // removed due to complaints about anonymous stats collection
        // message.put( "total_bytes_downloaded", new Long( total_bytes_downloaded ) );
        // message.put( "total_bytes_uploaded", new Long( total_bytes_uploaded ) );
        message.put("total_uptime", new Long(total_uptime));
        // message.put( "dlstats", stats.getDownloadStats());
      }

      try {
        NetworkAdminASN current_asn = NetworkAdmin.getSingleton().getCurrentASN();

        String as = current_asn.getAS();

        message.put("ip_as", current_asn.getAS());

        String asn = current_asn.getASName();

        if (asn.length() > 64) {

          asn = asn.substring(0, 64);
        }

        message.put("ip_asn", asn);

      } catch (Throwable e) {

        Debug.out(e);
      }

      // send locale, so we can determine which languages need attention
      message.put("locale", Locale.getDefault().toString());
      String originalLocale =
          System.getProperty("user.language") + "_" + System.getProperty("user.country");
      String variant = System.getProperty("user.variant");
      if (variant != null && variant.length() > 0) {
        originalLocale += "_" + variant;
      }
      message.put("orig_locale", originalLocale);

      // We may want to reply differently if the user is in Beginner mode vs Advanced
      message.put("user_mode", COConfigurationManager.getIntParameter("User Mode", -1));

      Set<String> features = UtilitiesImpl.getFeaturesInstalled();

      if (features.size() > 0) {

        String str = "";

        for (String f : features) {
          str += (str.length() == 0 ? "" : ",") + f;
        }

        message.put("vzfeatures", str);
      }

      try {
        if (AzureusCoreFactory.isCoreAvailable()) {

          // installed plugin IDs
          PluginInterface[] plugins =
              AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaces();

          List pids = new ArrayList();

          List vs_data = new ArrayList();

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

            PluginInterface plugin = plugins[i];

            String pid = plugin.getPluginID();

            String info = plugin.getPluginconfig().getPluginStringParameter("plugin.info");

            // filter out built-in and core ones
            if ((info != null && info.length() > 0)
                || (!pid.startsWith("<")
                    && !pid.startsWith("azbp")
                    && !pid.startsWith("azupdater")
                    && !pid.startsWith("azplatform")
                    && !pids.contains(pid))) {

              if (info != null && info.length() > 0) {

                if (info.length() < 256) {

                  pid += ":" + info;

                } else {

                  Debug.out("Plugin '" + pid + "' reported excessive info string '" + info + "'");
                }
              }

              pids.add(pid);
            }

            Map data =
                plugin.getPluginconfig().getPluginMapParameter("plugin.versionserver.data", null);

            if (data != null) {

              Map payload = new HashMap();

              byte[] data_bytes = BEncoder.encode(data);

              if (data_bytes.length > 16 * 1024) {

                Debug.out(
                    "Plugin '"
                        + pid
                        + "' reported excessive version server data (length="
                        + data_bytes.length
                        + ")");

                payload.put("error", "data too long: " + data_bytes.length);

              } else {

                payload.put("data", data_bytes);
              }

              payload.put("id", pid);
              payload.put("version", plugin.getPluginVersion());

              vs_data.add(payload);
            }
          }
          message.put("plugins", pids);

          if (vs_data.size() > 0) {

            message.put("plugin_data", vs_data);
          }
        }
      } catch (Throwable e) {

        Debug.out(e);
      }
    }

    return message;
  }
 public static void main(String[] args) {
   // Initialize the logger (saves to RMG.log file).
   Logger.initialize();
   initializeSystemProperties();
   try {
     ChemGraph.readForbiddenStructure();
   } catch (IOException e1) {
     System.err.println("PopulateReactions cannot locate forbiddenStructures.txt file");
     e1.printStackTrace();
   }
   ArrheniusKinetics.setAUnits("moles");
   ArrheniusKinetics.setEaUnits("kcal/mol");
   // Creating a new ReactionModelGenerator so I can set the variable temp4BestKinetics
   // and call the new readAndMakePTL and readAndMakePRL methods
   ReactionModelGenerator rmg = new ReactionModelGenerator();
   rmg.setSpeciesSeed(new LinkedHashSet());
   // Set Global.lowTemp and Global.highTemp
   // The values of the low/highTemp are not used in the function
   // (to the best of my knowledge).
   // They are necessary for the instances of additionalKinetics,
   // e.g. H2C*-CH2-CH2-CH3 -> H3C-CH2-*CH-CH3
   /*
    * 7Apr2010: The input file will now ask the user for a TemperatureModel and PressureModel (same as the RMG
    * module). The Global .lowTemperature and .highTemperature will automatically be determined
    */
   // Global.lowTemperature = new Temperature(300,"K");
   // Global.highTemperature = new Temperature(1500,"K");
   // Define variable 'speciesSet' to store the species contained in the input file
   LinkedHashSet speciesSet = new LinkedHashSet();
   // Define variable 'reactions' to store all possible rxns between the species in speciesSet
   LinkedHashSet reactions = new LinkedHashSet();
   // Define two string variables 'listOfReactions' and 'listOfSpecies'
   // These strings will hold the list of rxns (including the structure,
   // modified Arrhenius parameters, and source/comments) and the list of
   // species (including the chemkin name and graph), respectively
   String listOfReactions =
       "Arrhenius 'A' parameter has units of: "
           + ArrheniusEPKinetics.getAUnits()
           + ",cm3,s\n"
           + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
           + "Arrhenius 'E' parameter has units of: "
           + ArrheniusEPKinetics.getEaUnits()
           + "\n\n";
   String listOfSpecies = "";
   // Open and read the input file
   try {
     FileReader fr_input = new FileReader(args[0]);
     BufferedReader br_input = new BufferedReader(fr_input);
     // Read in the Database field
     String line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("database")) {
       RMG.extractAndSetDatabasePath(line);
     } else {
       System.err.println("PopulateReactions: Could not" + " locate the Database field");
       System.exit(0);
     }
     // Read in the first line of the input file
     // This line should hold the temperature of the system, e.g.
     // Temperature: 500 (K)
     line = ChemParser.readMeaningfulLine(br_input, true);
     /*
      * Read max atom types (if they exist)
      */
     line = rmg.readMaxAtomTypes(line, br_input);
     /*
      * Read primary thermo libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarythermolibrary")) {
       rmg.readAndMakePTL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryThermoLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     // Read primary transport library
     if (line.toLowerCase().startsWith("primarytransportlibrary"))
       rmg.readAndMakePTransL(br_input);
     else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryTransportLibrary field.\n"
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read the temperature model (must be of length one)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createTModel(line);
     if (rmg.getTempList().size() > 1) {
       System.out.println("Please list only one temperature in the TemperatureModel field.");
       System.exit(0);
     }
     // Set the user's input temperature
     LinkedList tempList = rmg.getTempList();
     systemTemp = ((ConstantTM) tempList.get(0)).getTemperature();
     rmg.setTemp4BestKinetics(systemTemp);
     /*
      * Read the pressure model (must be of length 1)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     rmg.createPModel(line);
     if (rmg.getPressList().size() > 1) {
       System.out.println("Please list only one pressure in the PressureModel field.");
       System.exit(0);
     }
     /*
      * Read the solvation field (if present)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     StringTokenizer st = new StringTokenizer(line);
     // The first line should start with "Solvation", otherwise do nothing and display a message to
     // the user
     if (st.nextToken().startsWith("Solvation")) {
       line = st.nextToken().toLowerCase();
       // The options for the "Solvation" field are "on" or "off" (as of 18May2009), otherwise do
       // nothing and
       // display a message to the user
       // Note: I use "Species.useInChI" because the "Species.useSolvation" updates were not yet
       // committed.
       if (line.equals("on")) {
         Species.useSolvation = true;
         // rmg.setUseDiffusion(true);
         listOfReactions += "Solution-phase chemistry!\n\n";
       } else if (line.equals("off")) {
         Species.useSolvation = false;
         // rmg.setUseDiffusion(false);
         listOfReactions += "Gas-phase chemistry.\n\n";
       } else {
         System.out.println(
             "Error in reading input.txt file:\nThe field 'Solvation' has the options 'on' or 'off'."
                 + "\nPopulateReactions does not recognize: "
                 + line);
         return;
       }
       line = ChemParser.readMeaningfulLine(br_input, true);
     }
     /*
      * Read in the species (name, concentration, adjacency list)
      */
     if (line.toLowerCase().startsWith("speciesstatus")) {
       LinkedHashMap lhm = new LinkedHashMap();
       lhm = rmg.populateInitialStatusListWithReactiveSpecies(br_input);
       speciesSet.addAll(lhm.values());
     }
     /*
      * Read in the inert gas (name, concentration)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("bathgas")) {
       rmg.populateInitialStatusListWithInertSpecies(br_input);
     }
     /*
      * Read in the p-dep options
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("spectroscopicdata")) {
       rmg.setSpectroscopicDataMode(line);
       line = ChemParser.readMeaningfulLine(br_input, true);
       line = rmg.setPressureDependenceOptions(line, br_input);
     }
     /*
      * Read primary kinetic libraries (if they exist)
      */
     if (line.toLowerCase().startsWith("primarykineticlibrary")) {
       rmg.readAndMakePKL(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the PrimaryKineticLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line.toLowerCase().startsWith("reactionlibrary")) {
       rmg.readAndMakeReactionLibrary(br_input);
     } else {
       System.err.println(
           "PopulateReactions: Could not locate the ReactionLibrary field."
               + "Line read was: "
               + line);
       System.exit(0);
     }
     /*
      * Read in verbosity field (if it exists)
      */
     line = ChemParser.readMeaningfulLine(br_input, true);
     if (line != null && line.toLowerCase().startsWith("verbose")) {
       StringTokenizer st2 = new StringTokenizer(line);
       String tempString = st2.nextToken();
       tempString = st2.nextToken();
       tempString = tempString.toLowerCase();
       if (tempString.equals("on") || tempString.equals("true") || tempString.equals("yes"))
         ArrheniusKinetics.setVerbose(true);
     }
     TemplateReactionGenerator rtLibrary = new TemplateReactionGenerator();
     // / THE SERVERY BIT
     ServerSocket Server = new ServerSocket(5000);
     Logger.info("TCPServer Waiting for client on port 5000");
     Logger.info("Switching to quiet mode - only WARNINGS and above will be logged...");
     Logger.setConsoleLevel(jing.rxnSys.Logger.WARNING);
     Logger.setFileLevel(jing.rxnSys.Logger.WARNING);
     while (true) {
       Socket connected = Server.accept();
       Logger.warning(
           " THE CLIENT"
               + " "
               + connected.getInetAddress()
               + ":"
               + connected.getPort()
               + " IS CONNECTED ");
       BufferedReader inFromClient =
           new BufferedReader(new InputStreamReader(connected.getInputStream()));
       inFromClient.mark(4096); // so you can reset up to 4096 characters back.
       PrintWriter outToClient = new PrintWriter(connected.getOutputStream(), true);
       try {
         listOfReactions =
             "Arrhenius 'A' parameter has units of: "
                 + ArrheniusEPKinetics.getAUnits()
                 + ",cm3,s\n"
                 + "Arrhenius 'n' parameter is unitless and assumes Tref = 1K\n"
                 + "Arrhenius 'E' parameter has units of: "
                 + ArrheniusEPKinetics.getEaUnits()
                 + "\n\n";
         listOfSpecies = "";
         // clear old things
         speciesSet.clear();
         reactions.clear();
         /*
          * Read in the species (name, concentration, adjacency list)
          */
         LinkedHashMap lhm = new LinkedHashMap();
         lhm = rmg.populateInitialStatusListWithReactiveSpecies(inFromClient);
         speciesSet.addAll(lhm.values());
         // Check Reaction Library
         ReactionLibrary RL = rmg.getReactionLibrary();
         LibraryReactionGenerator lrg1 = new LibraryReactionGenerator(RL);
         reactions = lrg1.react(speciesSet);
         if (RL != null) {
           System.out.println("Checking Reaction Library " + RL.getName() + " for reactions.");
           Iterator ReactionIter = reactions.iterator();
           while (ReactionIter.hasNext()) {
             Reaction current_reaction = (Reaction) ReactionIter.next();
             System.out.println("Library Reaction: " + current_reaction.toString());
           }
         }
         // Add all reactions found from RMG template reaction generator
         reactions.addAll(rtLibrary.react(speciesSet));
         System.out.println("FINISHED generating template reactions");
         if (!(rmg.getReactionModelEnlarger() instanceof RateBasedRME)) {
           // NOT an instance of RateBasedRME therefore assume RateBasedPDepRME and we're doing
           // pressure
           // dependence
           CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(speciesSet, reactions);
           rmg.setReactionModel(cerm);
           rmg.setReactionGenerator(rtLibrary);
           ReactionSystem rs =
               new ReactionSystem(
                   (TemperatureModel) rmg.getTempList().get(0),
                   (PressureModel) rmg.getPressList().get(0),
                   rmg.getReactionModelEnlarger(),
                   new FinishController(),
                   null,
                   rmg.getPrimaryKineticLibrary(),
                   rmg.getReactionGenerator(),
                   speciesSet,
                   (InitialStatus) rmg.getInitialStatusList().get(0),
                   rmg.getReactionModel(),
                   rmg.getLibraryReactionGenerator(),
                   0,
                   "GasPhase");
           PDepNetwork.reactionModel = rmg.getReactionModel();
           PDepNetwork.reactionSystem = rs;
           // If the reaction structure is A + B = C + D, we are not concerned w/pdep
           Iterator iter = reactions.iterator();
           LinkedHashSet nonPdepReactions = new LinkedHashSet();
           while (iter.hasNext()) {
             Reaction r = (Reaction) iter.next();
             if (FastMasterEqn.isReactionPressureDependent(r)) {
               cerm.categorizeReaction(r.getStructure());
               PDepNetwork.addReactionToNetworks(r);
             } else {
               nonPdepReactions.add(r);
             }
           }
           // Run fame calculation
           PDepKineticsEstimator pDepKineticsEstimator =
               ((RateBasedPDepRME) rmg.getReactionModelEnlarger()).getPDepKineticsEstimator();
           BathGas bathGas = new BathGas(rs);
           for (int numNetworks = 0;
               numNetworks < PDepNetwork.getNetworks().size();
               ++numNetworks) {
             LinkedHashSet allSpeciesInNetwork = new LinkedHashSet();
             PDepNetwork pdepnetwork = PDepNetwork.getNetworks().get(numNetworks);
             LinkedList isomers = pdepnetwork.getIsomers();
             for (int numIsomers = 0; numIsomers < isomers.size(); ++numIsomers) {
               PDepIsomer currentIsomer = (PDepIsomer) isomers.get(numIsomers);
               if (currentIsomer.getNumSpecies() == 2)
                 pdepnetwork.makeIsomerIncluded(currentIsomer);
             }
             pDepKineticsEstimator.runPDepCalculation(pdepnetwork, rs, cerm);
             if (pdepnetwork.getNetReactions().size() > 0) {
               String formatSpeciesName = "%1$-16s\t";
               listOfReactions +=
                   "!PDepNetwork\n"
                       + "!\tdeltaEdown = "
                       + bathGas.getDeltaEdown().getAlpha()
                       + "(T / "
                       + bathGas.getDeltaEdown().getT0()
                       + ")^"
                       + bathGas.getDeltaEdown().getN()
                       + " kJ/mol\n"
                       + "!\tbathgas MW = "
                       + bathGas.getMolecularWeight()
                       + " amu\n"
                       + "!\tbathgas LJ sigma = "
                       + bathGas.getLJSigma()
                       + " meters\n"
                       + "!\tbathgas LJ epsilon = "
                       + bathGas.getLJEpsilon()
                       + " Joules\n"
                       + "!Here are the species and their thermochemistry:\n";
               LinkedList<PDepIsomer> allpdepisomers = pdepnetwork.getIsomers();
               for (int numIsomers = 0; numIsomers < allpdepisomers.size(); ++numIsomers) {
                 LinkedList species = allpdepisomers.get(numIsomers).getSpeciesList();
                 for (int numSpecies = 0; numSpecies < species.size(); ++numSpecies) {
                   Species currentSpec = (Species) species.get(numSpecies);
                   if (!allSpeciesInNetwork.contains(currentSpec)) {
                     listOfReactions +=
                         "!\t"
                             + String.format(formatSpeciesName, currentSpec.getFullName())
                             + currentSpec.getThermoData().toString()
                             + currentSpec.getThermoData().getSource()
                             + "\n";
                     allSpeciesInNetwork.add(currentSpec);
                   }
                 }
                 speciesSet.addAll(species);
               }
               String formatRxnName = "%1$-32s\t";
               listOfReactions +=
                   "!Here are the path reactions and their high-P limit kinetics:\n";
               LinkedList<PDepReaction> pathRxns = pdepnetwork.getPathReactions();
               for (int numPathRxns = 0; numPathRxns < pathRxns.size(); numPathRxns++) {
                 Kinetics[] currentKinetics = pathRxns.get(numPathRxns).getKinetics();
                 for (int numKinetics = 0; numKinetics < currentKinetics.length; ++numKinetics) {
                   listOfReactions +=
                       "!\t"
                           + String.format(
                               formatRxnName,
                               pathRxns.get(numPathRxns).getStructure().toRestartString(true))
                           + currentKinetics[numKinetics].toChemkinString(
                               pathRxns
                                   .get(numPathRxns)
                                   .calculateHrxn(new Temperature(298.0, "K")),
                               new Temperature(298.0, "K"),
                               false)
                           + "\n";
                 }
               }
               listOfReactions += "\n";
               LinkedList<PDepReaction> indivPDepRxns = pdepnetwork.getNetReactions();
               for (int numPDepRxns = 0; numPDepRxns < indivPDepRxns.size(); numPDepRxns++) {
                 listOfReactions += indivPDepRxns.get(numPDepRxns).toRestartString(systemTemp);
               }
               LinkedList<PDepReaction> nonIncludedRxns = pdepnetwork.getNonincludedReactions();
               for (int numNonRxns = 0; numNonRxns < nonIncludedRxns.size(); ++numNonRxns) {
                 listOfReactions += nonIncludedRxns.get(numNonRxns).toRestartString(systemTemp);
               }
             }
           }
           reactions = nonPdepReactions;
         }
         // Some of the reactions may be duplicates of one another
         // (e.g. H+CH4=CH3+H2 as a forward reaction and reverse reaction)
         // Create new LinkedHashSet which will store the non-duplicate rxns
         LinkedHashSet nonDuplicateRxns = new LinkedHashSet();
         int Counter = 0;
         Iterator iter_rxns = reactions.iterator();
         while (iter_rxns.hasNext()) {
           ++Counter;
           Reaction r = (Reaction) iter_rxns.next();
           // The first reaction is not a duplicate of any previous reaction
           if (Counter == 1) {
             nonDuplicateRxns.add(r);
             listOfReactions += writeOutputString(r, rtLibrary);
             speciesSet.addAll(r.getProductList());
           }
           // Check whether the current reaction (or its reverse) has the same structure
           // of any reactions already reported in the output
           else {
             Iterator iterOverNonDup = nonDuplicateRxns.iterator();
             boolean dupRxn = false;
             while (iterOverNonDup.hasNext()) {
               Reaction temp_Reaction = (Reaction) iterOverNonDup.next();
               if (r.getStructure() == temp_Reaction.getStructure()) {
                 dupRxn = true;
                 break;
               } else if (r.hasReverseReaction()) {
                 if (r.getReverseReaction().getStructure() == temp_Reaction.getStructure()) {
                   dupRxn = true;
                   break;
                 }
               }
             }
             if (!dupRxn) {
               nonDuplicateRxns.add(r);
               // If Reaction is Not a Library Reaction
               listOfReactions += writeOutputString(r, rtLibrary);
               speciesSet.addAll(r.getProductList());
             }
           }
         }
         Iterator iter_species = speciesSet.iterator();
         // Define dummy integer 'i' so our getChemGraph().toString()
         // call only returns the graph
         int i = 0;
         while (iter_species.hasNext()) {
           Species species = (Species) iter_species.next();
           listOfSpecies +=
               species.getFullName() + "\n" + species.getChemGraph().toStringWithoutH(i) + "\n";
         }
         // Write the output files
         try {
           File rxns = new File("PopRxnsOutput_rxns.txt");
           FileWriter fw_rxns = new FileWriter(rxns);
           fw_rxns.write(listOfReactions);
           fw_rxns.close();
           File spcs = new File("PopRxnsOutput_spcs.txt");
           FileWriter fw_spcs = new FileWriter(spcs);
           fw_spcs.write(listOfSpecies);
           fw_spcs.close();
         } catch (IOException e) {
           System.err.println("Could not write PopRxnsOutput*.txt files");
         }
         // Display to the user that the program was successful and also
         // inform them where the results may be located
         System.out.println(
             "Reaction population complete. "
                 + "Results are stored in PopRxnsOutput_rxns.txt and PopRxnsOutput_spcs.txt");
         // send output to client
         System.out.println("SENDING RESPONSE TO CLIENT");
         outToClient.println(listOfSpecies);
         outToClient.println(listOfReactions);
       } catch (Throwable t) {
         Logger.error("Error in PopulateReactionsServer");
         try {
           inFromClient.reset();
           Logger.error("Input:");
           while (inFromClient.ready()) {
             Logger.error(inFromClient.readLine());
           }
         } catch (IOException e) {
           Logger.error("Couldn't read input stream");
         }
         Logger.logStackTrace(t);
         outToClient.println("Error in PopulateReactionsServer");
         t.printStackTrace(outToClient);
       }
       connected.close();
       System.out.println("SOCKET CLOSED");
     }
   } catch (FileNotFoundException e) {
     System.err.println("File was not found!\n");
   } catch (IOException e) {
     System.err.println(
         "IOException: Something maybe wrong with ChemParser.readChemGraph.\n" + e.toString());
   }
 }