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:org.apache.hadoop.gateway.util.KnoxCLITest.java

@Test
public void testCreateMasterForce() throws Exception {
    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));
    }// ww  w. j  ava 2 s .  c o  m

    KnoxCLI cli = new KnoxCLI();
    cli.setConf(config);
    MasterService ms;
    int rc = 0;
    outContent.reset();

    String[] args = { "create-master", "--master", "test-master-1" };

    rc = cli.run(args);
    assertThat(rc, is(0));
    ms = cli.getGatewayServices().getService("MasterService");
    String master = String.copyValueOf(ms.getMasterSecret());
    assertThat(master, is("test-master-1"));
    assertThat(outContent.toString(), containsString("Master secret has been persisted to disk."));

    outContent.reset();
    rc = cli.run(args);
    assertThat(rc, is(-1));
    assertThat(outContent.toString(), containsString("Master secret is already present on disk."));

    outContent.reset();
    args = new String[] { "create-master", "--master", "test-master-2", "--force" };
    rc = cli.run(args);
    assertThat(rc, is(0));
    ms = cli.getGatewayServices().getService("MasterService");
    master = String.copyValueOf(ms.getMasterSecret());
    assertThat(master, is("test-master-2"));
    assertThat(outContent.toString(), containsString("Master secret has been persisted to disk."));
}

From source file:org.deviceconnect.android.localoauth.LocalOAuth2Main.java

/**
 * (2)?./*from  w  w w.  j  a v  a2 s .  c o m*/
 * <p>
 * ????????.
 * </p>
 * @param packageInfo (Android)??????<br>
 *            (Web)???????URL<br>
 *            ????????ID<br>
 * @return ??(ID, )?<br>
 *         null???
 * @throws AuthorizationException Authorization.
 */
public ClientData createClient(final PackageInfoOAuth packageInfo) throws AuthorizationException {
    if (packageInfo == null) {
        throw new IllegalArgumentException("packageInfo is null.");
    } else if (packageInfo.getPackageName() == null) {
        throw new IllegalArgumentException("packageInfo.getPackageName() is null.");
    } else if (packageInfo.getPackageName().length() <= 0) {
        throw new IllegalArgumentException("packageInfo is empty.");
    } else if (!mDb.isOpen()) {
        throw new RuntimeException("Database is not opened.");
    }

    // ???????clientId?(DB????????)
    int clientCount = cleanupClient();

    // ????????
    if (clientCount >= LocalOAuth2Settings.CLIENT_MAX) {
        throw new AuthorizationException(AuthorizationException.CLIENT_COUNTS_IS_FULL);
    }

    // 
    ClientData clientData;

    synchronized (mLockForDbAccess) {
        try {
            mDb.beginTransaction();

            // ??ID??????
            Client client = mClientManager.findByPackageInfo(packageInfo);
            if (client != null) {
                String clientId = client.getClientId();
                removeTokenData(clientId);
                removeClientData(clientId);
            }

            // ?????
            client = addClientData(packageInfo);
            clientData = new ClientData(client.getClientId(), String.copyValueOf(client.getClientSecret()));

            mDb.setTransactionSuccessful();
        } catch (SQLiteException e) {
            throw new RuntimeException(e);
        } finally {
            mDb.endTransaction();
        }
    }

    return clientData;
}

From source file:org.openmrs.module.radiology.web.controller.RadiologyObsFormControllerTest.java

/**
 * @see RadiologyObsFormController#populateModelAndView(RadiologyOrder,Obs)
 * @verifies populate the model and view for given obs with complex concept
 *///from   w ww. j  a v a2  s  .c om
