Example usage for java.lang String String

List of usage examples for java.lang String String

Introduction

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

Prototype

public String(StringBuilder builder) 

Source Link

Document

Allocates a new string that contains the sequence of characters currently contained in the string builder argument.

Usage

From source file:com.mindquarry.management.user.UserManagementClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(UserManagementClient.class);
    log.info("Starting user management client..."); //$NON-NLS-1$

    // parse command line arguments
    CommandLine line = null;/*from w  w  w .  j a  v  a 2  s  . co m*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed."); //$NON-NLS-1$
        printUsage();
        return;
    }
    // retrieve login data
    System.out.print("Please enter your login ID: "); //$NON-NLS-1$

    String user = readString();
    user = user.trim();

    System.out.print("Please enter your new password: "); //$NON-NLS-1$

    String password = readString();
    password = password.trim();
    password = new String(DigestUtils.md5(password));
    password = new String(Base64.encodeBase64(password.getBytes()));

    // start PWD change client
    UserManagementClient manager = new UserManagementClient();
    try {
        if (line.hasOption(O_DEL)) {
            manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        } else {
            manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        }
    } catch (Exception e) {
        log.error("Error while applying password changes.", e); //$NON-NLS-1$
    }
    log.info("User management client finished successfully."); //$NON-NLS-1$
}

From source file:com.amalto.workbench.utils.PasswordUtil.java

public static void main(String args[]) {
    Base64 base64 = new Base64();
    String str = "qwe";//$NON-NLS-1$
    byte[] enbytes = null;
    String encodeStr = null;//from w  w  w.j a v a 2  s  . co m
    byte[] debytes = null;
    String decodeStr = null;
    enbytes = base64.encode(str.getBytes());
    encodeStr = new String(enbytes);
    debytes = base64.decode(enbytes);
    decodeStr = new String(debytes);
    System.out.println("plain password:" + str); //$NON-NLS-1$
    System.out.println("encrypted password:" + encodeStr); //$NON-NLS-1$
    System.out.println("decrypted password:" + decodeStr); //$NON-NLS-1$
}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception// w  ww.  j  a va  2s .  c o m
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:org.soasecurity.wso2.mutual.auth.oauth2.client.MutualSSLOAuthClient.java

public static void main(String[] args) throws Exception {

    File file = new File((new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main"
            + File.separator + "resources" + File.separator + "keystore" + File.separator + keyStoreName);

    if (!file.exists()) {
        throw new Exception("Key Store file can not be found in " + file.getCanonicalPath());
    }/*from w  ww .  j a v  a 2 s .  c om*/

    //Set trust store, you need to import server's certificate of CA certificate chain in to this
    //key store
    System.setProperty("javax.net.ssl.trustStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);

    //Set key store, this must contain the user private key
    //here we have use both trust store and key store as the same key store
    //But you can use a separate key store for key store an trust store.
    System.setProperty("javax.net.ssl.keyStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);

    HttpClient client = new HttpClient();

    HttpMethod method = new PostMethod(endPoint);

    // Base64 encoded client id & secret
    method.setRequestHeader("Authorization",
            "Basic T09pN2dpUjUwdDZtUmU1ZkpmWUhVelhVa1QwYTpOOUI2dDZxQ0E2RFp2eTJPQkFIWDhjVlI1eUlh");
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    NameValuePair pair1 = new NameValuePair();
    pair1.setName("grant_type");
    pair1.setValue("x509");

    NameValuePair pair2 = new NameValuePair();
    pair2.setName("username");
    pair2.setValue("asela");

    NameValuePair pair3 = new NameValuePair();
    pair3.setName("password");
    pair3.setValue("asela");

    method.setQueryString(new NameValuePair[] { pair1, pair2, pair3 });

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {

        System.out.println("Failed: " + method.getStatusLine());

    } else {

        byte[] responseBody = method.getResponseBody();

        System.out.println(new String(responseBody));
    }
}

From source file:net.padlocksoftware.padlock.licensevalidator.Main.java

/**
 * @param args the command line arguments
 *///from ww  w.j ava 2  s .c  o m
public static void main(String[] args) {
    parse(args);
    Date currentDate = new Date();

    Validator v = new Validator(license, new String(Hex.encodeHex(pair.getPublic().getEncoded())));
    v.setIgnoreFloatTime(true);

    boolean ex = false;
    LicenseState state;
    try {
        state = v.validate();
    } catch (ValidatorException e) {
        state = e.getLicenseState();
    }

    // Show test status
    System.out.println("\nValidation Test Results:");
    System.out.println("========================\n");
    for (TestResult result : state.getTests()) {
        System.out.println(
                "\t" + result.getTest().getName() + "\t\t\t" + (result.passed() ? "Passed" : "Failed"));
    }

    System.out.println("\nLicense state: " + (state.isValid() ? "Valid" : "Invalid"));

    //
    // Cycle through any dates
    //
    Date d = license.getCreationDate();
    System.out.println("\nCreation date: \t\t" + d);

    d = license.getStartDate();
    System.out.println("Start date: \t\t" + d);

    d = license.getExpirationDate();
    System.out.println("Expiration date: \t" + d);

    Long floatPeroid = license.getFloatingExpirationPeriod();
    if (floatPeroid != null) {
        long seconds = floatPeroid / 1000L;
        System.out.println("\nExpire after first run: " + seconds + " seconds");

    }

    if (floatPeroid != null || license.getExpirationDate() != null) {
        long remaining = v.getTimeRemaining(currentDate) / 1000L;
        System.out.println("\nTime remaining: " + remaining + " seconds");

    }

    //
    // License properties
    //
    System.out.println("\nLicense Properties");
    Properties p = license.getProperties();
    if (p.size() == 0) {
        System.out.println("None");
    }

    for (final Enumeration propNames = p.propertyNames(); propNames.hasMoreElements();) {
        final String key = (String) propNames.nextElement();
        System.out.println("Property: " + key + " = " + p.getProperty(key));
    }

    //
    // Hardware locking
    //
    for (String address : license.getHardwareAddresses()) {
        System.out.println("\nHardware lock: " + address);
    }
    System.out.println("\n");
}

From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java

public static void main(String[] args) {

    // test();/*from  w ww .  ja v  a  2 s.c o m*/
    // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP
    // System.setProperty("proxyPort", "8080");
    // System.setProperty("socksProxyPort", "1080");
    //
    // Authenticator.setDefault(new MyAuthenticator());

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Create a method instance.
    GetMethod method = new GetMethod(url);

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //     
    // client.getState().setProxyCredentials(authScope, credentials);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:net.itransformers.bgpPeeringMap.BgpPeeringMapFromFile.java

public static void main(String[] args) throws Exception {

    Map<String, String> params = CmdLineParser.parseCmdLine(args);
    logger.info("input params" + params.toString());
    final String settingsFile = params.get("-s");
    if (settingsFile == null) {
        printUsage("bgpPeeringMap.properties");
        return;/*from w ww  .  j  av a 2 s. co m*/
    }

    Map<String, String> settings = loadProperties(new File(System.getProperty("base.dir"), settingsFile));
    logger.info("Settings" + settings.toString());

    File outputDir = new File(System.getProperty("base.dir"), settings.get("output.dir"));
    System.out.println(outputDir.getAbsolutePath());
    boolean result = outputDir.mkdir();
    //        if (!result) {
    //            System.out.println("result:"+result);
    //            System.out.println("Unable to create dir: "+outputDir);
    //            return;
    //        }

    File graphmlDir = new File(outputDir, settings.get("output.dir.graphml"));
    result = outputDir.mkdir();
    //        if (!result) {
    //            System.out.println("Unable to create dir: "+graphmlDir);
    //            return;
    //        }

    XsltTransformer transformer = new XsltTransformer();
    byte[] rawData = readRawDataFile(settings.get("raw-data-file"));
    logger.info("First-transformation has started with xsltTransformator " + settings.get("xsltFileName1"));

    ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
    File xsltFileName1 = new File(System.getProperty("base.dir"), settings.get("xsltFileName1"));
    ByteArrayInputStream inputStream1 = new ByteArrayInputStream(rawData);
    // transformer.transformXML(inputStream1, xsltFileName1, outputStream1, settings);
    logger.info("First transformation finished");
    File outputFile1 = new File(graphmlDir, "bgpPeeringMap-intermediate.xml");

    FileUtils.writeStringToFile(outputFile1, new String(outputStream1.toByteArray()));

    logger.info("Second transformation started with xsltTransformator " + settings.get("xsltFileName2"));

    ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
    File xsltFileName2 = new File(System.getProperty("base.dir"), settings.get("xsltFileName2"));
    ByteArrayInputStream inputStream2 = new ByteArrayInputStream(outputStream1.toByteArray());
    // transformer.transformXML(inputStream2, xsltFileName2, outputStream2, settings);
    logger.info("Second transformation finished");
    File outputFile = new File(graphmlDir, "bgpPeeringMap.graphml");
    File nodesFileListFile = new File(graphmlDir, "nodes-file-list.txt");
    FileUtils.writeStringToFile(outputFile, new String(outputStream2.toByteArray()));
    logger.info("Output Graphml saved in a file in" + graphmlDir);

    FileUtils.writeStringToFile(nodesFileListFile, "bgpPeeringMap.graphml");

    ByteArrayInputStream inputStream3 = new ByteArrayInputStream(outputStream2.toByteArray());
    ByteArrayOutputStream outputStream3 = new ByteArrayOutputStream();
    File xsltFileName3 = new File(System.getProperty("base.dir"), settings.get("xsltFileName3"));
    // transformer.transformXML(inputStream3, xsltFileName3, outputStream3);

}

From source file:br.eti.kinoshita.xstream.Bird.java

public static void main(String[] args) throws Exception {
    XStream xs = new XStream();
    File f = new File("/tmp/bird2.xml");
    xs.registerConverter(new Converter() {

        public boolean canConvert(Class type) {
            return type.equals(Bird.class);
        }//ww w.j a  va2  s.co m

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
            Object beak = null;
            Object feathers = null;
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                if (reader.getNodeName().equals("beak")) {
                    beak = reader.getValue();
                }
                if (reader.getNodeName().equals("feathers")) {
                    feathers = reader.getValue();
                }
            }
            Bird bird = new Bird(beak, feathers);
            return bird;
        }

        public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
            Bird bird = (Bird) source;
            writer.startNode("beak");
            writer.setValue(bird.getBeak() == null ? "" : bird.getBeak().toString());
            writer.endNode();
            writer.startNode("feathers");
            writer.setValue(bird.getFeathers() == null ? "" : bird.getFeathers().toString());
            writer.endNode();
        }
    });
    Bird bird = new Bird(new Object(), new String("many"));
    String s = xs.toXML(bird);
    System.out.println(s);
    FileUtils.write(f, s);
    Bird anotherBird = (Bird) xs.fromXML(f);
    System.out.println(anotherBird);
}

