Example usage for java.lang String copyValueOf

List of usage examples for java.lang String copyValueOf

Introduction

In this page you can find the example usage for java.lang String copyValueOf.

Prototype

public static String copyValueOf(char data[]) 

Source Link

Document

Equivalent to #valueOf(char[]) .

Usage

From source file:net.sf.jpam.jaas.JpamLoginModule.java

/**
 * Method to authenticate a <code>Subject</code> (phase 1).
 * <p/>/*from  w w w.j  ava  2s . c  o m*/
 * <p> The implementation of this method authenticates
 * a <code>Subject</code>.  For example, it may prompt for
 * <code>Subject</code> information such
 * as a username and password and then attempt to verify the password.
 * This method saves the result of the authentication attempt
 * as private state within the LoginModule.
 * <p/>
 * <p/>
 *
 * @return true if the authentication succeeded, or false if this
 *         <code>LoginModule</code> should be ignored.
 * @throws javax.security.auth.login.LoginException
 *          if the authentication fails
 */
public boolean login() throws LoginException {
    pam = createPam();

    Callback[] callbacks = new Callback[2];
    String username = null;
    NameCallback nameCallback = new NameCallback("Enter Username: ");
    callbacks[0] = nameCallback;
    String credentials = null;
    PasswordCallback passwordCallback = new PasswordCallback("Enter Credentials: ", false);
    callbacks[1] = passwordCallback;

    try {
        callbackHandler.handle(callbacks);
    } catch (IOException e) {
        LOG.error("IOException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        LOG.error("UnsupportedCallbackException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    }
    username = nameCallback.getName();
    credentials = String.copyValueOf(passwordCallback.getPassword());
    boolean authenticated = false;
    PamReturnValue pamReturnValue = pam.authenticate(username, credentials);
    if (pamReturnValue.equals(PamReturnValue.PAM_SUCCESS)) {
        authenticated = true;
    } else if (pamReturnValue.equals(PamReturnValue.PAM_ACCT_EXPIRED)) {
        throw new AccountExpiredException(PamReturnValue.PAM_ACCT_EXPIRED.toString());
    } else if (pamReturnValue.equals(PamReturnValue.PAM_CRED_EXPIRED)) {
        throw new CredentialExpiredException(PamReturnValue.PAM_CRED_EXPIRED.toString());
    } else {
        throw new FailedLoginException(pamReturnValue.toString());
    }
    return authenticated;
}

From source file:client.SampleLoginModule.java

/**
 * Authenticate the user by prompting for a user name and password.
 * /*  ww w.  j  ava2  s. com*/
 * <p>
 * 
 * @return true in all cases since this <code>LoginModule</code> should
 *         not be ignored.
 * 
 * @exception FailedLoginException
 *                if the authentication fails.
 *                <p>
 * 
 * @exception LoginException
 *                if this <code>LoginModule</code> is unable to perform
 *                the authentication.
 */
public boolean login() throws LoginException {

    // prompt for a user name and password
    if (callbackHandler == null)
        throw new LoginException(
                "Error: no CallbackHandler available " + "to garner authentication information from the user");

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user name: ");
    callbacks[1] = new PasswordCallback("password: ", false);

    try {
        callbackHandler.handle(callbacks);
        username = ((NameCallback) callbacks[0]).getName();
        String tmpPassword = String.copyValueOf(((PasswordCallback) callbacks[1]).getPassword());
        if (tmpPassword == null) {
            // treat a NULL password as an empty password
            tmpPassword = "";
        }
        password = tmpPassword;
        //System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length());
        ((PasswordCallback) callbacks[1]).clearPassword();

    } catch (java.io.IOException ioe) {
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException("Error: " + uce.getCallback().toString()
                + " not available to garner authentication information " + "from the user");
    }

    // print debugging information
    if (debug) {
        System.out.println("\t\t[SampleLoginModule] " + "user entered user name: " + username);
        System.out.print("\t\t[SampleLoginModule] " + "user entered password: ");
        for (int i = 0; i < password.length(); i++)
            System.out.print(password.toCharArray()[i]);
        System.out.println();
    }

    cmdAuthent.setUsern(username);
    cmdAuthent.setPassw(password);
    cmdAuthent.execute();
    return cmdAuthent.getRes();

}

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.MemberLookupCompleter.java

@Override
public int indexOfStartCharacter(char[] line) {
    //TODO: change to check if there is a data-sly-use before the class
    final String text = String.copyValueOf(line);
    final Matcher matcher = LAST_DOLLAR_CURLYBRACE.matcher(text);

    if (matcher.find()) {
        final int beginIndex = matcher.start();
        final Matcher variableMatcher = LAST_VARIABLE.matcher(text);
        if (variableMatcher.find(beginIndex)) {
            return variableMatcher.start() - 1;
        }// ww  w .  ja v a 2s.com
    }
    return -1;
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Read password from console./*from ww  w  .  j  ava  2 s.  c o  m*/
 *
 * Note that when the System.console() is null, there is no secure way of entering a password
 * without exposing it in the clear on the console (it is echoed onto the screen).
 *
 * For this reason, it is suggested that the user login prior to using functionality such as
 * input redirection since this could result in a null console.
 *
 * @return user-inputted password
 */
public static String readPassword() throws IOException {
    Console console = System.console();
    if (console != null) {
        System.out.format("password for '%s': ", USER_NAME.value());
        return String.copyValueOf(System.console().readPassword());
    } else {
        throw new IOException(
                "Please login by running a command without piping.\n" + "For example: keywhiz.cli login");
    }
}

From source file:com.supermap.desktop.icloud.CloudLicenseDialog.java

private void saveToken() {
    FileOutputStream outPutStream = null;
    String userName = textFieldUserName.getText() + ",";
    String password = String.copyValueOf(fieldPassWord.getPassword());
    String saveToken = checkBoxSavePassword.isSelected() ? "true" : "false";
    String autoLogin = checkBoxAutoLogin.isSelected() ? "true" : "false";
    try {//from   w  w w  .  j a  v a  2s .c o  m
        outPutStream = new FileOutputStream(TOKEN_PATH);
        outPutStream.write(userName.getBytes());
        outPutStream.write(password.getBytes());
        outPutStream.write(",".getBytes());
        outPutStream.write(saveToken.getBytes());
        outPutStream.write(",".getBytes());
        outPutStream.write(autoLogin.getBytes());
    } catch (FileNotFoundException e) {
        Application.getActiveApplication().getOutput().output(e);
    } catch (IOException e) {
        Application.getActiveApplication().getOutput().output(e);
    } finally {
        try {
            outPutStream.close();
        } catch (IOException e) {
            Application.getActiveApplication().getOutput().output(e);
        }
    }

}

From source file:org.apache.hadoop.gateway.util.KnoxCLITest.java

private void createTestMaster() throws Exception {
    outContent.reset();//  w ww.  j a va 2  s . c o  m
    String[] args = new String[] { "create-master", "--master", "master", "--force" };
    KnoxCLI cli = new KnoxCLI();
    int rc = cli.run(args);
    assertThat(rc, is(0));
    MasterService ms = cli.getGatewayServices().getService("MasterService");
    String master = String.copyValueOf(ms.getMasterSecret());
    assertThat(master, is("master"));
    assertThat(outContent.toString(), containsString("Master secret has been persisted to disk."));
}

From source file:br.com.vizzatech.cryptocipher.CryptoXCipher.java

/**
 * Aplica o <a href=http://pt.wikipedia.org/wiki/Cifra_de_Csar>conceito Cifra de cesar</a> para
 * a String, dependendo de seu modo//w  w w  .j  a v  a  2  s.c o  m
 * 
 * @param str
 *            - String a ser aplicada
 * @param modo
 *            {@link Mode}
 * @return String alterada
 */
private String cifraCesar(String str, Mode modo) {
    char[] newStr = new char[str.length()];
    int i = 0;
    if (modo.equals(Mode.ENCRYPT)) {
        for (char c : str.toCharArray()) {
            newStr[i] = (char) (c + this.cifraCesar);
            i++;
        }
    } else {
        for (char c : str.toCharArray()) {
            newStr[i] = (char) (c - this.cifraCesar);
            i++;
        }
    }

    return String.copyValueOf(newStr);
}

From source file:org.apache.hadoop.gateway.util.KnoxCLITest.java

@Test
public void testCreateMasterGenerate() throws Exception {
    String[] args = { "create-master", "--generate" };
    int rc = 0;/*from  w w w  .  j  ava 2s .  c o m*/
    GatewayConfigImpl config = new GatewayConfigImpl();
    File masterFile = new File(config.getGatewaySecurityDir(), "master");

    // Need to delete the master file so that the change isn't ignored.
    if (masterFile.exists()) {
        assertThat("Failed to delete existing master file.", masterFile.delete(), is(true));
    }
    outContent.reset();
    KnoxCLI cli = new KnoxCLI();
    cli.setConf(config);
    rc = cli.run(args);
    assertThat(rc, is(0));
    MasterService ms = cli.getGatewayServices().getService("MasterService");
    String master = String.copyValueOf(ms.getMasterSecret());
    assertThat(master.length(), is(36));
    assertThat(master.indexOf('-'), is(8));
    assertThat(master.indexOf('-', 9), is(13));
    assertThat(master.indexOf('-', 14), is(18));
    assertThat(master.indexOf('-', 19), is(23));
    assertThat(UUID.fromString(master), notNullValue());
    assertThat(outContent.toString(), containsString("Master secret has been persisted to disk."));

    // Need to delete the master file so that the change isn't ignored.
    if (masterFile.exists()) {
        assertThat("Failed to delete existing master file.", masterFile.delete(), is(true));
    }
    outContent.reset();
    cli = new KnoxCLI();
    rc = cli.run(args);
    ms = cli.getGatewayServices().getService("MasterService");
    String master2 = String.copyValueOf(ms.getMasterSecret());
    assertThat(master2.length(), is(36));
    assertThat(UUID.fromString(master2), notNullValue());
    assertThat(master2, not(is(master)));
    assertThat(rc, is(0));
    assertThat(outContent.toString(), containsString("Master secret has been persisted to disk."));
}

From source file:br.com.vectorx.BlowfishCryptox.java

/**
 * Aplica o conceito <a href=http://pt.wikipedia.org/wiki/Cifra_de_Csar>
 * Cifra de cesar</a> para a String, dependendo de seu modo
 * //from w w  w. jav  a2 s.  co  m
 * @param str
 *            - String a ser aplicada
 * @param modo
 *            {@link Mode}
 * @return String alterada
 */
private String cifraCesar(String str, Mode modo) {
    char[] newStr = new char[str.length()];
    int i = 0;
    // Caso para criptografia
    if (modo.equals(Mode.ENCRYPT)) {
        for (char c : str.toCharArray()) {
            // Valor do char + int da cifra de cesar
            newStr[i] = (char) (c + this.cifraCesar);
            i++;
        }
    } // Caso para descriptografia
    else {
        for (char c : str.toCharArray()) {
            // Valor do char - int da cifra de cesar
            newStr[i] = (char) (c - this.cifraCesar);
            i++;
        }
    }
    // Retorna uma String com o valor do char[]
    return String.copyValueOf(newStr);
}

From source file:util.YelpAPI.java

public JSONObject search4Yelp(String term, double latitude, double longitude) {
    try {/*from  w w w  . j a  va2s . c  om*/
        OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/v2/search");
        request.addQuerystringParameter("term", term);
        request.addQuerystringParameter("ll", latitude + "," + longitude);
        request.addQuerystringParameter("limit", String.valueOf(SEARCH_LIMIT));
        this.service.signRequest(this.accessToken, request);
        Response response = request.send();

        boolean Begin_City = false;
        int number = 0;
        JSONObject list1 = new JSONObject();
        String input = null;

        BufferedReader br = new BufferedReader(new InputStreamReader(response.getStream()));

        while ((input = br.readLine()) != null) {
            //                System.out.println(input);
            String[] tempS = input.split(",");
            for (int index = 0; index < tempS.length; index++) {
                String[] IntempS = tempS[index].split(":");
                if (IntempS.length < 2)
                    continue;
                char[] SaveStringArry = null;

                if (IntempS[0].contains("location") && IntempS.length > 2) {
                    IntempS[0] = IntempS[1];
                    SaveStringArry = IntempS[2].toCharArray();
                } else {
                    SaveStringArry = IntempS[1].toCharArray();
                }

                for (int i = 0; i < SaveStringArry.length; i++) {
                    if (SaveStringArry[i] == '\"')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == '[')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == ']')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == '{')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == '}')
                        SaveStringArry[i] = ' ';
                }
                String SaveString = String.copyValueOf(SaveStringArry).trim();

                if (IntempS[0].contains("postal_code")) {
                    list1.put("post_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("state_code")) {
                    list1.put("state_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("country_code")) {
                    list1.put("country_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("city")) {
                    list1.put("city_name", SaveString);
                    number++;
                } else if (IntempS[0].contains("address")) {
                    list1.put("address", SaveString);
                    number++;
                } else if (IntempS[0].contains("display_address")) {
                    list1.put("place_name", SaveString);
                    number++;
                }

                if (number > 5)
                    break;
            }
        }
        br.close();

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