コード例 #1
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: addNewEntry - user interface
  Purpose: word menu, interacts with user and calls database methods
              to add new entries, prints out results
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void addNewEntry(Database currentThesaurus) {
    System.out.println("\nPlease type the word you would like to add");
    System.out.print(">>");
    // Will accept spaces in words
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // the wood the user wants to add
    String newUserWord = inputScanner.nextLine();

    // checks whether the word was added successfully
    boolean successCheck = currentThesaurus.addEntryFromMenu(newUserWord);
    if (successCheck == true) {
      System.out.println("\n" + newUserWord + " has been " + "added to the thesaurus");
      System.out.println("Would you like to add a synonym for it?");
      System.out.print("type (yes/no) >>");
      // does the user want to add a synonym
      String userResponse = inputScanner.next();
      if (userResponse.equalsIgnoreCase("yes")) {
        // calls the same method that addNewSynonym calls
        currentThesaurus.addSynonymFromMenu(newUserWord);
      } else {
        System.out.println("\nGoing back to the main menu");
      }
    } else {
      System.out.println("\nSorry, that word is already in the thesaurus\n");
      System.out.println("Going back to the main menu");
      // returns to the main menu
    }
  }
コード例 #2
0
ファイル: JokeServer.java プロジェクト: cloera/Joke-Server
 /**
  * * sendResponse checks for the mode of the server and sends a Response object to the client with
  * the appropriate string stored and the client's Cookie.
  *
  * @param clientCookie - Cookie object received by client
  * @param responseToClient - Response object that will be sent to client
  * @param outputObject - Used to write serialized version of object back to client
  * @throws IOException - Thrown if outputObject is interrupted while processing or fails to
  *     process
  */
 static void sendResponse(
     Cookie clientCookie, Response responseToClient, ObjectOutputStream outputObject)
     throws IOException {
   if (mode.getMode() == ServerMode.JOKE) { // If the mode of the server is set to JOKE, send joke
     responseToClient.addResponse(
         joke.say(
             clientCookie
                 .getJokeKey())); // gets joke from Database and stores string in responseToClient
     clientCookie.nextJoke(); // clientCookie increments the index of the joke to be accessed later
     responseToClient.setCookie(clientCookie); // stores clientCookie in responseToClient
     System.out.println("Sending joke response..."); // notify server joke is being sent
     outputObject.writeObject(
         responseToClient); // send a serialized version of Response object to client
   } else if (mode.getMode()
       == ServerMode.PROVERB) { // If the mode of the server is set to PROVERB, send proverb
     responseToClient.addResponse(proverb.say(clientCookie.getProverbKey()));
     clientCookie.nextProverb();
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending proverb response...");
     outputObject.writeObject(
         responseToClient); // send Response object with proverb and client's Cookie to the client
   } else if (mode.getMode()
       == ServerMode
           .MAINTENANCE) { // If the mode of the server is set to MAINTENANCE, notify clients
                           // server is down for maintenance
     responseToClient.addResponse("Joke server temporarily down for maintenance.\n");
     responseToClient.setCookie(clientCookie);
     System.out.println("Sending maintenance response...");
     outputObject.writeObject(
         responseToClient); // send Response object with maintenance message and client's Cookie to
                            // the client
   }
 }
コード例 #3
0
  /** Method declaration */
  public void run() {

    Channel c = init();

    if (c != null) {
      try {
        while (true) {
          String sql = mInput.readUTF();

          mServer.trace(mThread + ":" + sql);

          if (sql == null) {
            break;
          }

          write(mDatabase.execute(sql, c).getBytes());
        }
      } catch (Exception e) {
      }
    }

    try {
      mSocket.close();
    } catch (IOException e) {
    }

    if (mDatabase.isShutdown()) {
      System.out.println("The database is shutdown");
      System.exit(0);
    }
  }
