예제 #1
0
  private String ReadWholeFileToString(String filename) {

    File file = new File(filename);
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file));
      String text = null;

      // repeat until all lines is read
      while ((text = reader.readLine()) != null) {
        contents.append(text).append(System.getProperty("line.separator"));
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // show file contents here
    return contents.toString();
  }
예제 #2
0
  /**
   * Find mod files in the "mods" folder
   *
   * @param modFolder Folder to search
   * @param modFiles List of mod files to load
   */
  protected void findModFiles(File modFolder, LinkedList<File> modFiles) {
    List<String> supportedVerions = Arrays.asList(SUPPORTED_VERSIONS);

    for (File modFile : modFolder.listFiles(this)) {
      try {
        // Check for a version file
        ZipFile modZip = new ZipFile(modFile);
        ZipEntry version = modZip.getEntry("version.txt");

        if (version != null) {
          // Read the version string
          InputStream versionStream = modZip.getInputStream(version);
          BufferedReader versionReader = new BufferedReader(new InputStreamReader(versionStream));
          String strVersion = versionReader.readLine();
          versionReader.close();

          // Only add the mod if the version matches and we were able to successfully add it to the
          // class path
          if (supportedVerions.contains(strVersion) && addURLToClassPath(modFile.toURI().toURL())) {
            modFiles.add(modFile);
          }
        }

        modZip.close();
      } catch (Exception ex) {
        logger.warning(
            "Error enumerating '"
                + modFile.getAbsolutePath()
                + "': Invalid zip file or error reading file");
      }
    }
  }
예제 #3
0
  /** @param args the command line arguments */
  public static void main(String[] args) throws IOException {
    // TODO code application logic here

    Socket socket = null;
    BufferedReader read = null;
    BufferedReader in = null;
    PrintWriter out = null;

    try {
      socket = new Socket("10.151.34.155", 6666);

      read = new BufferedReader(new InputStreamReader(System.in));
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);

    } catch (IOException ex) {
      Logger.getLogger(UTSProgjar.class.getName()).log(Level.SEVERE, null, ex);
    }

    String textToServer;
    while ((textToServer = read.readLine()) != null) {
      out.print(textToServer + "\r\n");
      out.flush();

      String messageFromServer;
      while ((messageFromServer = textToServer = in.readLine()) != null) {
        System.out.println(messageFromServer);
      }
    }

    Integer intToServer;
    while ((intToServer = Integer.parseInt(read.readLine())) != null) {
      out.print(intToServer + "\r\n");
      out.flush();

      String messageFromServer;
      while ((messageFromServer = textToServer = in.readLine()) != null) {
        System.out.println(messageFromServer);
      }
    }

    out.close();
    in.close();
    read.close();
    socket.close();
  }
예제 #4
0
  public String stringQuery(String msgString) {

    jc.out.print(msgString);
    try {
      return bf.readLine();
    } catch (IOException ioe) {
      throw new UIError("Input/Output error!");
    }
  }
