@Test
 public void shouldGeneratePasswordWithUpperCaseLowerCaseAndNumberCharacterCombination() {
   Password password = new Password(9);
   for (int i = 0; i < 15; i++) {
     assertPassword(password.create());
   }
 }
Exemplo n.º 2
0
 public Password setPassword(String name) {
   Password element = getPassword(name);
   if (element == null) {
     element = new Password();
     element.setName(name);
     this.getPassword().add(element);
   }
   return element;
 }
 @Override
 public Map<String, Credentials> apply(HttpResponse arg0) {
   Map<String, Credentials> serverNameToCredentials = Maps.newHashMap();
   for (Password password : json.apply(arg0).getList()) {
     serverNameToCredentials.put(
         password.getServer().getName(),
         new Credentials(password.getUserName(), password.getPassword()));
   }
   return serverNameToCredentials;
 }
Exemplo n.º 4
0
 void copyPassToClipboard() {
   try {
     Password pw = new Password(new URL(url), mPasswordView.getText().toString());
     MyClipboardManager clipboard = new MyClipboardManager();
     clipboard.copyToClipboard(this, pw.getPassword());
   } catch (MalformedURLException e) {
     e.printStackTrace();
     Toast.makeText(this, "Copying failed", Toast.LENGTH_LONG).show();
   }
 }
Exemplo n.º 5
0
  protected void encodeMarkup(FacesContext context, Password password) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    String clientId = password.getClientId(context);
    boolean disabled = password.isDisabled();

    String inputClass = Password.STYLE_CLASS;
    inputClass = password.isValid() ? inputClass : inputClass + " ui-state-error";
    inputClass = !disabled ? inputClass : inputClass + " ui-state-disabled";
    String styleClass =
        password.getStyleClass() == null ? inputClass : inputClass + " " + password.getStyleClass();

    writer.startElement("input", password);
    writer.writeAttribute("id", clientId, "id");
    writer.writeAttribute("name", clientId, null);
    writer.writeAttribute("type", "password", null);
    writer.writeAttribute("class", styleClass, null);
    if (password.getStyle() != null) {
      writer.writeAttribute("style", password.getStyle(), null);
    }

    String valueToRender = ComponentUtils.getValueToRender(context, password);
    if (!isValueEmpty(valueToRender) && password.isRedisplay()) {
      writer.writeAttribute("value", valueToRender, null);
    }

    renderPassThruAttributes(context, password, HTML.INPUT_TEXT_ATTRS);

    if (disabled) writer.writeAttribute("disabled", "disabled", null);
    if (password.isReadonly()) writer.writeAttribute("readonly", "readonly", null);

    writer.endElement("input");
  }
    @Override
    protected void onPostExecute(String result) {

      // Log.e("Joseph", result);
      Gson gson = new Gson();
      Authorisation auth = gson.fromJson(result, Authorisation.class);

      String error = auth.getError();
      if (error.equals("false")) {
        // User has logged in successfully and api key has been issued
        // Send data to FragmentActivity by hooking into UI event
        APIKEY = auth.getApikey();
        if (mListener != null) {
          String[] authDetails = {auth.getName(), auth.getEmail(), auth.getApikey()};
          mListener.onFragmentInteraction(authDetails);
          Toast.makeText(getActivity(), auth.getMessage(), Toast.LENGTH_SHORT).show();
          // Update the list in the Drawer so that it can show logout

          CloseFragment();
        }
      } else {
        // Login failed because error was returned from service
        registerFailed.setText(auth.getMessage());
        registerFailed.setTextColor(Color.RED);
        Name.setText("");
        Email.setText("");
        Password.setText("");
        ConfirmPassword.setText("");
        Name.requestFocus();
      }
    }
 @Override
 public void serialize(Password password, JsonGenerator jgen, SerializerProvider provider)
     throws IOException {
   if (password != null) {
     jgen.writeString(String.format("%s", password.getValue()));
   }
 }