コード例 #4
0
ファイル: FileMenuHandler.java プロジェクト: cglass102/cs212
  /**
   * opens the chosen file, reads in the file, and prints out a receipt
   *
   * @param chosenFile
   */
  private void readSource(File chosenFile) {
    String chosenFileName = chosenFile.getName();
    TextFileInput inFile = new TextFileInput(chosenFileName);
    Container myContentPane = jframe.getContentPane();
    // chosenFile TextArea myTextArea = new TextArea();
    myContentPane.add(myTextArea);

    int count = 0;
    float priceTotal = 0.0f;
    Database db = new Database("database2.txt");
    String[] transaction = new String[100];
    String line = inFile.readLine();
    DecimalFormat df = new DecimalFormat("#00.00");
    while (line != null) {
      StringTokenizer tokenized = new StringTokenizer(line, ",");
      String code = tokenized.nextToken();
      float weight = Float.parseFloat(tokenized.nextToken());
      String name;
      float price;

      try {
        name = db.getName(code);

      } catch (ItemNotFoundException e) {
        name = JOptionPane.showInputDialog(null, "Item " + code + " not found. Enter Name: ");
      }
      try {
        price = db.getPrice(code);
      } catch (ItemNotFoundException e) {
        price =
            Float.valueOf(
                JOptionPane.showInputDialog(
                    null, "Price for " + name + " not found. Enter price: "));
      }
      float itemTotal = weight * price;
      priceTotal += itemTotal;
      transaction[count] =
          name + "\t" + price + "\t" + df.format(weight) + "\t $" + df.format(itemTotal);
      count++;
      line = inFile.readLine();
    } // while
    myTextArea.setText("ITEM: \t PRICE\\LB: \t POUNDS: \t TOTAL:");
    myTextArea.append("\n");
    for (int i = 0; i < count; i++) {
      myTextArea.append(transaction[i]);
      myTextArea.append("\n");
    }
    myTextArea.append("\t\t   TOTAL: $" + df.format(priceTotal));
    jframe.setVisible(true);
  } // openFile
コード例 #5
0
 /**
  * Write the database settings to ./config/db.cfg.
  *
  * @param database the database to write
  */
 public static void writeDatabaseConfig(Database database, String location) {
   try {
     FileWriter fw = new FileWriter(location + "/db.cfg");
     PrintWriter pw = new PrintWriter(fw);
     pw.println("[Databaseconfig]");
     pw.println("name:" + database.getName());
     pw.println("host:" + database.getHost());
     pw.println("port:" + database.getPort());
     pw.println("username:"******"password:" + database.getPassword());
     pw.close();
     fw.close();
   } catch (IOException ioe) {
   }
 }
コード例 #6
0
  // see DbFile.java for javadocs
  public ArrayList<Page> insertTuple(TransactionId tid, Tuple t)
      throws DbException, IOException, TransactionAbortedException {
    // some code goes here
    BufferPool bp = Database.getBufferPool();
    int id = getId(), i, slots;
    ArrayList<Page> retlist = new ArrayList<Page>();
    PageId pid = null;
    HeapPage p = null;
    for (i = 0; i < numPages(); i++) {
      pid = new HeapPageId(id, i);
      p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE);
      slots = p.getNumEmptySlots();
      if (slots > 0) {
        p.insertTuple(t);
        retlist.add(p);
        return retlist;
      }
    }

    // create new page and add tuple to it
    pid = new HeapPageId(id, i);
    raf.setLength(raf.length() + BufferPool.PAGE_SIZE);
    p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE);
    p.insertTuple(t);
    retlist.add(p);
    return retlist;
  }
コード例 #7
0
  public static void main(String[] args) {
    CloudantClient client =
        new CloudantClient("http://username.cloudant.com", "username", "password");
    Database db = client.database("java-searchindex", false);

    Map<String, Object> animals = new HashMap<>();
    animals.put("index", "function(doc){ index(\"default\", doc._id); }");

    Map<String, Object> indexes = new HashMap<>();
    indexes.put("animals", animals);

    Map<String, Object> ddoc = new HashMap<>();
    ddoc.put("_id", "_design/searchindex");
    ddoc.put("indexes", indexes);

    db.save(ddoc);
  }