@Test
public void populateModelAndView_shouldPopulateTheModelAndViewForGivenObsWithComplexConcept() throws Exception {
    //given
    ConceptComplex concept = new ConceptComplex();
    ConceptDatatype cdt = new ConceptDatatype();
    cdt.setHl7Abbreviation("ED");
    concept.setDatatype(cdt);
    mockObs.setConcept(concept);
    mockObs.setComplexData(RadiologyTestData.getMockComplexDataForMockObsWithComplexConcept());

    Field obsServiceField = RadiologyObsFormController.class.getDeclaredField("obsService");
    obsServiceField.setAccessible(true);
    obsServiceField.set(radiologyObsFormController, obsService);

    when(obsService.getComplexObs(mockObs.getId(), WebConstants.HTML_VIEW))
            .thenReturn(RadiologyTestData.getMockComplexObsAsHtmlViewForMockObs());
    when(obsService.getComplexObs(mockObs.getId(), WebConstants.HYPERLINK_VIEW))
            .thenReturn(RadiologyTestData.getMockComplexObsAsHyperlinkViewForMockObs());

    Method populateModelAndViewMethod = radiologyObsFormController.getClass().getDeclaredMethod(
            "populateModelAndView",
            new Class[] { org.openmrs.module.radiology.RadiologyOrder.class, org.openmrs.Obs.class });
    populateModelAndViewMethod.setAccessible(true);

    ModelAndView modelAndView = (ModelAndView) populateModelAndViewMethod.invoke(radiologyObsFormController,
            new Object[] { mockRadiologyOrder, mockObs });

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");
    assertThat(obs, is(mockObs));

    assertThat(modelAndView.getModelMap(), hasKey("htmlView"));
    CharArrayReader htmlComplexData = (CharArrayReader) modelAndView.getModelMap().get("htmlView");
    assertThat(htmlComplexData, is(notNullValue()));
    char[] htmlComplexDataCharArray = new char[47];
    htmlComplexData.read(htmlComplexDataCharArray);
    assertThat(String.copyValueOf(htmlComplexDataCharArray),
            is("<img src='/openmrs/complexObsServlet?obsId=1'/>"));

    assertThat(modelAndView.getModelMap(), hasKey("hyperlinkView"));
    CharArrayReader hyperlinkViewComplexData = (CharArrayReader) modelAndView.getModelMap()
            .get("hyperlinkView");
    assertThat(hyperlinkViewComplexData, is(notNullValue()));
    char[] hyperlinkViewComplexDataCharArray = new char[33];
    hyperlinkViewComplexData.read(hyperlinkViewComplexDataCharArray);
    assertThat(String.copyValueOf(hyperlinkViewComplexDataCharArray), is("openmrs/complexObsServlet?obsId=1"));
}

From source file:org.opentides.util.FileUtil.java

/**
 * Returns the MD5 hash of a file.//from  w  ww  . ja  v a  2  s. c  o m
 * (added to API Mar. 1, 2010 by e.javines)
 * @param inputStream
 * @return
 */
public static String getMD5sum(File file) {
    String md5sum = null;
    try {
        InputStream inputStream = new FileInputStream(file);
        MessageDigest msgDigest = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[8192]; // 8k buffer
        int read = 0;

        try {
            while ((read = inputStream.read(buffer)) > 0) {
                msgDigest.update(buffer, 0, read);
            }
            byte[] md5sumbytes = msgDigest.digest(); // get the MD5
            char[] md5sumchars = Hex.encodeHex(md5sumbytes); // make it readable
            md5sum = String.copyValueOf(md5sumchars);
            _log.debug("Processed MD5 sum [" + md5sum + "]");
        } catch (IOException e) {
            _log.error("Unable to process MD5 from file [" + file.getAbsolutePath() + "]", e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                _log.error("Unable to close input stream!", e);
            }
        }
    } catch (NoSuchAlgorithmException nosae) {
        _log.error(nosae, nosae);
    } catch (FileNotFoundException fnfe) {
        _log.error(fnfe, fnfe);
    }

    return md5sum;

}

From source file:util.FoursquareAPI_backup.java

