Example usage for java.lang System in

List of usage examples for java.lang System in

Introduction

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

Prototype

InputStream in

To view the source code for java.lang System in.

Click Source Link

Document

The "standard" input stream.

Usage

From source file:edu.oregonstate.eecs.mcplan.domains.tetris.TetrisVisualization.java

/**
 * @param args//  w  ww  . j ava  2s.co m
 * @throws IOException
 * @throws NumberFormatException
 */
public static void main(final String[] args) throws NumberFormatException, IOException {

    //      final int[][] cells = new int[][] {
    //         new int[] { 1, 2, 3, 0, 4, 5, 0, 0, 0, 6 },
    //         new int[] { 0, 7, 0, 0, 8, 9, 0, 0, 0, 1 },
    //         new int[] { 2, 3, 4, 5, 0, 0, 0, 0, 4, 3 },
    //         new int[] { 0, 0, 0, 0, 1, 2, 0, 0, 2, 9 },
    //         new int[] { 0, 0, 0, 0, 3, 4, 0, 0, 8, 7 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 5, 0, 0 }
    //      };

    // This one tests cascading block falls
    //      final int[][] cells = new int[][] {
    //         new int[] { 2, 2, 2, 2, 2, 2, 0, 2, 2, 2 },
    //         new int[] { 3, 0, 0, 1, 8, 9, 1, 1, 1, 1 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 1, 0, 1, 3 },
    //         new int[] { 0, 4, 4, 0, 0, 0, 1, 0, 1, 9 },
    //         new int[] { 0, 0, 4, 0, 0, 0, 0, 1, 8, 7 },
    //         new int[] { 0, 0, 4, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    //         new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
    //      };

    //      for( int y = 0; y < cells.length; ++y ) {
    //         for( int x = 0; x < TetrisState.Ncolumns; ++x ) {
    //            s.cells[y][x] = cells[y][x];
    //         }
    //      }

    final int T = 50;
    final int Nrows = 10;
    final RandomGenerator rng = new MersenneTwister(43);
    final TetrisParameters params = new TetrisParameters(T, Nrows);
    final TetrisFsssModel model = new TetrisFsssModel(rng, params, new TetrisBertsekasRepresenter(params));
    TetrisState s = model.initialState();

    //      for( final TetrominoType type : TetrominoType.values() ) {
    //         final Tetromino t = type.create();
    //         for( int r = 0; r < 4; ++r ) {
    //            for( int x = 0; x < TetrisState.Ncolumns; ++x ) {
    //               s = model.initialState();
    ////               Fn.assign( s.cells, 0 );
    //               s.queued_tetro = t;
    //
    //               System.out.println( "" + type + ", " + x + ", " + r );
    //
    //               final TetrisAction a = new TetrisAction( x, r );
    //               a.doAction( s );
    //
    ////               try {
    ////                  t.setCells( s, 1 );
    ////               }
    ////               catch( final TetrisGameOver ex ) {
    ////                  // TODO Auto-generated catch block
    ////                  ex.printStackTrace();
    ////               }
    //               System.out.println( s );
    //            }
    //         }
    //      }

    int steps = 0;
    while (!s.isTerminal()) {
        System.out.println(s);
        System.out.println(model.base_repr().encode(s));

        //         final int t = rng.nextInt( TetrominoType.values().length );
        //         final int r = rng.nextInt( 4 );
        //         final Tetromino tetro = TetrominoType.values()[t].create();
        //         tetro.setRotation( r );
        //         System.out.println( "Next:" );
        //         System.out.println( tetro );

        //         final int input_position = rng.nextInt( params.Ncolumns );
        //         final int input_rotation = rng.nextInt( 4 );

        // This move sequence produces a cascading clear for seed=43:
        // 00 41 21 60 91 73 41 01 01 61 83 53 23 31

        System.out.print(">>> ");
        final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        final int choice = Integer.parseInt(cin.readLine());
        final int input_position = choice / 10;
        final int input_rotation = choice - (input_position * 10);

        final TetrisAction a = new TetrisAction(input_position, input_rotation);
        System.out.println("Input: " + a);

        final TetrisState sprime = model.sampleTransition(s, a);
        s = sprime;

        //         tetro.setPosition( input_position, TetrisState.Nrows - 1 - tetro.getBoundingBox().top );
        //         tetro.setRotation( input_rotation );
        //         s.createTetromino( tetro );

        ++steps;

        if (s.isTerminal()) {
            break;
        }

        //         System.out.println( s );
        //         System.out.println();
        //         final int clears = s.drop();
        //         if( clears > 0 ) {
        //            System.out.println( "\tCleared " + clears );
        //         }
    }

    System.out.println("Steps: " + steps);

}