コード例 #8
0
ファイル: Database.java プロジェクト: Cenadar/InternetCrawler
 public static void saveURL(String URL, InputStream stream) throws IOException {
   File file = new File(Database.convertURLToFileName(URL));
   Path targetPath = file.toPath();
   file.mkdirs();
   if (file.exists()) {
     Files.copy(stream, targetPath, StandardCopyOption.REPLACE_EXISTING);
   }
 }
コード例 #9
0
ファイル: Database.java プロジェクト: Cenadar/InternetCrawler
 public static String getContentURL(String URL) throws IOException {
   File file = new File(Database.convertURLToFileName(URL));
   String content = "";
   if (file.exists() && !file.isDirectory()) {
     content = new String(Files.readAllBytes(file.toPath()));
   }
   return content;
 }
コード例 #10
0
 private Page readPage(int pageNumber)
     throws DbException, TransactionAbortedException, IOException {
   // File == table because we do one file per table
   //	System.out.println("readpage:"+_file.id()+" page:"+pageNumber);
   int tableId = _file.id();
   int pageId = pageNumber;
   //	System.out.println("Page is now "+pageNumber);
   HeapPageId pid = new HeapPageId(tableId, pageId);
   return Database.getBufferPool().getPage(_transactionId, pid, Permissions.READ_ONLY);
 }
コード例 #11
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: removeSynonymFromEntry  - basic user interface
  Purpose: word menu, interacts with user and calls database methods
              to remove synonyms
              real work is done in database
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void removeSynonymFromEntry(Database currentThesaurus) {
    System.out.println("\nPlease type the word you would like to update");
    System.out.print(">>");
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // WHat word does the user want to update?
    String word = inputScanner.nextLine();

    // calls the method where the real work is done
    currentThesaurus.removeSynonymFromMenu(word);
  }
コード例 #12
0
 // see DbFile.java for javadocs
 public Page deleteTuple(TransactionId tid, Tuple t)
     throws DbException, TransactionAbortedException {
   // some code goes here
   BufferPool bp = Database.getBufferPool();
   RecordId rid = t.getRecordId();
   if (rid == null) {
     throw new DbException("Tuple is not a member of this file");
   }
   HeapPage p = (HeapPage) bp.getPage(tid, rid.getPageId(), Permissions.READ_WRITE);
   p.deleteTuple(t);
   return p;
 }
コード例 #13
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: addNewSynonym - basic user interface
  Purpose: word menu, interacts with user and calls database methods
              to add new synonyms
              real work is done in database
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void addNewSynonymToEntry(Database currentThesaurus) {
    System.out.println("\nPlease type the word you would like to update");
    System.out.print(">>");
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // What word does the user want to update?
    String word = inputScanner.nextLine();

    // calls the method where the real work is done
    currentThesaurus.addSynonymFromMenu(word);
    // written that way so code is usable by addNewEntry
  }
コード例 #14
0
ファイル: LoadEmails.java プロジェクト: andrewh-code/stuff
  public static void main(String[] args) {
    // test Database class
    Connection db_connect = null;

    Database dbClass = new Database();

    String db = "test";
    String id = "andrew";
    String pwd = "password";
    String tableName = "";
    String fileName = "";
    // TO DO: figure out how to load file from a place that's not the default mysql data file
    // directory
    String fileDir = "C:\\ProgramData\\MySQL\\MySQL Server 5.6\\data\\";
    String inputFile = "";

    // inputFile = fileDir + args[0];
    inputFile = fileDir + "day1.txt";

    // connect to the database
    dbClass.connectToDB(db, id, pwd);

    // load e-mails into database
    // String sqlFileLoad = "LOAD DATA INFILE '" + inputFile + "' INTO TABLE test.mailing LINES
    // TERMINATED BY '\r\n'";
    String sqlFileLoad =
        "LOAD DATA INFILE 'day1.txt' INTO TABLE test.mailing LINES TERMINATED BY '\r\n'";
    System.out.println("Now loading e-mails into the database using file: " + fileName);

    dbClass.insertStatement(sqlFileLoad);

    System.out.println("Sucessfully inserted e-mails into table " + tableName + "\n");

    // dbClass.dbCommit();
    dbClass.dbDisconnect();
  }
