public static void writeDbCommand2File(DbCommand cmd, RandomAccessFile randf) throws Exception {
   if (cmd == null) {
     return;
   }
   byte src[] = cmd.encode();
   randf.write((byte) (src.length >> 8));
   randf.write((byte) src.length);
   randf.write(src);
 }
예제 #2
0
  /**
   * Delete an index entry in the idx file of the specified column.
   *
   * @param colname the column's name
   * @param idxPos index entry (line nr) to be deleted
   * @throws Exception
   */
  protected long deleteIndexEntry(String colname, int idxPos) throws Exception {
    long s = System.currentTimeMillis();
    if (!indexExists(colname)) {
      throw new Exception("No index created");
    }
    int pkindex = def.getColPosition(colname);
    if (pkindex == -1) {
      throw new Exception("Column does not exist");
    }
    Integer[] size = def.getSizes();
    int recordSize = idxFixedRecordLength() + size[pkindex];

    indexFile.seek(idxPos * recordSize);
    String sLine = indexFile.readLine();
    String[] parts = sLine.split("#");
    if (Integer.parseInt(parts[0].trim()) != idxPos) {
      throw new Exception("Index not found in index file");
    } else {
      indexFile.seek(idxPos * recordSize + 6);
      String flag = "D";
      indexFile.write(flag.toString().getBytes());
    }
    long e = System.currentTimeMillis();
    return e - s;
  }
 public void setTimestamp(RandomAccessFile ff) throws tinySQLException {
   try {
     java.util.Calendar cal = java.util.Calendar.getInstance();
     cal.setTime(new java.util.Date());
     int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
     int mm = cal.get(java.util.Calendar.MONTH) + 1;
     int yy = cal.get(java.util.Calendar.YEAR);
     yy = yy % 100; // Y2K problem: only 2 digits
     ff.seek(DATE_INDEX);
     ff.write(yy);
     ff.write(mm);
     ff.write(dd);
   } catch (Exception e) {
     throw new tinySQLException(e.getMessage());
   }
 }
예제 #4
0
파일: GIDE.java 프로젝트: rexut/jkcemu
 private void execFormatTrackTask() {
   File file = this.ioFile;
   long pos = this.ioFilePos;
   int cnt = this.ioByteCnt;
   if ((file != null) && (pos >= 0) && (cnt > 0)) {
     boolean err = false;
     RandomAccessFile raf = null;
     try {
       raf = new RandomAccessFile(file, "rw");
       raf.seek(pos);
       while (cnt > 0) {
         raf.write(0);
         --cnt;
       }
       raf.close();
       raf = null;
     } catch (IOException ex) {
       err = true;
       if (!this.writeErrShown) {
         this.writeErrShown = true;
         EmuUtil.fireShowError(this.owner, null, ex);
       }
     } finally {
       EmuUtil.doClose(raf);
     }
     if (err) {
       this.errorReg = ERROR_UNCORRECTABLE_DATA;
       this.statusReg |= STATUS_ERROR;
     }
     fireInterrupt();
   }
 }
예제 #5
0
  /** Met dans le cache le résultat de l'url indiquée */
  public boolean putInCache(String url) throws Exception {

    // Lecture
    MyInputStream in = null;
    try {
      in = Util.openStream(url);
      byte buf[] = in.readFully();

      // Nettoyage et Ecriture
      String id = codage(url);
      File g = new File(dir + Util.FS + id);
      g.delete();
      RandomAccessFile f = null;
      try {
        f = new RandomAccessFile(dir + Util.FS + id, "rw");
        f.write(buf);
      } finally {
        if (f != null) f.close();
      }
      aladin.trace(3, "Put in cache [" + url + "]");
      return true;
    } catch (Exception e) {
      if (aladin.levelTrace >= 3) e.printStackTrace();
    } finally {
      if (in != null) in.close();
    }

    return false;
  }