From source file:de.micromata.genome.tpsb.executor.GroovyShellExecutor.java

public static void main(String[] args) {
    String methodName = null;//from w w w.j  a v a  2s  .  c om
    if (args.length > 0 && StringUtils.isNotBlank(args[0])) {
        methodName = args[0];
    }
    GroovyShellExecutor exec = new GroovyShellExecutor();
    //System.out.println("GroovyShellExecutor start");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line;
    StringBuffer code = new StringBuffer();
    try {
        while ((line = in.readLine()) != null) {
            if (line.equals("--EOF--") == true) {
                break;
            }
            code.append(line);
            code.append("\n");

            //System.out.flush();
        }
    } catch (IOException ex) {
        throw new RuntimeException("Failure reading std in: " + ex.toString(), ex);
    }
    try {
        exec.executeCode(code.toString(), methodName);
    } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework
        warn("GroovyShellExecutor failed with exception: " + ex.getClass().getName() + ": " + ex.getMessage()
                + "\n" + ExceptionUtils.getStackTrace(ex));
    }
    System.out.println("--EOP--");
    System.out.flush();
}

From source file:edu.asu.bscs.csiebler.calculatorrpc.CalcJavaClient.java

public static void main(String args[]) {
    try {//from   ww  w  .ja v  a2 s  .com
        String url = "http://127.0.0.1:8080/";
        if (args.length > 0) {
            url = args[0];
        }
        CalcJavaClient cjc = new CalcJavaClient(url);
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
        String inStr = stdin.readLine();
        StringTokenizer st = new StringTokenizer(inStr);
        String opn = st.nextToken();
        while (!opn.equalsIgnoreCase("end")) {
            if (opn.equalsIgnoreCase("+")) {
                double result = cjc.add(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("-")) {
                double result = cjc.subtract(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("*")) {
                double result = cjc.multiply(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("/")) {
                double result = cjc.divide(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            }
            System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
            inStr = stdin.readLine();
            st = new StringTokenizer(inStr);
            opn = st.nextToken();
        }
    } catch (Exception e) {
        System.out.println("Oops, you didn't enter the right stuff");
    }
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);//from ww  w  .  ja va2s.c  o  m
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFALogP.java

/**
 * @param args/*ww w.ja va2 s . c om*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_SMARTS_FILE, true, "Optional: to overwrite atom type definition file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_PRINT_COUNTS, false,
            "If set the count of each atom type is added to the output file.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_VALIDATE_ASSIGNMENT, false,
            "Print warning if no atomtype matches an atom in a candidte molecule.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SUPRESS_ZERO, false, "If given atom type counts with count=0 will not be added.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_NEUTRALIZE, true, "y|n to neutralize molecule if possible (default=y)");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smartsFile = cmd.getOptionValue(OPT_SMARTS_FILE);
    boolean outputCount = cmd.hasOption(OPT_PRINT_COUNTS);
    boolean outputZero = !cmd.hasOption(OPT_SUPRESS_ZERO);
    boolean neutralize = !"n".equalsIgnoreCase(cmd.getOptionValue(OPT_NEUTRALIZE));
    boolean ValidateAssignment = cmd.hasOption(OPT_VALIDATE_ASSIGNMENT);

    SDFALogP sdfALogP = new SDFALogP(smartsFile, outFile, outputZero, neutralize, ValidateAssignment);

    sdfALogP.run(inFile, outputCount);
    sdfALogP.close();
}

From source file:org.dspace.app.cris.batch.ScriptDeleteRP.java

/**
 * Batch script to delete a RP. See the technical documentation for further
 * details.// w  w  w . j  ava 2 s .  c o  m
 */
public static void main(String[] args) {
    log.info("#### START DELETE: -----" + new Date() + " ----- ####");
    Context dspaceContext = null;
    ApplicationContext context = null;
    try {
        dspaceContext = new Context();
        dspaceContext.turnOffAuthorisationSystem();

        DSpace dspace = new DSpace();
        ApplicationService applicationService = dspace.getServiceManager()
                .getServiceByName("applicationService", ApplicationService.class);

        CommandLineParser parser = new PosixParser();

        Options options = new Options();
        options.addOption("h", "help", false, "help");

        options.addOption("r", "researcher", true, "RP id to delete");

        options.addOption("s", "silent", false, "no interactive mode");

        CommandLine line = parser.parse(options, args);

        if (line.hasOption('h')) {
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("ScriptHKURPDelete \n", options);
            System.out.println("\n\nUSAGE:\n ScriptHKURPDelete -r <id> \n");
            System.out.println("Please note: add -s for no interactive mode");
            System.exit(0);
        }

        Integer rpId = null;
        boolean delete = false;
        boolean silent = line.hasOption('s');
        Item[] items = null;
        if (line.hasOption('r')) {
            rpId = ResearcherPageUtils.getRealPersistentIdentifier(line.getOptionValue("r"),
                    ResearcherPage.class);
            ResearcherPage rp = applicationService.get(ResearcherPage.class, rpId);

            if (rp == null) {
                if (!silent) {
                    System.out.println("RP not exist...exit");
                }
                log.info("RP not exist...exit");
                System.exit(0);
            }

            log.info("Use browse indexing");

            BrowseIndex bi = BrowseIndex.getBrowseIndex(plugInBrowserIndex);
            // now start up a browse engine and get it to do the work for us
            BrowseEngine be = new BrowseEngine(dspaceContext);

            String authKey = ResearcherPageUtils.getPersistentIdentifier(rp);

            // set up a BrowseScope and start loading the values into it
            BrowserScope scope = new BrowserScope(dspaceContext);
            scope.setBrowseIndex(bi);
            // scope.setOrder(order);
            scope.setFilterValue(authKey);
            scope.setAuthorityValue(authKey);
            scope.setResultsPerPage(Integer.MAX_VALUE);
            scope.setBrowseLevel(1);

            BrowseInfo binfo = be.browse(scope);
            log.debug("Find " + binfo.getResultCount() + "item(s) for the reseracher " + authKey);
            items = binfo.getItemResults(dspaceContext);

            if (!silent && rp != null) {
                System.out.println(MESSAGE_ONE);

                // interactive mode
                System.out.println("Attempting to remove Researcher Page:");
                System.out.println("StaffNo:" + rp.getSourceID());
                System.out.println("FullName:" + rp.getFullName());
                System.out
                        .println("the researcher has " + items.length + " relation(s) with item(s) in the HUB");
                System.out.println();

                System.out.println(QUESTION_ONE);
                InputStreamReader isr = new InputStreamReader(System.in);
                BufferedReader reader = new BufferedReader(isr);
                String answer = reader.readLine();
                if (answer.equals("yes")) {
                    delete = true;
                } else {
                    System.out.println("Exit without delete");
                    log.info("Exit without delete");
                    System.exit(0);
                }

            } else {
                delete = true;
            }
        } else {
            System.out.println("\n\nUSAGE:\n ScriptHKURPDelete <-v> -r <RPid> \n");
            System.out.println("-r option is mandatory");
            log.error("-r option is mandatory");
            System.exit(1);
        }

        if (delete) {
            if (!silent) {
                System.out.println("Deleting...");
            }
            log.info("Deleting...");
            cleanAuthority(dspaceContext, items, rpId);
            applicationService.delete(ResearcherPage.class, rpId);
            dspaceContext.complete();
        }

        if (!silent) {
            System.out.println("Ok...Bye");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (dspaceContext != null && dspaceContext.isValid()) {
            dspaceContext.abort();
        }
        if (context != null) {
            context.publishEvent(new ContextClosedEvent(context));
        }
    }
    log.info("#### END: -----" + new Date() + " ----- ####");
    System.exit(0);
}

From source file:it.unimi.di.big.mg4j.document.WarcDocumentSequence_NYU.java

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

    SimpleJSAP jsap = new SimpleJSAP(WarcDocumentSequence_NYU.class.getName(),
            "Saves a serialised Warc document sequence based on a set of file names.",
            new Parameter[] {
                    new FlaggedOption("factory", JSAP.CLASS_PARSER, IdentityDocumentFactory.class.getName(),
                            JSAP.NOT_REQUIRED, 'f', "factory",
                            "A document factory with a standard constructor."),
                    new FlaggedOption("property", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'p',
                            "property", "A 'key=value' specification, or the name of a property file")
                                    .setAllowMultipleDeclarations(true),
                    new Switch("gzip", 'z', "gzip",
                            "Expect gzip-ed WARC content (files should end in .warc.gz)."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, DEFAULT_BUFFER_SIZE, JSAP.NOT_REQUIRED,
                            'b', "buffer-size", "The size of an I/O buffer."),
                    new UnflaggedOption("sequence", JSAP.STRING_PARSER, JSAP.REQUIRED,
                            "The filename for the serialized sequence."),
                    new UnflaggedOption("basename", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            JSAP.GREEDY,
                            "A list of basename files that will be indexed. If missing, a list of files will be read from standard input.") });

    final JSAPResult jsapResult = jsap.parse(args);
    if (jsap.messagePrinted())
        System.exit(1);//from  w w w .jav  a2s .  c  om

    final DocumentFactory factory = PropertyBasedDocumentFactory.getInstance(jsapResult.getClass("factory"),
            jsapResult.getStringArray("property"));
    final boolean isGZipped = jsapResult.getBoolean("gzip");

    String[] file = jsapResult.getStringArray("basename");
    if (file.length == 0)
        file = IOUtils.readLines(System.in).toArray(new String[0]);
    if (file.length == 0)
        LOGGER.warn("Empty fileset");

    BinIO.storeObject(new WarcDocumentSequence_NYU(file, factory, isGZipped, jsapResult.getInt("bufferSize")),
            jsapResult.getString("sequence"));
}

From source file:eu.openanalytics.rsb.SuiteITCase.java

/**
 * To help with any sort of manual testing.
 *///from w ww . j  a  v a2s. c  om
public static void main(final String[] args) throws Exception {
    setupTestSuite();

    System.out.println("Type ENTER to stop testing...");
    final Scanner scanner = new Scanner(System.in);
    scanner.nextLine();
    scanner.close();

    teardownTestSuite();
}

From source file:com.google.oacurl.Fetch.java

public static void main(String[] args) throws Exception {
    FetchOptions options = new FetchOptions();
    CommandLine line = options.parse(args);
    args = line.getArgs();//from   w ww  .  j  a  va 2s  . co m

    if (options.isHelp()) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(0);
    }

    if (args.length != 1) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(-1);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isVerbose()) {
        LoggingConfig.enableWireLog();
    }

    String url = args[0];

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao();
    AccessorDao accessorDao = new AccessorDao();

    Properties loginProperties = null;
    try {
        loginProperties = new PropertiesProvider(options.getLoginFileName()).get();
    } catch (FileNotFoundException e) {
        System.err.println(".oacurl.properties file not found in homedir");
        System.err.println("Make sure you've run oacurl-login first!");
        System.exit(-1);
    }

    OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider();
    OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider);
    OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer);

    OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL));

    OAuthVersion version = (loginProperties.containsKey("oauthVersion"))
            ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion"))
            : OAuthVersion.V1;

    OAuthEngine engine;
    switch (version) {
    case V1:
        engine = new V1OAuthEngine();
        break;
    case V2:
        engine = new V2OAuthEngine();
        break;
    case WRAP:
        engine = new WrapOAuthEngine();
        break;
    default:
        throw new IllegalArgumentException("Unknown version: " + version);
    }

    try {
        OAuthMessage request;

        List<Entry<String, String>> related = options.getRelated();

        Method method = options.getMethod();
        if (method == Method.POST || method == Method.PUT) {
            InputStream bodyStream;
            if (related != null) {
                bodyStream = new MultipartRelatedInputStream(related);
            } else if (options.getFile() != null) {
                bodyStream = new FileInputStream(options.getFile());
            } else {
                bodyStream = System.in;
            }
            request = newRequestMessage(accessor, method, url, bodyStream, engine);
            request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType()));
        } else {
            request = newRequestMessage(accessor, method, url, null, engine);
        }

        List<Parameter> headers = options.getHeaders();
        addHeadersToRequest(request, headers);

        HttpResponseMessage httpResponse;
        if (version == OAuthVersion.V1) {
            OAuthResponseMessage response;
            response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
            httpResponse = response.getHttpResponse();
        } else {
            HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL),
                    request.getBodyAsStream());
            httpRequest.headers.addAll(request.getHeaders());
            httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters());
            httpResponse = HttpMessageDecoder.decode(httpResponse);
        }

        System.err.flush();

        if (options.isInclude()) {
            Map<String, Object> dump = new HashMap<String, Object>();
            httpResponse.dump(dump);
            System.out.print(dump.get(HttpMessage.RESPONSE));
        }

        // Dump the bytes in the response's encoding.
        InputStream bodyStream = httpResponse.getBody();
        byte[] buf = new byte[1024];
        int count;
        while ((count = bodyStream.read(buf)) > -1) {
            System.out.write(buf, 0, count);
        }
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    }
}