コード例 #15
0
ファイル: BufferPool.java プロジェクト: kheath/CS133-Lab1
  /**
   * Retrieve the specified page with the associated permissions. Will acquire a lock and may block
   * if that lock is held by another transaction.
   *
   * <p>The retrieved page should be looked up in the buffer pool. If it is present, it should be
   * returned. If it is not present, it should be added to the buffer pool and returned. If there is
   * insufficient space in the buffer pool, an page should be evicted and the new page should be
   * added in its place.
   *
   * @param tid the ID of the transaction requesting the page
   * @param pid the ID of the requested page
   * @param perm the requested permissions on the page
   * @throws IOException
   * @throws NoSuchElementException
   */
  public Page getPage(TransactionId tid, PageId pid, Permissions perm)
      throws TransactionAbortedException, DbException, NoSuchElementException, IOException {

    if (this.deadPool.containsKey(pid)) {
      return this.deadPool.get(pid);
    } else {
      if (this.deadPool.size() >= this.numPages) {
        throw new DbException("Too many pages!");
      } else {
        this.deadPool.put(
            pid, Database.getCatalog().getDatabaseFile(pid.getTableId()).readPage(pid));
        return this.deadPool.get(pid);
      }
    }
  }
コード例 #16
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: wordSearchMenu - user interface
  Purpose: word menu, interacts with user and calls database methods
              to search for user input, prints out search results
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void wordSearchMenu(Database currentThesaurus) {
    // basic menu for simple text input
    // should work for any normal circumstances
    System.out.println("\nPlease type the word to be searched for");
    System.out.print(">> ");
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // the word being searched for
    String userInput = inputScanner.nextLine();

    // searches the database for a word

    String returnString = currentThesaurus.searchForWord(userInput);
    // the results of the search
    System.out.println(returnString + "\n");
  }
コード例 #17
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: synonymSearchMenu - user interface
  Purpose: word menu, interacts with user and calls database methods
              to search for user input, prints out search results
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void synonymSearchMenu(Database currentThesaurus) {
    // basic menu for simple text input
    // should work for any normal circumstances
    // because it stores user input into a string
    System.out.println("\nPlease type the synonym to be searched for");
    System.out.print(">> ");
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // Synonym being searched for
    String userInput = inputScanner.nextLine();

    // searches each entry for a matching synonym
    String returnString = currentThesaurus.searchForSynonym(userInput);
    // the results of the search
    System.out.println(returnString + "\n");
  }
コード例 #18
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: removeEntry  - basic user interface
  Purpose: word menu, interacts with user and calls database methods
              to remove entries
              real work is done in database
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void removeEntry(Database currentThesaurus) {
    System.out.println("\nPlease type the word you would like to remove");
    System.out.print(">>");
    // Will accept spaces in words
    // Scanner to take user input
    Scanner inputScanner = new Scanner(System.in);
    // the wood the user wants to add
    String newUserWord = inputScanner.nextLine();

    // checks whether the word was added successfully
    boolean successCheck = currentThesaurus.removeEntryFromMenu(newUserWord);
    if (successCheck) {
      System.out.println("\n" + newUserWord + " has been " + "removed from the thesaurus");
      System.out.println("\nGoing back to the main menu");
    } else {
      System.out.println("Going back to the main menu");
      // returns to the main menu
    }
  }