Exemplo n.º 8
0
  /**
   * Decrypt a partialy file encrypted. Generate a signle file, totally decrypted.
   *
   * @param password String password used to crypt the file
   * @param output String path to the output file
   * @throws FileNotFoundException
   * @throws IOException
   * @throws GeneralSecurityException
   */
  public void decrypt(String password, String output)
      throws FileNotFoundException, IOException, GeneralSecurityException {
    this.prefix = FileUtility.unaggregate(this.file, this.marker);

    // use the API
    Security.addProvider(new BouncyCastleProvider());

    // create a new crypter
    FileCrypter crypter = new FileCrypter();

    // get key to be used from the password
    SecretKeySpec key = Password.getKey(password);

    // decrypt the second file (which is supposed to be crypted)
    crypter.decryptFile(
        key,
        this.file + FileUtility.extension_crypt,
        FileUtility.tmp + this.prefix + "-2" + FileUtility.extension_tmp);

    // recompose the file with an encrypted part in one single file
    FileUtility.recompose(this.prefix, output);

    // clean temporary files
    FileUtility.clean();
  }
Exemplo n.º 9
0
  @Override
  public void decode(FacesContext context, UIComponent component) {
    Password password = (Password) component;

    if (password.isDisabled() || password.isReadonly()) {
      return;
    }

    decodeBehaviors(context, password);

    String submittedValue =
        context.getExternalContext().getRequestParameterMap().get(password.getClientId(context));

    if (submittedValue != null) {
      password.setSubmittedValue(submittedValue);
    }
  }
Exemplo n.º 10
0
  @Test
  public void shouldHashPassword() {

    // sha1(password)
    String password = "******";
    assertThat(
        Password.sha1(password),
        is(
            new byte[] {
              100, 83, -32, 50, 87, -28, 87, 111, 42, 31, 11, 95, 93, -19, 6, -96, 23, -113, 108, -3
            }));

    // sha1(sha1(password))
    assertThat(
        Password.hash(password),
        is(
            new byte[] {
              -15, -114, 55, -84, 56, -54, 39, 1, -84, 107, 56, -19, -54, -116, -74, -110, 13, 55,
              3, 121
            }));
  }
Exemplo n.º 11
0
 /** {@inheritDoc}. */
 public boolean verifyPassword(final Password password) {
   boolean success = false;
   if (password != null) {
     String text = password.getText();
     if (this.ignoreCase) {
       text = text.toLowerCase();
     }
     if (text.indexOf(this.userID) != -1) {
       this.setMessage(String.format("Password contains the user id '%s'", this.userID));
     } else if (this.backwards && text.indexOf(this.reverseUserID) != -1) {
       this.setMessage(
           String.format("Password contains the backwards user id '%s'", this.reverseUserID));
     } else {
       success = true;
     }
   } else {
     this.setMessage("Password cannot be null");
   }
   return success;
 }
Exemplo n.º 12
0
  public static void main(String args[]) {
    MultithreadedServer st = null;
    BootStrap bs = null;
    HttpStartup hs = null;

    int Httpport = 0;
    int Dataport = 0;
    String Dataip = null;
    String LogFile = null;
    String Pass = null;
    int port = 0;

    ConfigReader cd = ConfigReader.getInstance();
    Password cs = Password.getInstance();
    StopServer s = StopServer.getInstance();
    VectorTable v = VectorTable.getInstance();
    HttpClock hc = HttpClock.getInstance();
    StopGossip stop = StopGossip.getInstance();
    KillHeartBeat kill = KillHeartBeat.getInstance();

    if (args.length > 0) {
      if (args[0].equalsIgnoreCase(Constants.HTTP)) {
        Httpport = Integer.parseInt(args[1]);
        Dataport = Integer.parseInt(args[2]);
        Dataip = args[3];
        LogFile = args[4];
        Pass = args[5];

        cd.setup(Httpport, Dataport, Dataip);
        cs.setup(Pass);

        hs = new HttpStartup();
        hs.setupHTTPServer();
        hc.setNewDataServer(Dataip, Dataport);

        st = new MultithreadedServer(LogFile, true);
        s.setInstance(st);

        Thread t = new Thread(st);
        t.start();

        HeartBeat gp = new HeartBeat();
        kill.setInstance(gp);

        Thread h = new Thread(gp);
        h.start();

      } else if (args[0].equalsIgnoreCase(Constants.DATA)) {
        Dataport = Integer.parseInt(args[1]);
        Dataip = args[2];
        port = Integer.parseInt(args[3]);
        LogFile = args[4];
        Pass = args[5];

        cd.setup(Httpport, Dataport, Dataip);
        cs.setup(Pass);

        // adding the ip address and the port of the server which we will be connecting to
        v.addNewVectorClock(Dataip + "," + port, 0);

        // if it is different from our ip address then we will add ours.
        System.out.println(Dataport + "____" + port);
        if (!(cd.getMyip() + "," + Dataport).equals(Dataip + "," + port)) {
          bs = new BootStrap(port);
          bs.setupBEServer();

          System.out.println("Adding 2nd vector");
          System.out.println(cd.getMyip() + "," + Dataport);
          v.addNewVectorClock(cd.getMyip() + "," + Dataport, 0);
        }

        st = new MultithreadedServer(LogFile, false);
        s.setInstance(st);

        Thread t = new Thread(st);
        t.start();

        GossipThread gp = new GossipThread(LogFile);
        stop.setInstance(gp);

        Thread g = new Thread(gp);
        g.start();

      } else {
        System.out.println("Options: HTTP/DATA");
      }
    } else {
      System.out.println("Options: HTTP/DATA");
    }
  }