예제 #5
0
  public static void main(String[] args) throws Exception {
    Reader trainingFile = null;

    // Process arguments
    int restArgs = commandOptions.processOptions(args);

    // Check arguments
    if (restArgs != args.length) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Unexpected arg " + args[restArgs]);
    }
    if (trainFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --train-file FILE");
    }
    if (modelFileOption.value == null) {
      commandOptions.printUsage(true);
      throw new IllegalArgumentException("Expected --model-file FILE");
    }

    // Get the CRF structure specification.
    ZipFile zipFile = new ZipFile(modelFileOption.value);
    ZipEntry zipEntry = zipFile.getEntry("crf-info.xml");
    CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry));

    StringBuffer crfInfoBuffer = new StringBuffer();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
    String line;
    while ((line = reader.readLine()) != null) {
      crfInfoBuffer.append(line).append('\n');
    }
    reader.close();

    // Create the CRF, and train it.
    CRF4 crf = createCRF(trainFileOption.value, crfInfo);

    // Create a new zip file for our output.  This will overwrite
    // the file we used for input.
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value));

    // Copy the CRF info xml to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-info.xml"));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos));
    writer.write(crfInfoBuffer.toString());
    writer.flush();
    zos.closeEntry();

    // Save the CRF classifier model to the output zip file.
    zos.putNextEntry(new ZipEntry("crf-model.ser"));
    ObjectOutputStream oos = new ObjectOutputStream(zos);
    oos.writeObject(crf);
    oos.flush();
    zos.closeEntry();
    zos.close();
  }
  public void leer() {
    String texto = "";

    try {
      FileReader lector = new FileReader("texto.txt");
      BufferedReader contenido = new BufferedReader(lector);
      while ((texto = contenido.readLine()) != null) {
        System.out.println(texto);
      }
    } catch (Exception e) {
      System.out.println("Error al leer");
    }
  }
  /** @param args */
  public static void main(String[] args) {

    // Welcome
    System.out.println("Welcome to my traffic simulation project.");
    System.out.println("Choose from the following options:");
    System.out.println("start - Start a simulation");
    System.out.println("stop - Stop a simulation");
    System.out.println("0 - clear");
    System.out.println("1 - init null hypothesis");
    System.out.println("2 - init alt hypothesis");
    System.out.println("3 - step 1");
    System.out.println("4 - step n (1000x)");
    System.out.println("5 - step continuous");
    System.out.println("6 - print results");
    System.out.println("exit - Exit the program");
    System.out.println("");

    // simulation initialization
    Simulation s = new Simulation();

    // input initialization
    String command = "";
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    while (!command.equals("exit")) {
      System.out.print("Input: ");
      try {
        command = reader.readLine();
      } catch (IOException e) {
        System.out.println("Invalid input!");
        e.printStackTrace();
      }

      // parse int command
      if (command.matches("\\d+")) {
        mode = Integer.parseInt(command);
      } else {
        // do nothing
      }

      if (command.matches("start")) {
        s.start();
      }

      if (command.matches("stop")) {
        run = false;
      }
    }
  }
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here

    long lNumOfLines = 0;
    List list1 = new ArrayList();

    try {
      FileInputStream fstream = new FileInputStream("n:\\myphd\\dataset\\gps.csv");
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      // Read File Line By Line
      while ((strLine = br.readLine()) != null) {
        // Print the content on the console
        lNumOfLines++;
        list1.add(strLine.trim());
      }
      // Close the input stream
      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    long lTotal = 1000000;
    long numberOfLines = 0;
    long lStep = lTotal / lNumOfLines;
    System.out.println("lTotal:" + lTotal + " numberOfLines:" + numberOfLines + "lStep:" + lStep);
    float fSpeed = 100;
    float newfSpeed = 0;
    for (int iNum = 0; iNum < lStep; iNum++) {
      Random randomGenerator = new Random();
      int randomInt = randomGenerator.nextInt(1000);
      float f = (float) randomInt / 10000.0f;
      System.out.println("Random Int:" + randomInt + " f:" + f);
      if ((randomInt % 2) == 0) {
        newfSpeed = fSpeed + fSpeed * f;
        System.out.println("Even");
      } else {
        newfSpeed = fSpeed - fSpeed * f;
        System.out.println("odd");
      }
      // InsertInstance(fLat,fLon,fAlt,fSpeed,sDate,sTimestamp,sBTAddress,sBTName,sURI);
      System.out.println("generated speed:" + newfSpeed);
    }
  }
예제 #9
0
 private static void checkLogRecords(File log) throws Exception {
   System.out.println("Checking log records in file: " + log);
   FileInputStream in = new FileInputStream(log);
   String EXPECTED_LOG = "SEVERE: Log message 1 string";
   try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
     String line;
     String[] record = new String[2];
     int count = 0;
     int i = 0;
     while ((line = reader.readLine()) != null) {
       line = line.trim();
       System.out.println(line);
       record[i++] = line;
       if (i == 2) {
         i = 0;
         // check log message
         if (!record[1].equals(EXPECTED_LOG)) {
           // it can sometime happen that some static initializer
           // in the system will log an error message - due to e.g.
           // some kind of misconfiguration or system settings.
           // For instance - somethink like:
           //   INFO: currency.properties entry for FR ignored
           //         because the value format is not recognized.
           // instead of failing if we get such an unexpected
           // message, we will simply print that out.
           System.out.println("*** WARNING: Unexpected log: " + record[1]);
           continue;
         }
         count++;
         // check source class name and method
         String[] ss = record[0].split("\\s+");
         int len = ss.length;
         if (!ss[len - 2].equals("SourceClassName") || !ss[len - 1].equals("writeLogRecords")) {
           throw new RuntimeException("Unexpected source: " + ss[len - 2] + " " + ss[len - 1]);
         }
       }
     }
     if (count != 3) {
       throw new RuntimeException("Unexpected number of records: " + count);
     }
   } finally {
     in.close();
   }
 }
  public String getRunData(Run run, String name) {
    File file = new File(getRunDir(run), name);
    String retVal = null;

    if (!file.exists()) return null;

    try {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      StringBuilder builder = new StringBuilder();
      String line = null;

      while ((line = reader.readLine()) != null) {
        builder.append(line);
      }

      reader.close();
      retVal = builder.toString();
    } catch (Exception exp) {
      throw new IllegalArgumentException(
          "Error trying to read data at " + file.getAbsolutePath(), exp);
    }
    return retVal;
  }
  public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