コード例 #19
0
  /**
   * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set
   * of header bytes indicating the slots of the page that are in use, some number of tuple slots.
   * Specifically, the number of tuples is equal to:
   *
   * <p>floor((BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1))
   *
   * <p>where tuple size is the size of tuples in this database table, which can be determined via
   * {@link Catalog#getTupleDesc}. The number of 8-bit header words is equal to:
   *
   * <p>ceiling(no. tuple slots / 8)
   *
   * <p>
   *
   * @see Database#getCatalog
   * @see Catalog#getTupleDesc
   * @see BufferPool#PAGE_SIZE
   */
  public HeapPage(HeapPageId id, byte[] data) throws IOException {
    this.pid = id;
    this.td = Database.getCatalog().getTupleDesc(id.getTableId());
    this.numSlots = getNumTuples();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    // allocate and read the header slots of this page
    header = new byte[getHeaderSize()];
    for (int i = 0; i < header.length; i++) header[i] = dis.readByte();

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < tuples.length; i++) tuples[i] = readNextTuple(dis, i);
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }
    dis.close();

    setBeforeImage();
  }
コード例 #20
0
  /**
   * Create a HeapPage from a set of bytes of data read from disk. The format of a HeapPage is a set
   * of 32-bit header words indicating the slots of the page that are in use, plus
   * (BufferPool.PAGE_SIZE/tuple size) tuple slots, where tuple size is the size of tuples in this
   * database table, which can be determined via {@link Catalog#getTupleDesc}.
   *
   * <p>The number of 32-bit header words is equal to:
   *
   * <p>(no. tuple slots / 32) + 1
   *
   * <p>
   *
   * @see Database#getCatalog
   * @see Catalog#getTupleDesc
   * @see BufferPool#PAGE_SIZE
   */
  public HeapPage(HeapPageId id, byte[] data) throws IOException {
    this.pid = id;
    this.td = Database.getCatalog().getTupleDesc(id.tableid());
    // this.numSlots = (BufferPool.PAGE_SIZE) / (td.getSize());
    this.numSlots = (BufferPool.PAGE_SIZE * 8) / ((td.getSize() * 8) + 1);
    // System.out.println(this.numSlots);
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    // allocate and read the header slots of this page
    header = new Header(dis);

    try {
      // allocate and read the actual records of this page
      tuples = new Tuple[numSlots];
      for (int i = 0; i < numSlots; i++) {
        tuples[i] = readNextTuple(dis, i);
      }
    } catch (NoSuchElementException e) {
      // e.printStackTrace();
    }

    dis.close();
  }
コード例 #21
0
  /**
   * Method declaration
   *
   * @return
   */
  private Channel init() {

    try {
      mSocket.setTcpNoDelay(true);

      mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream()));
      mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream()));

      String user = mInput.readUTF();
      String password = mInput.readUTF();
      Channel c;

      try {
        mServer.trace(mThread + ":trying to connect user " + user);

        return mDatabase.connect(user, password);
      } catch (SQLException e) {
        write(new Result(e.getMessage()).getBytes());
      }
    } catch (Exception e) {
    }

    return null;
  }
コード例 #22
0
 /**
  * Static method to generate a byte array corresponding to an empty HeapPage. Used to add new,
  * empty pages to the file. Passing the results of this method to the HeapPage constructor will
  * create a HeapPage with no valid tuples in it.
  *
  * @param tableid The id of the table that this empty page will belong to.
  * @return The returned ByteArray.
  */
 public static byte[] createEmptyPageData(int tableid) {
   TupleDesc td = Database.getCatalog().getTupleDesc(tableid);
   // int hb = (((BufferPool.PAGE_SIZE / td.getSize()) / 32) +1) * 4;
   int len = BufferPool.PAGE_SIZE; // + hb;
   return new byte[len]; // all 0
 }