Exemplo n.º 13
0
  public static void main(String[] args) {

    try {

      // Read arguments
      if (args.length != 3) {
        System.out.println("Usage: PFX <dbdir> <infile> <outfile>");
        System.exit(-1);
      }

      // open input file for reading
      FileInputStream infile = null;
      try {
        infile = new FileInputStream(args[1]);
      } catch (FileNotFoundException f) {
        System.out.println("Cannot open file " + args[1] + " for reading: " + f.getMessage());
        return;
      }
      int certfile = 0;

      // initialize CryptoManager. This is necessary because there is
      // crypto involved with decoding a PKCS #12 file
      CryptoManager.initialize(args[0]);
      CryptoManager manager = CryptoManager.getInstance();

      // Decode the P12 file
      PFX.Template pfxt = new PFX.Template();
      PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(infile, 2048));
      System.out.println("Decoded PFX");

      // print out information about the top-level PFX structure
      System.out.println("Version: " + pfx.getVersion());
      AuthenticatedSafes authSafes = pfx.getAuthSafes();
      SEQUENCE safeContentsSequence = authSafes.getSequence();
      System.out.println("AuthSafes has " + safeContentsSequence.size() + " SafeContents");

      // Get the password for the old file
      System.out.println("Enter password: "******"Enter new password:"******"AuthSafes verifies correctly.");
      } else {
        System.out.println("AuthSafes failed to verify because: " + sb);
      }

      // Create a new AuthenticatedSafes. As we read the contents of the
      // old authSafes, we will store them into the new one.  After we have
      // cycled through all the contents, they will all have been copied into
      // the new authSafes.
      AuthenticatedSafes newAuthSafes = new AuthenticatedSafes();

      // Loop over contents of the old authenticated safes
      // for(int i=0; i < asSeq.size(); i++) {
      for (int i = 0; i < safeContentsSequence.size(); i++) {

        // The safeContents may or may not be encrypted.  We always send
        // the password in.  It will get used if it is needed.  If the
        // decryption of the safeContents fails for some reason (like
        // a bad password), then this method will throw an exception
        SEQUENCE safeContents = authSafes.getSafeContentsAt(pass, i);

        System.out.println("\n\nSafeContents #" + i + " has " + safeContents.size() + " bags");

        // Go through all the bags in this SafeContents
        for (int j = 0; j < safeContents.size(); j++) {
          SafeBag safeBag = (SafeBag) safeContents.elementAt(j);

          // The type of the bag is an OID
          System.out.println("\nBag " + j + " has type " + safeBag.getBagType());

          // look for bag attributes
          SET attribs = safeBag.getBagAttributes();
          if (attribs == null) {
            System.out.println("Bag has no attributes");
          } else {
            for (int b = 0; b < attribs.size(); b++) {
              Attribute a = (Attribute) attribs.elementAt(b);
              if (a.getType().equals(SafeBag.FRIENDLY_NAME)) {
                // the friendly name attribute is a nickname
                BMPString bs =
                    (BMPString)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(BMPString.getTemplate());
                System.out.println("Friendly Name: " + bs);
              } else if (a.getType().equals(SafeBag.LOCAL_KEY_ID)) {
                // the local key id is used to match a key
                // to its cert.  The key id is the SHA-1 hash of
                // the DER-encoded cert.
                OCTET_STRING os =
                    (OCTET_STRING)
                        ((ANY) a.getValues().elementAt(0)).decodeWith(OCTET_STRING.getTemplate());
                System.out.println("LocalKeyID:");
                /*
                                     AuthenticatedSafes.
                                         print_byte_array(os.toByteArray());
                */
              } else {
                System.out.println("Unknown attribute type: " + a.getType().toString());
              }
            }
          }

          // now look at the contents of the bag
          ASN1Value val = safeBag.getInterpretedBagContent();

          if (val instanceof PrivateKeyInfo) {
            // A PrivateKeyInfo contains an unencrypted private key
            System.out.println("content is PrivateKeyInfo");
          } else if (val instanceof EncryptedPrivateKeyInfo) {
            // An EncryptedPrivateKeyInfo is, well, an encrypted
            // PrivateKeyInfo. Usually, strong crypto is used in
            // an EncryptedPrivateKeyInfo.
            EncryptedPrivateKeyInfo epki = ((EncryptedPrivateKeyInfo) val);
            System.out.println(
                "content is EncryptedPrivateKeyInfo, algoid:"
                    + epki.getEncryptionAlgorithm().getOID());

            // Because we are in a PKCS #12 file, the passwords are
            // char-to-byte converted in a special way.  We have to
            // use the special converter class instead of the default.
            PrivateKeyInfo pki = epki.decrypt(pass, new org.mozilla.jss.pkcs12.PasswordConverter());

            // import the key into the key3.db
            CryptoToken tok = manager.getTokenByName("Internal Key Storage Token");
            CryptoStore store = tok.getCryptoStore();
            tok.login(new ConsolePasswordCallback());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            pki.encode(baos);
            store.importPrivateKey(baos.toByteArray(), PrivateKey.RSA);

            // re-encrypt the PrivateKeyInfo with the new password
            // and random salt
            byte[] salt = new byte[PBEAlgorithm.PBE_SHA1_DES3_CBC.getSaltLength()];
            JSSSecureRandom rand = CryptoManager.getInstance().getSecureRNG();
            rand.nextBytes(salt);
            epki =
                EncryptedPrivateKeyInfo.createPBE(
                    PBEAlgorithm.PBE_SHA1_DES3_CBC, newPass, salt, 1, new PasswordConverter(), pki);

            // Overwrite the previous EncryptedPrivateKeyInfo with
            // this new one we just created using the new password.
            // This is what will get put in the new PKCS #12 file
            // we are creating.
            safeContents.insertElementAt(
                new SafeBag(safeBag.getBagType(), epki, safeBag.getBagAttributes()), i);
            safeContents.removeElementAt(i + 1);

          } else if (val instanceof CertBag) {
            System.out.println("content is CertBag");
            CertBag cb = (CertBag) val;
            if (cb.getCertType().equals(CertBag.X509_CERT_TYPE)) {
              // this is an X.509 certificate
              OCTET_STRING os = (OCTET_STRING) cb.getInterpretedCert();
              Certificate cert =
                  (Certificate) ASN1Util.decode(Certificate.getTemplate(), os.toByteArray());
              cert.getInfo().print(System.out);
            } else {
              System.out.println("Unrecognized cert type");
            }
          } else {
            System.out.println("content is ANY");
          }
        }

        // Add the new safe contents to the new authsafes
        if (authSafes.safeContentsIsEncrypted(i)) {
          newAuthSafes.addEncryptedSafeContents(
              authSafes.DEFAULT_KEY_GEN_ALG,
              newPass,
              null,
              authSafes.DEFAULT_ITERATIONS,
              safeContents);
        } else {
          newAuthSafes.addSafeContents(safeContents);
        }
      }

      // Create new PFX from the new authsafes
      PFX newPfx = new PFX(newAuthSafes);

      // Add a MAC to the new PFX
      newPfx.computeMacData(newPass, null, PFX.DEFAULT_ITERATIONS);

      // write the new PFX out to a file
      FileOutputStream fos = new FileOutputStream(args[2]);
      newPfx.encode(fos);
      fos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @Override
 public int compareTo(Password o) {
   return server.getName().compareTo(o.getServer().getName());
 }