예제 #12
0
  public void parse(Path file) throws IOException {
    clear();
    try (BufferedReader inp = Files.newBufferedReader(file)) {
      String line;
      while ((line = inp.readLine()) != null) {
        if (line.startsWith("Cpu ")) {
          PerfKey key = new PerfKey();
          PerfData data = new PerfData();
          // Cpu  0 NSE-AB         Init Lock Pgs     19          Mem Pages       4194304
          key.cpu = Integer.parseInt(line.substring(4, 6).trim());
          data.memPages = Integer.parseInt(line.substring(62).trim());

          line = inp.readLine();
          // Memory MB      65536  PCBs           12100          Pg Size    16384  Bytes
          if (line == null || !line.startsWith("Memory MB")) {
            throw new IOException("Строка должна начинаться с 'Memory MB': " + line);
          }

          line = inp.readLine();
          // IPUs    4
          if (line == null || !line.startsWith("IPUs")) {
            throw new IOException("Строка должна начинаться с 'IPUs': " + line);
          }

          line = inp.readLine();
          // Format Version:  H07  Data Version:  H07  Subsystem Version:  3
          if (line == null || !line.startsWith("Format Version:")) {
            throw new IOException("Строка должна начинаться с 'Format Version:': " + line);
          }

          line = inp.readLine();
          // Local System \KHAFE1  From   1 Oct 2016,  0:00:01   For   5.1 Minutes
          if (line == null || !line.startsWith("Local System")) {
            throw new IOException("Строка должна начинаться с 'Local System:': " + line);
          }
          key.system = line.substring(13, 21).trim();
          String str = line.substring(28, 49);
          try {
            key.date = DATETIME_SDF.parse(str);
            data.duration = parseDuration(line.substring(56).trim());
          } catch (ParseException e) {
            throw new IOException(
                "Ошибка декодирования строки (Позиция. "
                    + e.getErrorOffset()
                    + "): "
                    + str
                    + ". Строка:"
                    + line,
                e);
          } catch (NumberFormatException e) {
            throw new IOException("Ошибка декодирования строки : " + str + ". Строка:" + line, e);
          }

          line = inp.readLine();
          // ----------------------------------------------------------------------------
          if (line == null || !line.startsWith("---------")) {
            throw new IOException("Строка должна начинаться с '---------:': " + line);
          }

          line = inp.readLine();
          // Cpu-Busy-Time               79.99 %    Dispatches                115,637 /s
          if (line == null || !line.startsWith("Cpu-Busy-Time")) {
            throw new IOException("Строка должна начинаться с 'Cpu-Busy-Time': " + line);
          }
          str = line.substring(25, 33).trim();
          try {
            data.cpuBusyTime = DF.parse(str).floatValue();
          } catch (ParseException e) {
            throw new IOException("Ошибка декодирования Cpu-Busy-Time: " + str, e);
          }

          line = inp.readLine();
          // Cpu-Qtime                   13.89 AQL  Intr-Busy-Time              14.41 %
          if (line == null || !line.startsWith("Cpu-Qtime")) {
            throw new IOException("Строка должна начинаться с 'Cpu-Qtime': " + line);
          }

          line = inp.readLine();
          // Starting-Free-Mem       3,267,922 #    Ending-Free-Mem         3,267,951 #
          if (line == null || !line.startsWith("Starting-Free-Mem")) {
            throw new IOException("Строка должна начинаться с 'Starting-Free-Mem': " + line);
          }
          str = line.substring(55, 73).trim();
          try {
            data.endingFreeMem = DF.parse(str).intValue();
          } catch (ParseException e) {
            throw new IOException("Ошибка декодирования Ending-Free-Mem: " + str, e);
          }

          line = inp.readLine();
          // Swaps                        1.10 /s   Page-Requests                2.19 /s
          if (line == null || !line.startsWith("Swaps")) {
            throw new IOException("Строка должна начинаться с 'Swaps': " + line);
          }

          line = inp.readLine();
          // Disc-IOs                    49.79 /s   Cache-Hits                 946.87 /s
          if (line == null || !line.startsWith("Disc-IOs")) {
            throw new IOException("Строка должна начинаться с 'Disc-IOs': " + line);
          }

          this.stat.addPerfData(key, data);
        }
      }
    }
  }