コード例 #23
0
 public void update_table() {
   Database.showDB("transaction", transaction_column, info_data, info_table);
 }
コード例 #24
0
 public void update_table() {
   Database.showDB("member", member_column, info_data, info_table);
 }
コード例 #25
0
ファイル: prog3.java プロジェクト: theraptor42/CS-102
  /*
  Method: mainMenu - user interface
  Purpose: Main menu, interacts with user and directs
              to other sub-menus
  Parameters:
      Database currentThesaurus   the database parsed from the text file
  Returns:
      none
  */
  public static void mainMenu(Database currentThesaurus) {
    // menu command to search for a word
    final int SEARCHFORWORD = 1;
    // menu command to search for a synonym
    final int SEARCHFORSYNONYM = 2;
    // menu command to print the database
    final int PRINTDATABASE = 3;
    // menu command to add a new word
    final int ADDNEWWORD = 4;
    // menu command to add a new synonym
    final int ADDNEWSYNONYM = 5;
    // menu command to remove an entry
    final int REMOVEENTRY = 6;
    // menu command to remove an synonym
    final int REMOVESYNONYM = 7;
    // menu command to end the program
    final int EXIT = 8;

    System.out.println("Welcome to CS-102 Project One: The Thesaurus");
    System.out.println("Written by Caspian Peavyhouse\n");

    // scanner to take user input
    Scanner input = new Scanner(System.in);

    // controls whether the menu will loop on completion
    boolean loopOn = true;
    while (loopOn) // loop controlled by loopOn activation
    // loops menu after failure or success
    {
      try {
        // standard menu
        System.out.println("Available Commands:");
        System.out.println("1: Search for a word");
        System.out.println("2: Search for a synonym");
        System.out.println("3: Print the database");
        System.out.println("4: Add a new word to the thesaurus");
        System.out.println("5: Add a new synonym to a word");
        System.out.println("6: Remove a word from the thesaurus");
        System.out.println("7: Remove a synonym from a word");
        System.out.println("8: Exit");
        System.out.print("Option Number >> ");

        int selection = Integer.parseInt(input.nextLine());
        //

        switch (selection) {
          case SEARCHFORWORD: // Search for a word
            {
              wordSearchMenu(currentThesaurus);
              // calls the word search menu
              break;
            }
          case SEARCHFORSYNONYM: // Search for a synonym
            {
              synonymSearchMenu(currentThesaurus);
              // calls the synonym search menu
              break;
            }
          case PRINTDATABASE: // Print the database
            {
              System.out.println(currentThesaurus.toString());
              // prints the database using databases toString
              break;
            }
          case ADDNEWWORD: // add a new entry
            {
              addNewEntry(currentThesaurus);
              // calls the method to add a new entry
              break;
            }
          case ADDNEWSYNONYM: // add a new synonym to an entry
            {
              addNewSynonymToEntry(currentThesaurus);
              // calls the method to add a new synonym
              break;
            }
          case REMOVEENTRY:
            {
              removeEntry(currentThesaurus);
              // calls the method to remove an entry
              break;
            }
          case REMOVESYNONYM: // add a new synonym to an entry
            {
              removeSynonymFromEntry(currentThesaurus);
              // calls the method to remove a synonym
              break;
            }
          case EXIT: // Exit
            {
              System.out.println("The program will exit now");
              System.exit(0);
            }
          default:
            {
              System.out.println(
                  "Please enter a valid number for " + "the choice of your selection\n\n");
              // will loop though till user gets correct input
            }
        }

        // typeCheck = true; //this line sets mode for either
        // one run through or infinite run till user exits or breaks it
      } catch (NumberFormatException wrongTypeObject) {
        System.out.println("Please enter a valid number for " + "the choice of your selection\n\n");
        // catches when the user input bad data
      }
    }
  }
コード例 #26
0
 @Override
 public void run() {
   Database.load(file);
 }