Exemplo n.º 15
0
  /**
   * opens a new instance of Autoexplorer browser and attaches listeners.
   *
   * @throws FileNotFoundException
   * @throws IOException
   */
  void open() throws FileNotFoundException, IOException {

    // Call setup to get global settings and check if this is the first run.
    File settings = new File(settingsPath);
    if (!settings.isDirectory()) {
      // then this is the first run...call setup
      Setup firstrun = new Setup(this, ax);
    } else {
      // Get the settings from the file, if the file has dissappeared since
      // first setup, recreate.
      InputStream in = null;
      try {

        File sFile = new File("c:\\AE\\settings\\setting.txt");
        if (!sFile.exists()) {
          System.out.println("Creating Settings File with defaults.");
          sFile.createNewFile();
          Writer w = new FileWriter(sFile);
          w.append("Password:password:Homepage:www.google.com:Runs:1\n");
          w.close();
        }
        in = new FileInputStream("c:/ae/settings/setting.txt");
      } catch (FileNotFoundException fileNotFoundException) {
        System.out.println("File Not Found!");
      }

      Scanner scanner = new Scanner(in);

      while (scanner.hasNext()) {

        String[] Settings = scanner.nextLine().split(":");
        password = Settings[1];
        setPassword(password);

        String homepage = Settings[3];
        System.out.println(homepage);
        setHome(homepage);

        in.close();
      }
    }
    // Ask for password until the correct password is entered.

    Password pw = new Password();

    do {
      pw.showDialog();
    } while (!(pw.pass.getText() == null ? password == null : pw.pass.getText().equals(password)));

    // Add the browser into the browser Pane

    SwingUtilities.invokeLater(
        new Runnable() {

          @Override
          public void run() {

            ax.browserPane.add("Browser", ax.browser.getComponent());
          }
        });

    ///////////////////////////////////
    // Action listeners start here.   //
    ///////////////////////////////////

    /** Get the current page status and display in the statusLabel */
    ax.browser.addStatusListener(
        new StatusListener() {

          @Override
          public void statusChanged(final StatusChangedEvent event) {

            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.statusLabel.setText(event.getStatusText());
                  }
                });
          }
        });

    // Action Listener for homeButton
    ax.homeButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent ae) {
            try {
              ax.browser.navigate(getHome());
            } catch (IOException ex) {
              Logger.getLogger(AxBrowser.class.getName()).log(Level.SEVERE, null, ex);
            }
            ax.browser.waitReady();
            try {
              tokenString = ("<Action Home>::" + getHome() + delim);
            } catch (IOException ex) {
              Logger.getLogger(AxBrowser.class.getName()).log(Level.SEVERE, null, ex);
            }

            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.consoleTextArea.setText(tokenString);
                  }
                });
          }
        });

    // Action Listener Go to a new http web address
    ax.goButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent ae) {

            ax.browser.navigate(ax.addressBar.getText());
            ax.browser.waitReady();
            tokenString = ("<Action Navigate>::" + ax.browser.getCurrentLocation() + delim);
            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.consoleTextArea.setText(tokenString);
                  }
                });
          }
        });

    // Browser tab and enter listener

    ax.browser
        .getComponent()
        .addKeyListener(
            new KeyListener() {

              @Override
              public void keyTyped(KeyEvent ke) {}

              @Override
              public void keyPressed(KeyEvent ke) {}

              @Override
              public void keyReleased(KeyEvent ke) {
                {
                  if (ke.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {

                    tokenString = ("<Action Key>::" + "Enter" + delim);
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            ax.consoleTextArea.setText(tokenString);
                          }
                        });
                  }
                  {
                    if (ke.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) {

                      tokenString = ("<Action Key>::" + "Tab" + delim);
                      SwingUtilities.invokeLater(
                          new Runnable() {
                            @Override
                            public void run() {
                              ax.consoleTextArea.setText(tokenString);
                            }
                          });
                    }
                  }
                }
              }
            });

    // Address Bar Enter Key listener, same as above but with Enter Key
    ax.addressBar.addKeyListener(
        new java.awt.event.KeyAdapter() {

          @Override
          public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {

              ax.browser.navigate(ax.addressBar.getText());
              ax.browser.waitReady();

              tokenString = ("<Action Navigate>::" + ax.browser.getCurrentLocation() + delim);
              SwingUtilities.invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      ax.consoleTextArea.setText(tokenString);
                    }
                  });
            }
          }
        });

    // Search Bar Enter Key listener
    ax.searchField.addKeyListener(
        new java.awt.event.KeyAdapter() {
          @Override
          public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {

              ax.browser.navigate("http://www.google.com/search?q=" + ax.searchField.getText());
              ax.browser.waitReady();
              tokenString = ("<Action Google_Search>::" + ax.browser.getCurrentLocation() + delim);

              SwingUtilities.invokeLater(
                  new Runnable() {
                    @Override
                    public void run() {
                      ax.consoleTextArea.setText(tokenString);
                    }
                  });
            }
          }
        });

    // Action Listener Go Back
    ax.backButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent ae) {

            ax.browser.goBack();
            ax.browser.waitReady();
            tokenString = ("<Action Back>::" + ax.browser.getCurrentLocation() + delim);
            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.consoleTextArea.setText(tokenString);
                  }
                });
          }
        });

    // Action go forward
    ax.forwardButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent ae) {

            ax.browser.goForward();
            ax.browser.waitReady();
            tokenString = ("<Action Forward>::" + ax.browser.getCurrentLocation() + delim);
            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.consoleTextArea.setText(tokenString);
                  }
                });
          }
        });

    /*Now we need to update the address bar when we go to a new page
     *
     * Change the navigation text, and most importantly, process clicks
     */

    ax.browser.addNavigationListener(
        new NavigationListener() {
          @Override
          public void navigationStarted(final NavigationEvent event) {
            documentElement.removeEventListener("click", clickEventListener, false);
            documentElement.removeEventListener("change", changeEventListener, false);
            documentElement.removeEventListener("focusin", inEventListener, false);
            documentElement.removeEventListener("focusout", outEventListener, false);
          }

          @Override
          public void navigationFinished(NavigationFinishedEvent event) {

            ax.addressBar.setText(event.getUrl());

            // set the webpage title on the tab
            // set the title in its own swing thread
            String checkTitle = ax.browser.getTitle();
            if (checkTitle.length() > 40) {
              for (int i = 0; i <= checkTitle.length(); ++i) {
                checkTitle = checkTitle.substring(0, 30);
              }
            }
            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ax.browserPane.setTitleAt(0, ax.browser.getTitle());
                  }
                });

            document = ax.browser.getDocument();
            documentElement = (DOMElement) document.getDocumentElement();
            EventListener init =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {
                    HTMLElement t = (HTMLElement) evt.getTarget();

                    documentElement.addEventListener("change", changeEventListener, captureInput);
                  }
                };

            documentElement.addEventListener("load", init, false);

            ((EventTarget) documentElement)
                .addEventListener(
                    "click",
                    new EventListener() {
                      public void handleEvent(Event evt) {
                        HTMLElement t = (HTMLElement) evt.getTarget();
                        System.out.println("Type = " + t.getNodeName());

                        htmlEvent.processThis(ax, t, documentElement);
                        if ("textarea".equals(t.getNodeName().toLowerCase())) {
                          documentElement.addEventListener(
                              "change", changeEventListener, captureInput);
                        }
                      }
                    },
                    false);

            // Listener for element clicks

            clickEventListener =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {

                    org.w3c.dom.events.MouseEvent event = (org.w3c.dom.events.MouseEvent) evt;

                    HTMLElement target = (HTMLElement) event.getTarget();

                    String tagName = target.getNodeName().toLowerCase();

                    if (tagName.equals("input")) {
                      documentElement.addEventListener("keyup", keyEventListener, false);

                    } else {
                      htmlEvent.processThis(ax, target, documentElement);
                    }
                  }
                };

            // Looks for changes in text.
            keyEventListener =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {

                    org.w3c.dom.events.Event event = (org.w3c.dom.events.Event) evt;
                    HTMLElement target = (HTMLElement) event.getTarget();
                    System.out.println("target value: " + event.getType());

                    htmlEvent.processThis(ax, target, documentElement);
                  }
                };
            changeEventListener =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {
                    HTMLElement t = (HTMLElement) evt.getTarget();
                    System.out.println("Type = " + t.getNodeName());

                    htmlEvent.processThis(ax, t, documentElement);
                  }
                };

            inEventListener =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {

                    documentElement.addEventListener("click", clickEventListener, false);
                  }
                };

            documentElement.addEventListener("focusin", inEventListener, false);

            outEventListener =
                new EventListener() {

                  @Override
                  public void handleEvent(Event evt) {

                    // Remove Listeners on focus out.
                    System.out.println("Focused out, removing click and change listeners");
                    documentElement.removeEventListener("change", changeEventListener, false);
                    documentElement.removeEventListener("click", clickEventListener, false);
                  }
                };

            documentElement.addEventListener("focusout", outEventListener, false);
          }
        });

    // Navigate to our home screen and wait for it to be ready.
    ax.browser.navigate(getHome());
    ax.browser.waitReady();
    ax.conscriptPane.setVisible(false);

    // Get the history.
    /*
    HistoryListModel hlm = new HistoryListModel(ax);
    ax.HistoryCombo.setModel(hlm);
    */
    // Change the tab text to current page
    SwingUtilities.invokeLater(
        new Runnable() {

          @Override
          public void run() {

            // Setup the ax.browser tab, html tab and addressbar
            ax.browserPane.setTitleAt(0, ax.browser.getTitle());
            String stringToken1 = null;
            try {
              stringToken1 = ("<Navigate Home>::" + getHome());
            } catch (IOException ex) {
              Logger.getLogger(AxBrowser.class.getName()).log(Level.SEVERE, null, ex);
            }
            ax.consoleTextArea.setText(stringToken1);
            // Put the current html address in the addressbar
            ax.addressBar.setText(ax.browser.getCurrentLocation());
          }
        });
  }