public JSONObject search4Square(String term, double latitude, double longitude) {
    try {//  w  w  w  .j av  a 2 s.co m
        //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search");
        int len = G_htp.length();
        G_htp.append(latitude);
        G_htp.append(',');
        G_htp.append(longitude);
        int len1 = G_htp.length();
        //String contents = java.net.URL();
        URL url = new URL(G_htp.toString());
        G_htp.delete(len, len1);
        URLConnection con = url.openConnection();
        //SSLException thrown here if server certificate is invalid

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        boolean Begin_City = false;
        int number = 0;
        JSONObject list1 = new JSONObject();
        String input = null;
        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 = IntempS[1].toCharArray();
                for (int i = 0; i < SaveStringArry.length; i++) {
                    if (SaveStringArry[i] == '\"')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == '[')
                        SaveStringArry[i] = ' ';
                    if (SaveStringArry[i] == ']')
                        SaveStringArry[i] = ' ';
                }
                String SaveString = String.copyValueOf(SaveStringArry).trim();

                if (IntempS[0].contains("postalCode")) {
                    list1.put("post_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("state")) {
                    list1.put("state_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("cc")) {
                    list1.put("country_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("city")) {
                    list1.put("city_name", SaveString);
                    number++;
                } else if (IntempS[0].contains("formattedAddress")) {
                    list1.put("address", SaveString);
                    number++;
                } else if (IntempS[0].contains("name")) {
                    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;
}

From source file:com.cmsoftware.keyron.vista.admin.ActivarEmpleado.java

/**
 * Verifica los campos rellenos y actualiza la clave del usuario.
 *///from   w ww  .ja  v a  2  s. co  m
private void activarEmpleado() {
    labelError.setText("");
    if (correo.getText().trim().isEmpty() || correo.getText().trim().length() < 5) {
        labelError.setText("El campo 'Correo' no es vlido");
        correo.requestFocus();
        correo.setBackground(new Color(253, 194, 194));
    } else if (String.copyValueOf(clave.getPassword()).trim().isEmpty()
            || String.copyValueOf(clave.getPassword()).trim().length() < 6) {
        labelError.setText("El campo 'Clave' no es vlido");
        clave.requestFocus();
        clave.setBackground(new Color(253, 194, 194));
    } else {
        correo.setEnabled(false);
        clave.setEnabled(false);
        aceptar.setEnabled(false);
        cancelar.setEnabled(false);
        labelError.setText("Activando empleado ...");
        labelError.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/com/cmsoftware/keyron/recursos/cargando.gif")));
        activando = true;
        new ActivaEmpleado().start();
    }
}

From source file:com.cmsoftware.keyron.vista.admin.CambiarClave.java

private void repetirNuevaClaveKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_repetirNuevaClaveKeyReleased
    if (repetirNuevaClave.getPassword().length >= 6) {
        if (!String.copyValueOf(repetirNuevaClave.getPassword())
                .equals(String.copyValueOf(nuevaClave.getPassword()))) {
            label_pass.setText("Las claves no coinciden.");
        } else {//from ww w. j  a v a2s.  c o  m
            label_pass.setText("");
        }

    }
}

From source file:org.jcryptool.commands.core.HelpCommand.java

/**
 * derives the command line to show the detailed help from a command line that evoked the display of the short help.
 *
 * @param commandCallLine the command line for the short help
 *///from   www . j a va  2s .c o  m
private static String getDetailedHelpCmdlineFromShortHelpCmdline(String commandCallLine) {
    /*
     * possible commandCallLines: help cmd ? cmd cmd help cmd ? cmd -help cmd --help
     */

    // Seeking outer help call pattern first
    String outerHelpPattern = "(help)|\\?.*"; //$NON-NLS-1$
    if (commandCallLine.matches(outerHelpPattern)) {
        try {
            String cmdname = commandCallLine.trim().split(" ")[0]; //$NON-NLS-1$
            String cmdtail = commandCallLine.substring(cmdname.length());

            cmdname = cmdname.replaceFirst("\\Ahelp", "HELP"); //$NON-NLS-1$ //$NON-NLS-2$
            cmdname = cmdname.replaceFirst("\\A\\?", "??"); //$NON-NLS-1$ //$NON-NLS-2$

            return cmdname + cmdtail;
        } catch (IllegalStateException e) {
            LogUtil.logError(e);
            return null;
        }
    } else {
        String commandLine = String.copyValueOf(commandCallLine.toCharArray());
        commandLine = commandLine.replaceFirst("help", "HELP"); //$NON-NLS-1$ //$NON-NLS-2$
        commandLine = commandLine.replaceFirst("\\?", "??"); //$NON-NLS-1$ //$NON-NLS-2$

        if (commandLine.equals(commandCallLine)) {
            LogUtil.logError("Error in generating reference commandline for detailed help."); //$NON-NLS-1$
        }
        return commandLine;
    }

}

From source file:util.FoursquareAPI.java

public JSONObject search4Square(String term, double latitude, double longitude) {
    try {//from w  w  w.j a  v  a  2s  .  c om
        //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search");
        int len = G_htp.length();
        G_htp.append(latitude);
        G_htp.append(',');
        G_htp.append(longitude);
        int len1 = G_htp.length();
        //String contents = java.net.URL();
        URL url = new URL(G_htp.toString());
        G_htp.delete(len, len1);
        URLConnection con = url.openConnection();
        //SSLException thrown here if server certificate is invalid

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        boolean Begin_City = false;
        int number = 0;
        JSONObject list1 = new JSONObject();
        String input = null;
        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 = IntempS[1].toCharArray();
                for (int i = 0; i < SaveStringArry.length; i++) {
                    if (SaveStringArry[i] == '\"')
                        SaveStringArry[i] = ' ';
                    else if (SaveStringArry[i] == '[')
                        SaveStringArry[i] = ' ';
                    if (SaveStringArry[i] == ']')
                        SaveStringArry[i] = ' ';
                }
                String SaveString = String.copyValueOf(SaveStringArry).trim();

                if (IntempS[0].contains("postalCode")) {
                    list1.put("post_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("state")) {
                    list1.put("state_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("cc")) {
                    list1.put("country_code", SaveString);
                    number++;
                } else if (IntempS[0].contains("city")) {
                    list1.put("city_name", SaveString);
                    number++;
                } else if (IntempS[0].contains("formattedAddress")) {
                    list1.put("address", SaveString);
                    number++;
                } else if (IntempS[0].contains("name")) {
                    list1.put("place_name", SaveString);
                    number++;
                }

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

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

From source file:org.apache.maven.cli.CopyOfMavenCli.java

private void encryption(CliRequest cliRequest) throws Exception {
    if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) {
        String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_MASTER_PASSWORD);

        if (passwd == null) {
            Console cons;//from  www .  j  ava2 s.  com
            char[] password;
            if ((cons = System.console()) != null
                    && (password = cons.readPassword("Master password: ")) != null) {
                // Cipher uses Strings
                passwd = String.copyValueOf(password);

                // Sun/Oracle advises to empty the char array
                java.util.Arrays.fill(password, ' ');
            }
        }

        DefaultPlexusCipher cipher = new DefaultPlexusCipher();

        System.out
                .println(cipher.encryptAndDecorate(passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION));

        throw new ExitException(0);
    } else if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)) {
        String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_PASSWORD);

        if (passwd == null) {
            Console cons;
            char[] password;
            if ((cons = System.console()) != null && (password = cons.readPassword("Password: ")) != null) {
                // Cipher uses Strings
                passwd = String.copyValueOf(password);

                // Sun/Oracle advises to empty the char array
                java.util.Arrays.fill(password, ' ');
            }
        }

        String configurationFile = dispatcher.getConfigurationFile();

        if (configurationFile.startsWith("~")) {
            configurationFile = System.getProperty("user.home") + configurationFile.substring(1);
        }

        String file = System.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile);

        String master = null;

        SettingsSecurity sec = SecUtil.read(file, true);
        if (sec != null) {
            master = sec.getMaster();
        }

        if (master == null) {
            throw new IllegalStateException("Master password is not set in the setting security file: " + file);
        }

        DefaultPlexusCipher cipher = new DefaultPlexusCipher();
        String masterPasswd = cipher.decryptDecorated(master,
                DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION);
        System.out.println(cipher.encryptAndDecorate(passwd, masterPasswd));

        throw new ExitException(0);
    }
}