From source file:com.vmware.fdmsecprotomgmt.PasswdEncrypter.java

/**
 * Entry point into this Class//from w w w .  j av  a2 s . co  m
 */
public static void main(String[] args) {
    boolean validVals = false;
    String secretKey = "";
    String esxi_pwd = "";
    System.out.println("This Utility program would help you to ENCRYPT password with a given secretKey");
    Scanner in = new Scanner(System.in);
    System.out.print("Enter ESXi host password:");
    esxi_pwd = in.nextLine().trim();
    if (esxi_pwd.equals("")) {
        System.err.println("Invalid password entry, please try again ...");
    } else {
        System.out.println(
                "Enter SecretKey to be used for encrypting ESXi Password. MUST NOT exceed 16 characters,"
                        + "and should be different from ESXi password; for better security");
        secretKey = in.nextLine().trim();

        if (secretKey.equals("")) {
            System.err.println("Invalid SecretKey entry, please try again ...");
        } else if (secretKey.length() > STD_KEYSIZE) {
            System.err.println("SecretKey can NOT exceed 16 characters. Please try again");
        } else if (secretKey.length() < STD_KEYSIZE) {
            int remainingChars = STD_KEYSIZE - secretKey.length();
            while (remainingChars > 0) {
                secretKey = secretKey + PADDING_ARRAY[remainingChars];
                --remainingChars;
            }
        }
        if (secretKey.length() == STD_KEYSIZE) {
            validVals = true;
        }
    }

    // Go for encrypting the password with provided SecretKey
    if (validVals) {
        String encryptedStr = encrypt(secretKey, esxi_pwd);
        if ((!encryptedStr.equals(""))) {
            // Validate that on decrypt, you would receive the same password
            String decryptedStr = decrypt(secretKey, encryptedStr);
            if (!decryptedStr.equals("")) {
                if (decryptedStr.equals(esxi_pwd)) {
                    System.out.println("Successfully encrypted the password");
                    System.out.println("----------------------------------------------------------------");
                    System.out.println("ESXi Password: " + esxi_pwd);
                    System.out.println("Your Secret key: " + secretKey);
                    System.out.println("Encrypted String for the password: " + encryptedStr);
                    System.out.println("[TESTED] Decrypted string: " + decryptedStr);
                    System.out.println("----------------------------------------------------------------");
                    System.out.println("**** NOTE ****");
                    System.out.println(
                            "Please remember the secretkey, which is later needed when running TLS-Configuration script");
                } else {
                    System.err.println("Failed to match the password with decrypted string");
                }
            } else {
                System.err.println("Failed to decrypt the encrypted string");
            }
        } else {
            System.err.println("Failed to encrypt the provided password");
        }
    }
    // close the scanner
    in.close();
}