From source file:ByteBuffer.java

public static void main(String[] args) {
    ByteBuffer bb = new ByteBuffer();

    bb.add("Robert".getBytes());
    bb.add("Cosmo".getBytes());
    bb.add("Ilardi".getBytes());

    System.out.println(new String(bb.getBytes()));
    System.out.println(new String(bb.remove(7)));
    System.out.println(new String(bb.getBytes()));

    bb.clear();//from  w ww.  j  av a2  s.c o  m
    System.out.println(new String(bb.getBytes()));

    bb.add("Robert".getBytes());
    System.out.println(new String(bb.getBytes()));
    System.out.println(new String(bb.remove(3)));
    System.out.println(new String(bb.getBytes()));
    System.out.println(new String(bb.remove(3)));
    System.out.println(new String(bb.getBytes()));

    bb.add("Robert".getBytes());
    System.out.println(new String(bb.remove(6)));
    System.out.println(new String(bb.getBytes()));

    bb.add("Robert C. Ilardi".getBytes());
    System.out.println("|" + new String(bb.remove(100)) + "|");
    System.out.println(new String(bb.getBytes()));
}

From source file:net.itransformers.snmp2xml4j.snmptoolkit.XsltExecutor.java

/**
 * <p>main.</p>/*  ww w.  ja v  a2s.  c  om*/
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.io.IOException if any.
 */