Exemplo n.º 16
0
  protected void encodeScript(FacesContext context, Password password) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    String clientId = password.getClientId(context);
    boolean feedback = password.isFeedback();

    startScript(writer, clientId);

    writer.write("$(function(){");

    writer.write("PrimeFaces.cw('Password','" + password.resolveWidgetVar() + "',{");
    writer.write("id:'" + clientId + "'");

    if (feedback) {
      writer.write(",feedback:true");
      writer.write(",inline:" + password.isInline());

      if (password.getPromptLabel() != null)
        writer.write(",promptLabel:'" + password.getPromptLabel() + "'");
      if (password.getWeakLabel() != null)
        writer.write(",weakLabel:'" + password.getWeakLabel() + "'");
      if (password.getGoodLabel() != null)
        writer.write(",goodLabel:'" + password.getGoodLabel() + "'");
      if (password.getStrongLabel() != null)
        writer.write(",strongLabel:'" + password.getStrongLabel() + "'");
    }

    encodeClientBehaviors(context, password);

    writer.write("});});");

    endScript(writer);
  }
Exemplo n.º 17
0
  private void loginActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_loginActionPerformed
    // TODO add your handling code here:
    String K = Encrypt.cryptWithMD5(Password.getText());
    String sql = "Select * From user_login Where Username =? and Password=?";
    try {
      conn = DbConnectionManager.getInstance();
      pst = conn.getInstance().prepareStatement(sql);
      pst.setString(1, user_name.getText());
      /*--------------------------------------------------------*/
      pst.setString(2, K); // this should be corrected to K
      // System.out.println(Password.getText());

      String username = user_name.getText();
      UserDataAccessManager userda = new UserDataAccessManager();
      String getusertype = userda.getType(username);
      String userType = getusertype;
      System.out.println(userType);
      String pass = K;
      try {
        rs = pst.executeQuery();
        // System.out.println(rs);
      } catch (MySQLSyntaxErrorException e) {
        System.out.println("Mu horek methanata adala na..");
      }

      if (rs.next()) {
        System.out.println("loksda");
        userid = rs.getInt("User_id");
        System.out.println("user ID " + userid);
        System.out.println("user Type " + userType);

        if (userType.compareTo("Doctor") == 0) {
          close();
          DoctorJFrame doc = new DoctorJFrame();
          doc.setDoctorId(userid);
          doc.addmodeltime();
          doc.setLocationRelativeTo(null);
          doc.setVisible(true);
          doc.setExtendedState(doc.getExtendedState() | doc.MAXIMIZED_BOTH);

          //
        } else if (userType.compareTo("FrontDesk") == 0) {
          System.out.println("awa");
          close();
          FrontDeskJFrame FD = new FrontDeskJFrame();
          FD.setLocationRelativeTo(null);
          FD.setVisible(true);
          FD.setExtendedState(FD.getExtendedState() | FD.MAXIMIZED_BOTH);

        } else if (userType.compareTo("Attendant") == 0) {
          close();
          AttendentsJFrame FD = new AttendentsJFrame();
          FD.setLocationRelativeTo(null);
          FD.setVisible(true);
          FD.setSize(1024, 800);
          FD.setExtendedState(FD.getExtendedState() | FD.MAXIMIZED_BOTH);
        }
      } else {
        System.out.println("Check query");
        JOptionPane.showMessageDialog(new JDialog(), "Username or Password is wrong");
      }
    } catch (SQLException | NumberFormatException e) {
      JOptionPane.showMessageDialog(null, e);
    }
  } // GEN-LAST:event_loginActionPerformed