예제 #6
0
 /* write a chunk data to the region file at specified sector number */
 private void write(int sectorNumber, byte[] data, int length) throws IOException {
   debugln(" " + sectorNumber);
   file.seek(sectorNumber * SECTOR_BYTES);
   file.writeInt(length + 1); // chunk length
   file.writeByte(VERSION_DEFLATE); // chunk version number
   file.write(data, 0, length); // chunk data
 }
  /**
   * Reads a file from the given InputStream and saves it into the local download directory
   *
   * @param in The InputStream from which to read the file
   * @param start The starting byte of the piece that will be downloaded from this peer
   * @param end The end byte (exclusive) of the piece that will be downloaded from this peer
   * @throws java.io.IOException if an error occurs while downloading the file
   */
  private void saveFile(InputStream in, int start, int end) throws IOException {
    if (start >= end) {
      throw new IllegalStateException(
          "Start byte (" + start + ") must be less than the end byte (" + end + ")");
    }

    RandomAccessFile fileOut = null;
    try {
      File downloadFile = new File(Client.downloadDir, _file);
      // Open the file in read/write mode with synchronous content/metadata writing
      fileOut = new RandomAccessFile(downloadFile, "rws");
      fileOut.seek(start);

      byte[] bytes = new byte[_chunkSize];
      int bytesRead;
      int pos = start;
      while ((bytesRead = in.read(bytes, 0, _chunkSize)) >= 0 && pos < end) {
        fileOut.write(bytes, 0, Math.min(bytesRead, end - pos));
        pos += bytesRead;
      }
    } catch (SocketException e) {
      System.err.println(
          "[DownloadFromPeerRunnable] Disconnected from peer at " + _peer.getInetAddress());
      _callback.onFinishChunk(_file, false);
    } finally {
      if (fileOut != null) {
        try {
          fileOut.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
 private static void preallocateTestFile(final String fileName) throws Exception {
   // Create the file on the Indexes Disk and pre-allocate size
   RandomAccessFile file = new RandomAccessFile(indexFileSystemPath + "/" + fileName, "rw");
   for (long i = 0; i < FILE_SIZE; i += PAGE_SIZE) {
     file.write(BLANK_PAGE, 0, PAGE_SIZE);
   }
   file.close();
 }
예제 #9
0
  @Override
  public void run() {
    if (!kmlFile.exists()) {
      return;
    }

    try {
      synchronized (Kml22FileLogger.lock) {
        StringBuilder descriptionNode = new StringBuilder();
        descriptionNode.append("<Placemark><name>");
        descriptionNode.append(description);
        descriptionNode.append("</name><Point><coordinates>");
        descriptionNode.append(String.valueOf(loc.getLongitude()));
        descriptionNode.append(",");
        descriptionNode.append(String.valueOf(loc.getLatitude()));
        descriptionNode.append(",");
        descriptionNode.append(String.valueOf(loc.getAltitude()));
        descriptionNode.append("</coordinates></Point></Placemark>\n");

        BufferedReader bf = new BufferedReader(new FileReader(kmlFile));

        StringBuilder restOfFile = new StringBuilder();
        String currentLine;
        int lineNumber = 1;

        while ((currentLine = bf.readLine()) != null) {
          if (lineNumber > 1) {
            restOfFile.append(currentLine);
            restOfFile.append("\n");
          }

          lineNumber++;
        }

        bf.close();

        RandomAccessFile raf = new RandomAccessFile(kmlFile, "rw");
        raf.seek(255);
        raf.write(descriptionNode.toString().getBytes());
        raf.write(restOfFile.toString().getBytes());
        raf.close();
      }
    } catch (Exception e) {
      Utilities.LogError("Kml22FileLogger.Annotate", e);
    }
  }
 /**
  * Update the header (index 10-11) with the length of one record
  *
  * @param recordLength Length of one data record (row)
  */
 public void setRecordLength(RandomAccessFile ff, int recordLength) throws tinySQLException {
   this.recordLength = recordLength;
   try {
     ff.seek(DBFHeader.LENGTH_OF_REC_INDEX);
     ff.write(Utils.shortToLittleEndian((short) recordLength));
   } catch (Exception e) {
     throw new tinySQLException(e.getMessage());
   }
 }
 /**
  * Update the header (index 4-7) with the new number of records <br>
  * This is the static variant (use it if you don't want to obtain a DBFHeader instance
  *
  * @param New number of records
  */
 public static void writeNumRecords(RandomAccessFile ff, int numRecords) throws tinySQLException {
   try {
     byte[] b = Utils.intToLittleEndian(numRecords);
     ff.seek(NUMBER_OF_REC_INDEX);
     ff.write(b);
   } catch (Exception e) {
     throw new tinySQLException(e.getMessage());
   }
 }
예제 #12
0
 public synchronized int write(byte[] b, int nStart, int nLen) {
   int n = -1;
   try {
     oSavedFile.write(b, nStart, nLen);
     n = nLen;
   } catch (IOException e) {
     e.printStackTrace();
   }
   return n;
 }
 /**
  * Update the header (index 10-11) with the length of one record
  *
  * @param recordLength Length of one data record (row)
  */
 public void setReserved(RandomAccessFile ff) throws tinySQLException {
   try {
     ff.seek(DBFHeader.RESERVED_INDEX);
     byte[] reserved =
         Utils.forceToSize(null, DBFHeader.BULK_SIZE - DBFHeader.RESERVED_INDEX, (byte) 0);
     ff.write(reserved); // padding with \0!
   } catch (Exception e) {
     throw new tinySQLException(e.getMessage());
   }
 }
 /**
  * Update the header (index 8-9) with the new number of records
  *
  * @param numFields number of columns (used to calculate header length)
  */
 public void setHeaderLength(RandomAccessFile ff, int numFields) throws tinySQLException {
   this.numFields = numFields;
   try {
     int headerLength = (DBFHeader.BULK_SIZE + 1) + numFields * DBFHeader.BULK_SIZE;
     ff.seek(DBFHeader.LENGTH_OF_HEADER_INDEX);
     ff.write(Utils.shortToLittleEndian((short) headerLength));
   } catch (Exception e) {
     throw new tinySQLException(e.getMessage());
   }
 }
예제 #15
0
파일: Page.java 프로젝트: code4/ProjectPika
 public void saveChanges() throws IOException {
   if (!dirty) {
     return;
   }
   loadRawData();
   flatten();
   pageFile.seek(offset + HEADER);
   pageFile.write(rawData);
   saveMetaData();
   dirty = false;
 }
예제 #16
0
 static void writeToFile(RandomAccessFile rf, FileSendingFormat ff) {
   synchronized (rf) {
     try {
       System.out.println(">>>>>" + ff.length + " >>>" + ff.ary.length);
       rf.seek(ff.from);
       rf.write(ff.ary, 0, ff.length);
       //                System.out.append(" "+)
     } catch (IOException e) {
       e.printStackTrace();
     } catch (NullPointerException n) {
       n.printStackTrace();
     }
     //            System.out.println("rf "+rf.getFilePointer()+)
   }
 }
예제 #17
0
  private static void encryptFile(File file, EncryptedFormInformation formInfo)
      throws IOException, EncryptionException {
    File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc");

    if (encryptedFile.exists() && !encryptedFile.delete()) {
      throw new IOException(
          "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?");
    }

    // add elementSignatureSource for this file...
    formInfo.appendFileSignatureSource(file);

    RandomAccessFile randomAccessFile = null;
    CipherOutputStream cipherOutputStream = null;
    try {
      Cipher c = formInfo.getCipher();

      randomAccessFile = new RandomAccessFile(encryptedFile, "rws");
      ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
      cipherOutputStream = new CipherOutputStream(encryptedData, c);
      InputStream fin = new FileInputStream(file);
      byte[] buffer = new byte[2048];
      int len = fin.read(buffer);
      while (len != -1) {
        cipherOutputStream.write(buffer, 0, len);
        len = fin.read(buffer);
      }
      fin.close();
      cipherOutputStream.flush();
      cipherOutputStream.close();

      randomAccessFile.write(encryptedData.toByteArray());

      Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName());
    } catch (Exception e) {
      String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName();
      Log.e(t, msg, e);
      e.printStackTrace();
      throw new EncryptionException(msg, e);
    } finally {
      IOUtils.closeQuietly(cipherOutputStream);

      if (randomAccessFile != null) {
        randomAccessFile.close();
      }
    }
  }
예제 #18
0
  private static void truncateBlock(File blockFile, File metaFile, long oldlen, long newlen)
      throws IOException {
    if (newlen == oldlen) {
      return;
    }
    if (newlen > oldlen) {
      throw new IOException(
          "Cannout truncate block to from oldlen (=" + oldlen + ") to newlen (=" + newlen + ")");
    }

    DataChecksum dcs = BlockMetadataHeader.readHeader(metaFile).getChecksum();
    int checksumsize = dcs.getChecksumSize();
    int bpc = dcs.getBytesPerChecksum();
    long n = (newlen - 1) / bpc + 1;
    long newmetalen = BlockMetadataHeader.getHeaderSize() + n * checksumsize;
    long lastchunkoffset = (n - 1) * bpc;
    int lastchunksize = (int) (newlen - lastchunkoffset);
    byte[] b = new byte[Math.max(lastchunksize, checksumsize)];

    RandomAccessFile blockRAF = new RandomAccessFile(blockFile, "rw");
    try {
      // truncate blockFile
      blockRAF.setLength(newlen);

      // read last chunk
      blockRAF.seek(lastchunkoffset);
      blockRAF.readFully(b, 0, lastchunksize);
    } finally {
      blockRAF.close();
    }

    // compute checksum
    dcs.update(b, 0, lastchunksize);
    dcs.writeValue(b, 0, false);

    // update metaFile
    RandomAccessFile metaRAF = new RandomAccessFile(metaFile, "rw");
    try {
      metaRAF.setLength(newmetalen);
      metaRAF.seek(newmetalen - checksumsize);
      metaRAF.write(b, 0, checksumsize);
    } finally {
      metaRAF.close();
    }
  }
예제 #19
0
파일: GIDE.java 프로젝트: rexut/jkcemu
 private void execWriteSectorsTask() {
   File file = this.ioFile;
   long pos = this.ioFilePos;
   if (this.debugLevel > 3) {
     System.out.printf("GIDE io task: write sector, pos=%d", pos);
   }
   if ((file != null) && (pos >= 0)) {
     boolean err = false;
     RandomAccessFile raf = null;
     try {
       raf = new RandomAccessFile(file, "rw");
       raf.seek(pos);
       raf.write(this.ioBuf, 0, SECTOR_SIZE);
       raf.close();
       raf = null;
     } catch (IOException ex) {
       err = true;
       if (!this.writeErrShown) {
         this.writeErrShown = true;
         EmuUtil.fireShowError(this.owner, null, ex);
       }
     } finally {
       EmuUtil.doClose(raf);
     }
     if (err) {
       this.errorReg = ERROR_UNCORRECTABLE_DATA;
       this.statusReg |= STATUS_ERROR;
       if (this.debugLevel > 3) {
         System.out.println("GIDE io task: write sector: error");
       }
     } else {
       this.ioBufPos = 0;
       countSector();
       if (this.sectorCnt > 0) {
         fireInterrupt();
       } else {
         this.statusReg = STATUS_SEEK_COMPLETE | STATUS_DRIVE_READY;
       }
       if (this.debugLevel > 3) {
         System.out.println("GIDE io task: write sector: ok");
       }
     }
   }
 }
  public boolean download(DownloadListener dl) throws Exception {
    // 1) get crcod, cdn, and cookies
    handshake();

    // 2) get XML
    ArrayList<String> paths = parseXML();
    dl.setTotal(getTotal());

    // 3) get pages
    byte[] key = {
      99, 49, 51, 53, 100, 54, 56, 56, 57, 57, 99, 56, 50, 54, 99, 101, 100, 55, 99, 52, 57, 98, 99,
      55, 54, 97, 97, 57, 52, 56, 57, 48
    };
    BlowFishKey bfkey = new BlowFishKey(key);
    for (int i = 0; i < paths.size(); i++) {
      if (dl.isDownloadAborted()) return (true);

      // rid is just a random number from 0-9999
      URL url =
          new URL(
              "http://mangaonweb.com/page.do?cdn="
                  + cdn
                  + "&cpn="
                  + paths.get(i)
                  + "&crcod="
                  + crcod
                  + "&rid="
                  + (int) (Math.random() * 10000));

      byte[] encrypted = downloadByteArray(url);
      bfkey.decrypt(encrypted, 0);

      RandomAccessFile output = new RandomAccessFile(dl.downloadPath(this, i), "rw");
      output.write(encrypted);
      output.close();

      dl.downloadIncrement(this);
    }

    dl.downloadFinished(this);

    return (true);
  }
  @Override
  public int read() throws IOException {
    bitOffset = 0;

    if (streamPos >= raf.length()) {
      int b = is.read();

      if (b < 0) {
        return -1;
      }

      raf.seek(streamPos++);
      raf.write(b);
      return b;
    }

    raf.seek(streamPos++);
    return raf.read();
  }
      public int testWrite(final String fileName) throws Exception {
        RandomAccessFile file = new RandomAccessFile(fileName, "rw");
        final byte[] buffer = new byte[PAGE_SIZE];
        int pos = 0;
        int checkSum = 0;

        for (long i = 0; i < FILE_SIZE; i++) {
          byte b = (byte) i;
          checkSum += b;

          buffer[pos++] = b;
          if (PAGE_SIZE == pos) {
            file.write(buffer, 0, PAGE_SIZE);
            pos = 0;
          }
        }

        file.close();

        return checkSum;
      }
예제 #23
0
 public int luaCB_write(Lua l, LuaPlugin plugin) {
   l.pushNil();
   l.pushNil();
   try {
     long offset = (long) l.checkNumber(2);
     String towrite = l.checkString(3);
     if (towrite == "") {
       l.pushBoolean(true);
       return 1;
     }
     byte[] tmp = new byte[towrite.length()];
     object.seek(offset);
     for (int i = 0; i < towrite.length(); i++) tmp[i] = (byte) towrite.charAt(i);
     object.write(tmp);
     l.pushBoolean(true);
   } catch (IOException e) {
     l.pushBoolean(false);
     l.pushString("IOException: " + e.getMessage());
     return 2;
   }
   return 1;
 }
  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    bitOffset = 0;

    if (streamPos >= raf.length()) {
      int nBytes = is.read(b, off, len);

      if (nBytes < 0) {
        return -1;
      }

      raf.seek(streamPos);
      raf.write(b, off, nBytes);
      streamPos += nBytes;
      return nBytes;
    }

    raf.seek(streamPos);
    int nBytes = raf.read(b, off, len);
    streamPos += nBytes;
    return nBytes;
  }
예제 #25
0
 private void writeToOffset(File file, long offset, byte[] bytes) throws IOException {
   RandomAccessFile f = new RandomAccessFile(file, "rw");
   f.seek(offset);
   f.write(bytes);
   f.close();
 }
예제 #26
0
  public static void main(String[] argv) {

    String victim = "Beginner"; // What's the name of the target?
    int fpointer = 0; // Where are we in the target class file?

    // How on earth do I use this thing?
    if (argv.length != 0) {
      System.out.println("Try \"java Attacker" + "\".");
      System.exit(1);
    }

    // If the target isn't writeable, then forget the whole deal.
    File testit = new File(victim + ".class");
    if (!(testit.canWrite())) {
      System.out.println(victim + ".class must be writeable.  Fix it!");
      System.exit(2);
    }
    try {
      RandomAccessFile target = new RandomAccessFile(victim + ".class", "rw");

      /* Adjust the proper attribute_length and code_length in order to maintain
      the hacked class file's verifiability. */

      // Increase the attacked method's attribute_lenth by 3.
      fpointer = 455;
      target.seek(fpointer);
      int changed_byte = (int) target.readUnsignedByte() + 3;
      target.seek(fpointer);
      target.writeByte(changed_byte);

      // Increase the attacked method's code_length by 3.
      fpointer = 463;
      target.seek(fpointer);
      changed_byte = (int) target.readUnsignedByte() + 3;
      target.seek(fpointer);
      target.writeByte(changed_byte);

      /* Insert the 3 bytes of code to make Beginner.class deviant */

      // Get to where we want to insert code.
      fpointer = 506;
      target.seek(fpointer);

      // Save the remainder of the target class file.
      int diff = (int) target.length() - fpointer;
      byte[] tail = new byte[diff];
      target.read(tail, 0, diff);

      // Insert the 3 bytes.
      target.seek(fpointer);
      target.writeByte(167);
      target.writeByte(255);
      target.writeByte(214);

      // Restore the tail.
      target.write(tail);

      // All the changes are made, so close the file and get out of here
      target.close();
    } catch (IOException ioe) {
    }
  }
예제 #27
0
  @Override
  public void run() {
    try {

      RandomAccessFile raf;

      String dateTimeString = Utilities.GetIsoDateTime(new Date(loc.getTime()));
      String placemarkHead = "<Placemark>\n<gx:Track>\n";
      String placemarkTail = "</gx:Track>\n</Placemark></Document></kml>\n";

      synchronized (Kml22FileLogger.lock) {
        if (!kmlFile.exists()) {
          kmlFile.createNewFile();

          FileOutputStream initialWriter = new FileOutputStream(kmlFile, true);
          BufferedOutputStream initialOutput = new BufferedOutputStream(initialWriter);

          StringBuilder initialXml = new StringBuilder();
          initialXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
          initialXml.append("<kml xmlns=\"http://www.opengis.net/kml/2.2\" ");
          initialXml.append("xmlns:gx=\"http://www.google.com/kml/ext/2.2\" ");
          initialXml.append("xmlns:kml=\"http://www.opengis.net/kml/2.2\" ");
          initialXml.append("xmlns:atom=\"http://www.w3.org/2005/Atom\">");
          initialXml.append("<Document>");
          initialXml.append("<name>").append(dateTimeString).append("</name>\n");

          initialXml.append("</Document></kml>\n");
          initialOutput.write(initialXml.toString().getBytes());
          initialOutput.flush();
          initialOutput.close();

          // New file, so new track segment
          addNewTrackSegment = true;
        }

        if (addNewTrackSegment) {
          raf = new RandomAccessFile(kmlFile, "rw");
          raf.seek(kmlFile.length() - 18);
          raf.write((placemarkHead + placemarkTail).getBytes());
          raf.close();
        }

        StringBuilder coords = new StringBuilder();
        coords.append("\n<when>");
        coords.append(dateTimeString);
        coords.append("</when>\n<gx:coord>");
        coords.append(String.valueOf(loc.getLongitude()));
        coords.append(" ");
        coords.append(String.valueOf(loc.getLatitude()));
        coords.append(" ");
        coords.append(String.valueOf(loc.getAltitude()));
        coords.append("</gx:coord>\n");
        coords.append(placemarkTail);

        raf = new RandomAccessFile(kmlFile, "rw");
        raf.seek(kmlFile.length() - 42);
        raf.write(coords.toString().getBytes());
        raf.close();
        Utilities.LogDebug("Finished writing to KML22 File");
      }

    } catch (Exception e) {
      Utilities.LogError("Kml22FileLogger.Write", e);
    }
  }
예제 #28
0
 public int write(byte[] data, int offset, int length) throws IOException {
   image.write(data, offset, length);
   return length;
 }
예제 #29
0
파일: Receiver.java 프로젝트: bh00t/Sharing
  void write(file x) throws IOException {
    rf.seek(x.start);

    rf.write(x.ary, 0, x.length);
  }
예제 #30
0
  // initiate either a server or a user session
  public void run() {
    if (isDaemon) {
      daemon();
      return;
    }
    ;

    boolean loggedIn = false;
    int i, h1;
    String di, str1, user = "******", user_id = "0";
    InetAddress localNode;
    byte dataBuffer[] = new byte[1024];
    String command = null;
    StringBuffer statusMessage = new StringBuffer(40);
    File targetFile = null;

    try {
      // start mysql
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      this.db_conn = DriverManager.getConnection(db_url);
      this.db_stmt = this.db_conn.createStatement();

      this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')");

      incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout
      remoteNode = incoming.getInetAddress();
      localNode = InetAddress.getLocalHost();

      BufferedReader in =
          new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET));
      PrintWriter out =
          new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true);
      str1 = "220 Flickr FTP Server Ready";
      out.println(str1);
      if (log) System.out.println(remoteNode.getHostName() + " " + str1);

      boolean done = false;
      char dataType = 0;

      while (!done) {
        statusMessage.setLength(0);

        // obtain and tokenize command
        String str = in.readLine();
        if (str == null) break; // EOS reached
        i = str.indexOf(' ');
        if (i == -1) i = str.length();
        command = str.substring(0, i).toUpperCase().intern();
        if (log)
          System.out.print(
              user
                  + "@"
                  + remoteNode.getHostName()
                  + " "
                  + (String) ((command != "PASS") ? str : "PASS ***"));
        str = str.substring(i).trim();

        try {
          if (command == "USER") {

            user = str;
            statusMessage.append("331 Password");

          } else if (command == "PASS") {

            String pass = str;
            String pass_md5 = md5(pass);

            this.db_rs =
                this.db_stmt.executeQuery(
                    "SELECT * FROM users WHERE email='"
                        + user
                        + "' AND password='******'");
            if (this.db_rs.first()) {
              loggedIn = true;
              user_id = this.db_rs.getString("id");
              System.out.println("Account id is " + user_id);
            }

            statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect");

          } else if (!loggedIn) {

            statusMessage.append("530 Not logged in");

          } else if (command == "RETR") {

            statusMessage.append("999 Not likely");

          } else if (command == "STOR") {

            out.println(BINARY_XFER);

            // trim a leading slash off the filename if there is one
            if (str.substring(0, 1).equals("/")) str = str.substring(1);
            String filename = user_id + "_" + str;
            // TODO: sanitise filename
            targetFile = new File(upload_root + "/" + filename);

            RandomAccessFile dataFile = null;
            InputStream inStream = null;
            OutputStream outStream = null;
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
              int amount;
              dataSocket = setupDataLink();

              // ensure timeout on reads.
              dataSocket.setSoTimeout(inactivityTimer);

              dataFile = new RandomAccessFile(targetFile, "rw");

              inStream = dataSocket.getInputStream();
              while ((amount = inStream.read(dataBuffer)) != -1)
                dataFile.write(dataBuffer, 0, amount);

              statusMessage.append(XFER_COMPLETE);

              shell_exec(ingest_path + " " + user_id + " " + filename);
            } finally {
              try {
                if (inStream != null) inStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (outStream != null) outStream.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataFile != null) dataFile.close();
              } catch (Exception e1) {
              }
              ;
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e1) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "REST") {

            statusMessage.append("502 Sorry, no resuming");

          } else if (command == "TYPE") {

            if (Character.toUpperCase(str.charAt(0)) == 'I') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504 Only binary baybee");
            }

          } else if (command == "DELE"
              || command == "RMD"
              || command == "XRMD"
              || command == "MKD"
              || command == "XMKD"
              || command == "RNFR"
              || command == "RNTO"
              || command == "CDUP"
              || command == "XCDUP"
              || command == "CWD"
              || command == "SIZE"
              || command == "MDTM") {

            statusMessage.append("502 None of that malarky!");

          } else if (command == "QUIT") {

            statusMessage.append(COMMAND_OK).append("GOOD BYE");
            done = true;

          } else if (command == "PWD" | command == "XPWD") {

            statusMessage.append("257 \"/\" is current directory");

          } else if (command == "PORT") {

            int lng, lng1, lng2, ip2;
            String a1 = "", a2 = "";
            lng = str.length() - 1;
            lng2 = str.lastIndexOf(",");
            lng1 = str.lastIndexOf(",", lng2 - 1);

            for (i = lng1 + 1; i < lng2; i++) {
              a1 = a1 + str.charAt(i);
            }

            for (i = lng2 + 1; i <= lng; i++) {
              a2 = a2 + str.charAt(i);
            }

            remotePort = Integer.parseInt(a1);
            ip2 = Integer.parseInt(a2);
            remotePort = (remotePort << 8) + ip2;
            statusMessage.append(COMMAND_OK).append(remotePort);

          } else if (command == "LIST" | command == "NLST") {

            try {

              out.println("150 ASCII data");
              dataSocket = setupDataLink();

              PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true);

              if ((command == "NLST")) {
                out2.println(".");
                out2.println("..");
              } else {
                out2.println("total 8.0k");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 .");
                out2.println("dr--r--r-- 1 owner group           213 Aug 26 16:31 ..");
              }

              // socket MUST be closed before signalling EOD
              dataSocket.close();
              dataSocket = null;
              statusMessage.setLength(0);
              statusMessage.append(XFER_COMPLETE);
            } finally {
              try {
                if (dataSocket != null) dataSocket.close();
              } catch (Exception e) {
              }
              ;
              dataSocket = null;
            }

          } else if (command == "NOOP") {

            statusMessage.append(COMMAND_OK);

          } else if (command == "SYST") {

            statusMessage.append("215 UNIX"); // allows NS to do long dir

          } else if (command == "MODE") {

            if (Character.toUpperCase(str.charAt(0)) == 'S') {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "STRU") {

            if (str.equals("F")) {
              statusMessage.append(COMMAND_OK);
            } else {
              statusMessage.append("504");
            }

          } else if (command == "PASV") {

            try {

              int num = 0, j = 0;
              if (passiveSocket != null)
                try {
                  passiveSocket.close();
                } catch (Exception e) {
                }
              ;
              passiveSocket = new ServerSocket(0); // any port

              // ensure timeout on reads.
              passiveSocket.setSoTimeout(inactivityTimer);

              statusMessage.append("227 Entering Passive Mode (");
              String s = localNode.getHostAddress().replace('.', ','); // get host #
              statusMessage.append(s).append(',');
              num = passiveSocket.getLocalPort(); // get port #
              j = (num >> 8) & 0xff;
              statusMessage.append(j);
              statusMessage.append(',');
              j = num & 0xff;
              statusMessage.append(j);
              statusMessage.append(')');
            } catch (Exception e) {
              try {
                if (passiveSocket != null) passiveSocket.close();
              } catch (Exception e1) {
              }
              ;
              passiveSocket = null;
              throw e;
            }

          } else {
            statusMessage.append("502 unimplemented ").append(command);
          }
        }

        // shutdown causes an interruption to be thrown
        catch (InterruptedException e) {
          throw (e);
        } catch (Exception e) // catch all for any errors (including files)
        {
          statusMessage.append(FAULT).append(e.getMessage());
          if (debug) {
            System.out.println("\nFAULT - lastfile " + targetFile);
            e.printStackTrace();
          }
          ;
        }

        // send result status to remote
        out.println(statusMessage);
        if (log) System.out.println("\t" + statusMessage);
      }
    } catch (Exception e) // usually network errors (including timeout)
    {
      if (log) System.out.println("forced instance exit " + e);
      if (debug) e.printStackTrace();
    } finally // exiting server instance
    {
      // tear down mysql
      if (this.db_rs != null) {
        try {
          this.db_rs.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_stmt != null) {
        try {
          this.db_stmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_pstmt != null) {
        try {
          this.db_pstmt.close();
        } catch (SQLException SQLE) {;
        }
      }
      if (this.db_conn != null) {
        try {
          this.db_conn.close();
        } catch (SQLException SQLE) {;
        }
      }

      forceClose();
    }
  }