public static void main(String[] args) throws IOException {

    if (args.length != 3 && args.length != 4) {
        System.out.println("Missing input parameters");
        System.out.println(
                " Example usage: xsltTransform.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml ");
        return;
    }

    String inputXslt = args[0];
    if (inputXslt == null) {
        System.out.println("Missing input xslt file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }
    String inputFilePath = args[1];
    if (inputFilePath == null) {
        System.out.println("Missing input xml file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }

    String outputFilePath = args[2];
    if (outputFilePath == null) {
        System.out.println("Missing output file path");
        System.out.println(
                " Example usage: xsltTransformer.sh /home/test/test.xslt /usr/data/Input.xml /usr/data/Output.xml");
        return;
    }
    Map params = new HashMap<String, String>();
    if (args.length == 4) {
        String deviceOS = args[3];
        if (deviceOS != null) {
            params.put("DeviceOS", deviceOS);

        }
    }
    ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
    File xsltFileName1 = new File(inputXslt);

    FileInputStream inputStream1 = new FileInputStream(new File(inputFilePath));

    XsltTransformer xsltTransformer = new XsltTransformer();
    try {
        xsltTransformer.transformXML(inputStream1, xsltFileName1, outputStream1, params);
    } catch (TransformerException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    FileUtils.writeStringToFile(new File(outputFilePath), new String(outputStream1.toByteArray()));

    System.out.println("Done! please review the transformed file " + outputFilePath);

}