예제 #13
0
  @Override
  public void run() {
    try {
      socketInput =
          new BufferedReader(
              new InputStreamReader(
                  connectionSocket.getInputStream())); // get the inputstream from other peer
      pieceReader =
          connectionSocket
              .getInputStream(); // return an input stream for reading bytes from this socket.
      socketOutput =
          new DataOutputStream(
              connectionSocket.getOutputStream()); // get the outputstream to others
      // return an output stream for writing bytes to this socket.
    } catch (IOException ex) {
      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // TCP handshake
    if (OtherPeerID != -1) {
      try {
        socketOutput.writeBytes(handshakeMsg);
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }
      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

    } else // ackhandshake
    {

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }

      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

      if (checkHandShakeHeader.equals(handshakeheader)) {

        try { // if it is the right neighbour, write log that peer1 is connected from peer2
          peerProcess.logfile.write(LogWriter.logmsg(1, peerProcess.myPeerID, OtherPeerID));
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {

          socketOutput.writeBytes(handshakeMsg);
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }

    // start transferring
    try {
      while (quited == false
          && (peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainAll() == false
              || peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).obtainAll() == false)) {

        try {
          socketOutput.writeBytes(peerNotExitMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent not quit message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {
            //
          }
        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        // get the corresponding message length, message type and message payload
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else if (msgType != 9) {
          System.out.println(
              "Received message type " + msgType + ", expecting quit/not quit message.");
        } else {
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received not quit message from peer "
                  + OtherPeerID
                  + ".");
        }

        // bitField exchange
        try {
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          socketOutput.writeBytes(haveMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent bitfield message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {}

        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 4) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received bitField message from peer "
                  + OtherPeerID
                  + ".");
          peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
        } else if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else {
          System.out.println(" received message type " + msgType + ", expecting bitField message.");
        }

        if (peerProcess.choked[OtherPeerID % 1000 - 1] == false) {
          try {

            socketOutput.writeBytes(unchokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          try {

            socketOutput.writeBytes(haveMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine();
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 1) {
            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
              while (socketInput.ready() == false) {}
            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {
              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {
                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  try {
                    peerProcess.logfile.write(
                        LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}

                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    if (msgType == 10) {

                      socketOutput.write(piececontent);

                      while (socketInput.ready() == false) {}

                      try {
                        MsgFromOtherPeer = socketInput.readLine();
                      } catch (Exception e) {
                      }
                      RecvdMsg = MsgFromOtherPeer.split("#");
                      msgLen = Integer.parseInt(RecvdMsg[0]);
                      msgType = Integer.parseInt(RecvdMsg[1]);
                      msgPayload = RecvdMsg[2];
                      if (msgType != 10) {
                        System.out.println(
                            "received message type "
                                + msgType
                                + ", expecting channel clear message.");
                      }
                      continue;
                    } else {
                      System.out.println(
                          "received message type "
                              + msgType
                              + ", expecting channel clear message.");
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    try {
                      peerProcess.logfile.write(
                          LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}
                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    int indexFromOther = msgLen;
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    int loadsize = Integer.parseInt(msgPayload);
                    byte[] mspiececon = new byte[loadsize];
                    if (msgType == 7) {
                      if (peerProcess.myPeerID < OtherPeerID) {

                        socketOutput.writeBytes(channelClearMsg);

                        while (pieceReader.available() <= 0) {}

                        int totallen = 0;
                        byte[] c = new byte[1];
                        while (totallen < loadsize) {
                          try {
                            pieceReader.read(c);
                          } catch (Exception e) {
                          }
                          mspiececon[totallen] = c[0];
                          totallen++;
                        }
                        socketOutput.write(piececontent);
                        try {

                          peerProcess.writebackPiece(indexFromOther, mspiececon);
                          peerProcess.logfile.write(
                              LogWriter.logmsg(
                                  8,
                                  peerProcess.myPeerID,
                                  OtherPeerID,
                                  interestedPieceID,
                                  peerProcess
                                      .Peers
                                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                                      .hasHowManyPieces()));

                          if (peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                  .obtainAll()
                              == true) {
                            try {
                              peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                            } catch (Exception e) {
                            }
                          }
                        } catch (IOException ex) {
                          Logger.getLogger(SocketThread.class.getName())
                              .log(Level.SEVERE, null, ex);
                        }

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType != 10) {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                        continue;
                      } else {

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType == 10) {

                          socketOutput.write(piececontent);

                          while (pieceReader.available() <= 0) {}

                          int totallen = 0;
                          byte[] c = new byte[1];
                          while (totallen < loadsize) {
                            try {
                              pieceReader.read(c);
                            } catch (Exception e) {
                            }
                            mspiececon[totallen] = c[0];
                            totallen++;
                          }
                          socketOutput.writeBytes(channelClearMsg);
                          try {

                            peerProcess.writebackPiece(indexFromOther, mspiececon);
                            peerProcess.logfile.write(
                                LogWriter.logmsg(
                                    8,
                                    peerProcess.myPeerID,
                                    OtherPeerID,
                                    interestedPieceID,
                                    peerProcess
                                        .Peers
                                        .elementAt(peerProcess.myPeerID % 1000 - 1)
                                        .hasHowManyPieces()));

                            if (peerProcess
                                    .Peers
                                    .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                    .obtainAll()
                                == true) {
                              try {
                                peerProcess.logfile.write(
                                    LogWriter.logmsg(9, peerProcess.myPeerID));
                              } catch (Exception e) {
                              }
                            }
                          } catch (IOException ex) {
                            Logger.getLogger(SocketThread.class.getName())
                                .log(Level.SEVERE, null, ex);
                          }
                          continue;
                        } else {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                      }
                    } else {
                      System.out.println(
                          "Expecting piecemessage, received message type " + msgType);
                    }

                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  try {

                    MsgFromOtherPeer = socketInput.readLine() + "";
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  int indexFromOther = msgLen;
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  int loadsize = Integer.parseInt(msgPayload);
                  byte[] mspiececon = new byte[loadsize];
                  if (msgType == 7) {
                    socketOutput.writeBytes(channelClearMsg);

                    while (pieceReader.available() <= 0) {}
                    int totallen = 0;
                    byte[] c = new byte[1];
                    while (totallen < loadsize) {
                      try {
                        pieceReader.read(c);
                      } catch (Exception e) {
                      }
                      mspiececon[totallen] = c[0];
                      totallen++;
                    }
                    socketOutput.writeBytes(channelClearMsg);
                    try {

                      peerProcess.writebackPiece(indexFromOther, mspiececon);
                      peerProcess.logfile.write(
                          LogWriter.logmsg(
                              8,
                              peerProcess.myPeerID,
                              OtherPeerID,
                              interestedPieceID,
                              peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % 1000 - 1)
                                  .hasHowManyPieces()));

                      if (peerProcess
                              .Peers
                              .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                              .obtainAll()
                          == true) {
                        try {
                          peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                        } catch (Exception e) {
                        }
                      }
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    continue;
                  } else {
                    System.out.println(
                        "Expecting piece data, received message type" + msgType + ".");
                  }
                }
              }
            }
          } else if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 2) {
              byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
              piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
              try {
                socketOutput.writeBytes(piecemsg);

                while (socketInput.ready() == false) {}

                try {
                  MsgFromOtherPeer = socketInput.readLine();
                } catch (Exception e) {
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 10) {

                  socketOutput.write(piececontent);

                  while (socketInput.ready() == false) {}

                  try {
                    MsgFromOtherPeer = socketInput.readLine();
                  } catch (Exception e) {
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  if (msgType != 10) {
                    System.out.println(
                        "Expecting channel clear message, received message type " + msgType);
                  }
                  continue;
                } else {
                  System.out.println(
                      "Expecting channel clear message, received message type " + msgType);
                }
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              try {
                peerProcess.logfile.write(LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            } else if (msgType == 3) {
              try {

                peerProcess.logfile.write(LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            }
          } else {
            continue;
          }
        } else {
          try {
            socketOutput.writeBytes(chokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine() + "";
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }

            continue;
          } else if (msgType == 1) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }
            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine() + "";
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {

              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {

                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (Exception e) {
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}

                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                int indexFromOther = msgLen;
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                int loadsize = Integer.parseInt(msgPayload);
                byte[] mspiececon = new byte[loadsize];
                if (msgType == 7) {
                  socketOutput.writeBytes(channelClearMsg);

                  while (pieceReader.available() <= 0) {}
                  int totallen = 0;
                  byte[] c = new byte[1];
                  while (totallen < loadsize) {
                    try {
                      pieceReader.read(c);
                    } catch (Exception e) {
                    }
                    mspiececon[totallen] = c[0];
                    totallen++;
                  }
                  socketOutput.writeBytes(channelClearMsg);
                  try {

                    peerProcess.writebackPiece(indexFromOther, mspiececon);
                    peerProcess.logfile.write(
                        LogWriter.logmsg(
                            8,
                            peerProcess.myPeerID,
                            OtherPeerID,
                            interestedPieceID,
                            peerProcess
                                .Peers
                                .elementAt(peerProcess.myPeerID % 1000 - 1)
                                .hasHowManyPieces()));

                    if (peerProcess
                            .Peers
                            .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                            .obtainAll()
                        == true) {
                      try {
                        peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                      } catch (Exception e) {
                      }
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  continue;
                } else {
                  System.out.println("received msg type " + msgType + ", expecting piece data.");
                }
              }

            } else {
              System.out.println("received msg type " + msgType + ", expecting have msg.");
            }
          } else {
            System.out.println("received msg type " + msgType + ", expecting choke/unchoke msg.");
          }
        }
      }
    } catch (Exception ite) {
    }

    if (quited == false) {

      try {
        socketOutput.writeBytes(peerExitMsg);
        System.out.println(
            "Peer " + peerProcess.myPeerID + " sent quit message to peer " + OtherPeerID + ".");
        try {
          Thread.sleep(100);
        } catch (Exception e) {
        }
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    System.out.println(
        "The socket between peer"
            + peerProcess.myPeerID
            + "and peer "
            + OtherPeerID
            + " will disconnect now.\n");
    peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setHasAllPieces();
    peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).setHasAllPieces();
  }
 /**
  * This calls the external Moodle web service.
  *
  * <p>params String containing the parameters of the call.<br>
  * elements NodeList containing name/value pairs of returned XML data.
  *
  * @param params String
  * @return elements NodeList
  * @throws MoodleRestException
  */
 public static NodeList call(String params) throws MoodleRestException {
   NodeList elements = null;
   try {
     URL getUrl = new URL(url);
     HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
     connection.setRequestMethod("POST");
     connection.setRequestProperty("Accept", "application/xml");
     connection.setDoOutput(true);
     OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
     writer.write(params);
     writer.flush();
     writer.close();
     // Used for testing
     StringBuilder buffer = new StringBuilder();
     BufferedReader reader =
         new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line = reader.readLine();
     buffer.append(line).append('\n');
     // FindPath fp=new FindPath();
     InputStream resource =
         ClassLoader.getSystemClassLoader()
             .getResourceAsStream("net/beaconhillcott/moodlerest/EntityInjection.xml");
     BufferedReader entities = new BufferedReader(new InputStreamReader(/*fp.*/ resource));
     String entitiesLine = null;
     while ((entitiesLine = entities.readLine()) != null) {
       // System.out.println(entitiesLine);
       buffer.append(entitiesLine).append('\n');
     }
     entities.close();
     boolean error = false;
     while ((line = reader.readLine()) != null) {
       // System.out.println(line);
       if (error)
         throw new MoodleRestException(
             line.substring(line.indexOf('>') + 1, line.indexOf('<', line.indexOf('>') + 1)));
       if (line.contains("<EXCEPTION")) error = true;
       buffer.append(line).append('\n');
     }
     reader.close();
     if (debug) {
       System.out.println(buffer.toString());
     }
     XPath xpath = XPathFactory.newInstance().newXPath();
     // InputSource source=new InputSource(connection.getInputStream());
     InputSource source = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes()));
     elements = (NodeList) xpath.evaluate("//VALUE", source, XPathConstants.NODESET);
     // Used for testing
     if (debug) {
       for (int i = 0; i < elements.getLength(); i++) {
         String parent =
             elements
                 .item(i)
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getNodeName();
         if (parent.equals("KEY"))
           parent =
               elements
                   .item(i)
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getAttributes()
                   .getNamedItem("name")
                   .getNodeValue();
         String content = elements.item(i).getTextContent();
         String nodeName =
             elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
         System.out.println("parent=" + parent + " nodeName=" + nodeName + " content=" + content);
       }
     }
     connection.disconnect();
   } catch (XPathExpressionException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   }
   return elements;
 }