Exemplo n.º 18
0
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jLabel3 = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    user_name = new javax.swing.JTextField();
    login = new javax.swing.JButton();
    Password = new javax.swing.JPasswordField();

    jLabel3.setIcon(
        new javax.swing.ImageIcon(getClass().getResource("/image/iMAGE2.jpg"))); // NOI18N

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setPreferredSize(new java.awt.Dimension(560, 250));
    setResizable(false);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jLabel1.setFont(new java.awt.Font("Calibri", 1, 24)); // NOI18N
    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel1.setText("Username");
    getContentPane()
        .add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, 140, 40));

    jLabel2.setFont(new java.awt.Font("Calibri", 1, 24)); // NOI18N
    jLabel2.setText("Password");
    getContentPane()
        .add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 100, 140, 40));

    user_name.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    user_name.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            user_nameActionPerformed(evt);
          }
        });
    getContentPane()
        .add(user_name, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 50, 150, 30));

    login.setFont(new java.awt.Font("Calibri", 1, 18)); // NOI18N
    login.setText("Login");
    login.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            loginActionPerformed(evt);
          }
        });
    getContentPane()
        .add(login, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 150, 100, 30));

    Password.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
    Password.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            PasswordActionPerformed(evt);
          }
        });
    getContentPane()
        .add(Password, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 100, 150, 30));

    pack();
  } // </editor-fold>//GEN-END:initComponents
Exemplo n.º 19
0
 public Password getPassword(String name) {
   for (Password element : this.getPassword()) {
     if (element.getName().equals(name)) return element;
   }
   return null;
 }
Exemplo n.º 20
0
 public Password checkPassword(String password) throws Exception {
   Password pass = new Password();
   pass.verified = !password.isEmpty();
   pass.password = password;
   return pass;
 }
Exemplo n.º 21
0
 public void validatePasswords() {
   rootPassword.validate("setup.rootPassword");
   systemPasswords.validate("setup.systemPasswords");
 }
Exemplo n.º 22
0
 public LoginJFrame() {
   initComponents();
   user_name.addActionListener(this);
   Password.addActionListener(this);
 }