Example usage for java.io IOException printStackTrace

List of usage examples for java.io IOException printStackTrace

Introduction

In this page you can find the example usage for java.io IOException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:ServeurFTP.java

public static void main(String[] args) {
    String server1, username1, password1, file1;
    String server2, username2, password2, file2;
    String[] parts;// w ww .ja v a2 s.c  o m
    int port1 = 0, port2 = 0;
    FTPClient ftp1, ftp2;
    ProtocolCommandListener listener;

    if (args.length < 8) {
        System.err.println("Usage: ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>");
        System.exit(1);
    }

    server1 = args[0];
    parts = server1.split(":");
    if (parts.length == 2) {
        server1 = parts[0];
        port1 = Integer.parseInt(parts[1]);
    }
    username1 = args[1];
    password1 = args[2];
    file1 = args[3];
    server2 = args[4];
    parts = server2.split(":");
    if (parts.length == 2) {
        server2 = parts[0];
        port2 = Integer.parseInt(parts[1]);
    }
    username2 = args[5];
    password2 = args[6];
    file2 = args[7];

    listener = new PrintCommandListener(new PrintWriter(System.out), true);
    ftp1 = new FTPClient();
    ftp1.addProtocolCommandListener(listener);
    ftp2 = new FTPClient();
    ftp2.addProtocolCommandListener(listener);

    try {
        int reply;
        if (port1 > 0) {
            ftp1.connect(server1, port1);
        } else {
            ftp1.connect(server1);
        }
        System.out.println("Connected to " + server1 + ".");

        reply = ftp1.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp1.disconnect();
            System.err.println("FTP server1 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp1.isConnected()) {
            try {
                ftp1.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server1.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        int reply;
        if (port2 > 0) {
            ftp2.connect(server2, port2);
        } else {
            ftp2.connect(server2);
        }
        System.out.println("Connected to " + server2 + ".");

        reply = ftp2.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp2.disconnect();
            System.err.println("FTP server2 refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp2.isConnected()) {
            try {
                ftp2.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server2.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp1.login(username1, password1)) {
            System.err.println("Could not login to " + server1);
            break __main;
        }

        if (!ftp2.login(username2, password2)) {
            System.err.println("Could not login to " + server2);
            break __main;
        }

        // Let's just assume success for now.
        ftp2.enterRemotePassiveMode();

        ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort());

        // Although you would think the store command should be sent to server2
        // first, in reality, ftp servers like wu-ftpd start accepting data
        // connections right after entering passive mode.  Additionally, they
        // don't even send the positive preliminary reply until after the
        // transfer is completed (in the case of passive mode transfers).
        // Therefore, calling store first would hang waiting for a preliminary
        // reply.
        if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) {
            //      if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
            // We have to fetch the positive completion reply.
            ftp1.completePendingCommand();
            ftp2.completePendingCommand();
        } else {
            System.err.println("Couldn't initiate transfer.  Check that filenames are valid.");
            break __main;
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            if (ftp1.isConnected()) {
                ftp1.logout();
                ftp1.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }

        try {
            if (ftp2.isConnected()) {
                ftp2.logout();
                ftp2.disconnect();
            }
        } catch (IOException e) {
            // do nothing
        }
    }
}

From source file:estimatePressure.EstimatePressureValues.java

public static void main(String[] args) {

    EstimatePressureValues training = new EstimatePressureValues();
    //initialize elm
    //training.elm = new ELM(training.inputDim, training.hiddenDim, training.outputDim, 0.1, 0.1);
    if (training.useAngles) {
        training.elm = new ELM(training.inputDim, training.hiddenDim, training.outputDim, 10.0, 0.1);
    } else {/*from  www.j  a  va  2 s  .c  o m*/
        training.elm = new ELM(training.inputDim, training.hiddenDim, training.outputDim, 1.0, 0.1);
    }

    //initialize list for elm
    training.trainingInputList = new ArrayList<ArrayList<Double>>();
    training.expectedValuesList = new ArrayList<ArrayList<Double>>();
    training.isTrainingPhase = true;

    // read data from file
    try {
        training.processFile();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (training.br != null)
                training.br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //put values to matrices
    training.trainingInput = Matrix.identity(training.inputDim, training.trainingInputList.size());
    training.expectedValues = Matrix.identity(training.outputDim, training.expectedValuesList.size());

    System.out.println("Training input list: ");
    for (int i = 0; i < training.inputDim; i++) {
        for (int j = 0; j < training.trainingInputList.size(); j++) {
            training.trainingInput.set(i, j, training.trainingInputList.get(j).get(i));
            System.out.print(training.trainingInput.get(i, j) + "\t");
        }
        System.out.println("");
    }
    System.out.println("Expected value list: ");
    for (int k = 0; k < training.outputDim; k++) {
        for (int n = 0; n < training.expectedValuesList.size(); n++) {
            training.expectedValues.set(k, n, training.expectedValuesList.get(n).get(k));
            System.out.print(training.expectedValues.get(k, n) + "\t");
        }
        System.out.println("");
    }

    // training the algorithm
    Matrix outputWeights = training.elm.train(training.trainingInput, training.expectedValues,
            training.numSample + 1);

    /*System.out.println("training output Wout is: ");
    for (int k = 0; k < outputWeights.getRowDimension(); k++) {
       for (int n = 0; n < outputWeights.getColumnDimension(); n++) {
    System.out.print(outputWeights.get(k, n) + "\t");
       }
       System.out.println("");
    }*/

    //----------execute the learning algorithm----------//
    EstimatePressureValues m2 = new EstimatePressureValues();
    //initialize elm
    //m2.elm = new ELM(m2.inputDim, m2.hiddenDim, m2.outputDim, 0.1, 0.1);
    if (m2.useAngles) {
        m2.elm = new ELM(m2.inputDim, m2.hiddenDim, m2.outputDim, 10.0, 0.1);
    } else {
        m2.elm = new ELM(m2.inputDim, m2.hiddenDim, m2.outputDim, 1.0, 0.1);
    }

    //initialize list for elm
    m2.trainingInputList = new ArrayList<ArrayList<Double>>();
    m2.expectedValuesList = new ArrayList<ArrayList<Double>>();
    m2.isTrainingPhase = false;

    // read data from file
    try {
        m2.processFile();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (m2.br != null)
                m2.br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //put values to matrices
    m2.trainingInput = Matrix.identity(m2.inputDim, m2.trainingInputList.size());
    m2.expectedValues = Matrix.identity(m2.outputDim, m2.expectedValuesList.size());

    System.out.println("Execution input list: ");
    for (int i = 0; i < m2.inputDim; i++) {
        for (int j = 0; j < m2.trainingInputList.size(); j++) {
            m2.trainingInput.set(i, j, m2.trainingInputList.get(j).get(i));
            System.out.print(m2.trainingInput.get(i, j) + "\t");
        }
        System.out.println("");
    }
    System.out.println("Execution actual output value list: ");
    for (int i = 0; i < m2.outputDim; i++) {
        for (int j = 0; j < m2.expectedValuesList.size(); j++) {
            m2.expectedValues.set(i, j, m2.expectedValuesList.get(j).get(i));
            System.out.print(m2.expectedValues.get(i, j) + "\t");
        }
        System.out.println("");
    }

    //execute
    m2.predictPressureValues(m2.trainingInput, outputWeights, m2.expectedValues);
    //m2.predictPressureValues(outputWeights);

}

From source file:com.iciql.test.IciqlSuite.java

/**
 * Main entry point for the test suite. Executing this method will run the
 * test suite on all registered databases.
 * // w w  w  .j a  v a2  s  .c  om
 * @param args
 * @throws Exception
 */
public static void main(String... args) throws Exception {
    Params params = new Params();
    JCommander jc = new JCommander(params);
    try {
        jc.parse(args);
    } catch (ParameterException t) {
        usage(jc, t);
    }

    // Replace System.out with a file
    if (!StringUtils.isNullOrEmpty(params.dbPerformanceFile)) {
        out = new PrintStream(params.dbPerformanceFile);
        System.setErr(out);
    }

    deleteRecursively(new File("testdbs"));

    // Start the HSQL and H2 servers in-process
    org.hsqldb.Server hsql = startHSQL();
    org.h2.tools.Server h2 = startH2();

    // Statement logging
    final FileWriter statementWriter;
    if (StringUtils.isNullOrEmpty(params.sqlStatementsFile)) {
        statementWriter = null;
    } else {
        statementWriter = new FileWriter(params.sqlStatementsFile);
    }
    IciqlListener statementListener = new IciqlListener() {
        @Override
        public void logIciql(StatementType type, String statement) {
            if (statementWriter == null) {
                return;
            }
            try {
                statementWriter.append(statement);
                statementWriter.append('\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    IciqlLogger.registerListener(statementListener);

    SuiteClasses suiteClasses = IciqlSuite.class.getAnnotation(SuiteClasses.class);
    long quickestDatabase = Long.MAX_VALUE;
    String dividerMajor = buildDivider('*', 79);
    String dividerMinor = buildDivider('-', 79);

    // Header
    out.println(dividerMajor);
    out.println(MessageFormat.format("{0} {1} ({2}) testing {3} database configurations", Constants.NAME,
            Constants.VERSION, Constants.VERSION_DATE, TEST_DBS.length));
    out.println(dividerMajor);
    out.println();

    showProperty("java.vendor");
    showProperty("java.runtime.version");
    showProperty("java.vm.name");
    showProperty("os.name");
    showProperty("os.version");
    showProperty("os.arch");
    showProperty("available processors", "" + Runtime.getRuntime().availableProcessors());
    showProperty("available memory", MessageFormat.format("{0,number,0.0} GB",
            ((double) Runtime.getRuntime().maxMemory()) / (1024 * 1024)));
    out.println();

    // Test a database
    long lastCount = 0;
    for (TestDb testDb : TEST_DBS) {
        out.println(dividerMinor);
        out.println("Testing " + testDb.describeDatabase());
        out.println("        " + testDb.url);
        out.println(dividerMinor);

        // inject a database section delimiter in the statement log
        if (statementWriter != null) {
            statementWriter.append("\n\n");
            statementWriter.append("# ").append(dividerMinor).append('\n');
            statementWriter.append("# ").append("Testing " + testDb.describeDatabase()).append('\n');
            statementWriter.append("# ").append(dividerMinor).append('\n');
            statementWriter.append("\n\n");
        }

        if (testDb.getVersion().equals("OFFLINE")) {
            // Database not available
            out.println("Skipping.  Could not find " + testDb.url);
            out.println();
        } else {
            // Setup system properties
            System.setProperty("iciql.url", testDb.url);
            System.setProperty("iciql.user", testDb.username);
            System.setProperty("iciql.password", testDb.password);

            // Test database
            Result result = JUnitCore.runClasses(suiteClasses.value());

            // Report results
            testDb.runtime = result.getRunTime();
            if (testDb.runtime < quickestDatabase) {
                quickestDatabase = testDb.runtime;
            }
            testDb.statements = IciqlLogger.getTotalCount() - lastCount;
            // reset total count for next database
            lastCount = IciqlLogger.getTotalCount();

            out.println(MessageFormat.format(
                    "{0} tests ({1} failures, {2} ignores)  {3} statements in {4,number,0.000} secs",
                    result.getRunCount(), result.getFailureCount(), result.getIgnoreCount(), testDb.statements,
                    result.getRunTime() / 1000f));

            if (result.getFailureCount() == 0) {
                out.println();
                out.println("  100% successful test suite run.");
                out.println();
            } else {
                for (Failure failure : result.getFailures()) {
                    out.println(MessageFormat.format("\n  + {0}\n    {1}", failure.getTestHeader(),
                            failure.getMessage()));
                }
                out.println();
            }
        }
    }

    // Display runtime results sorted by performance leader
    out.println();
    out.println(dividerMajor);
    out.println(MessageFormat.format("{0} {1} ({2}) test suite performance results", Constants.NAME,
            Constants.VERSION, Constants.VERSION_DATE));
    out.println(dividerMajor);
    List<TestDb> dbs = Arrays.asList(TEST_DBS);
    Collections.sort(dbs);

    out.println(MessageFormat.format("{0} {1} {2} {3} {4}", StringUtils.pad("Name", 11, " ", true),
            StringUtils.pad("Type", 5, " ", true), StringUtils.pad("Version", 23, " ", true),
            StringUtils.pad("Stats/Sec", 10, " ", true), "Runtime"));
    out.println(dividerMinor);
    for (TestDb testDb : dbs) {
        DecimalFormat df = new DecimalFormat("0.0");
        out.println(MessageFormat.format("{0} {1} {2}   {3} {4} {5}s  ({6,number,0.0}x)",
                StringUtils.pad(testDb.name, 11, " ", true), testDb.isEmbedded ? "E" : "T",
                testDb.isMemory ? "M" : "F", StringUtils.pad(testDb.getVersion(), 21, " ", true),
                StringUtils.pad("" + testDb.getStatementRate(), 10, " ", false),
                StringUtils.pad(df.format(testDb.getRuntime()), 8, " ", false),
                ((double) testDb.runtime) / quickestDatabase));
    }
    out.println(dividerMinor);
    out.println("  E = embedded connection");
    out.println("  T = tcp/ip connection");
    out.println("  M = memory database");
    out.println("  F = file/persistent database");

    // cleanup
    for (PoolableConnectionFactory factory : connectionFactories.values()) {
        factory.getPool().close();
    }
    IciqlLogger.unregisterListener(statementListener);
    out.close();
    System.setErr(ERR);
    if (statementWriter != null) {
        statementWriter.close();
    }
    hsql.stop();
    h2.stop();
    System.exit(0);
}

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;//from w ww .j a  v  a  2  s.co m

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

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

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:esg.node.util.migrate.UserMigrationTool.java

public static void main(String[] args) {
    try {//from w w  w.j  av a2 s .  c  o  m
        //Enter the connection URI information
        //setup source connection
        Properties props = new Properties();
        if (args.length >= 4) {
            for (int i = 0; i < (args.length - 1); i++) {
                System.out.println();
                if ("-U".equals(args[i])) {
                    i++;
                    System.out.print("user = ");
                    if (args[i].startsWith("-")) {
                        --i;
                        continue;
                    }
                    props.setProperty("db.user", args[i]);
                    System.out.print(args[i]);
                    continue;
                }
                if ("-h".equals(args[i])) {
                    i++;
                    System.out.print("host = ");
                    if (args[i].startsWith("-")) {
                        --i;
                        continue;
                    }
                    props.setProperty("db.host", args[i]);
                    System.out.print(args[i]);
                    continue;
                }
                if ("-p".equals(args[i])) {
                    i++;
                    System.out.print("port = ");
                    if (args[i].startsWith("-")) {
                        --i;
                        continue;
                    }
                    props.setProperty("db.port", args[i]);
                    System.out.print(args[i]);
                    continue;
                }
                if ("-d".equals(args[i])) {
                    i++;
                    System.out.print("database = ");
                    if (args[i].startsWith("-")) {
                        --i;
                        continue;
                    }
                    props.setProperty("db.database", args[i]);
                    System.out.print(args[i]);
                    continue;
                }
            }
            System.out.println();
        } else {
            System.out.println("\nUsage:");
            System.out.println(
                    "  java -jar esgf-security-user-migration-x.x.x.jar -U <username> -h <host> -p <port> -d <database>");
            System.out.println("  (hit return and then enter your password)\n");
            System.exit(1);
        }

        char password[] = null;
        try {
            password = PasswordField.getPassword(System.in, "Enter source database password: ");
        } catch (IOException ioe) {
            System.err.println("Ooops sumthin' ain't right with the input... :-(");
            System.exit(1);
            ioe.printStackTrace();
        }
        if (password == null) {
            System.out.println("No password entered");
            System.exit(1);
        }

        props.setProperty("db.password", String.valueOf(password));

        System.out.println();

        (new UserMigrationTool()).init(props).migrate();

    } catch (Throwable t) {
        System.out.println(t.getMessage());
        System.out.println(
                "\n Sorry, please check your database connection information again, was not able to migrate users :-(\n");
        System.exit(1);
    }

    System.out.println("\ndone :-)\n");
    System.out.println(" Thank you for migrating to the ESGF P2P Node");
    System.out.println(" http://esgf.org\n");
}

From source file:com.ieasy.basic.util.file.FileUtils.java

public static void main(String[] args) {
    //System.out.println(formetFileSize(755996)); ;
    String s = "D:\\work\\app_server\\tomcat-7.0.55\\temp\\backup\\";
    String t = "D:\\work\\app_server\\tomcat-7.0.55\\webapps\\ieasy\\attached\\ueditor\\";
    String t1 = "D:\\work\\app_server\\tomcat-7.0.55\\webapps\\ieasy\\attached\\emp_touxiang\\";
    try {//from w  ww.  j a v a  2  s .  c  o  m
        copyDirectoryToDirectory(new File(t), new File(s));
        copyDirectoryToDirectory(new File(t1), new File(s));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:examples.mail.IMAPMail.java

public static void main(String[] args) {
    if (args.length < 3) {
        System.err.println("Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
        System.exit(1);// w  w w .j  av a  2 s.  c  o m
    }

    String server = args[0];
    String username = args[1];
    String password = args[2];

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    imap.setDefaultTimeout(60000);

    // suppress login details
    imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        imap.capability();

        imap.select("inbox");

        imap.examine("inbox");

        imap.status("inbox", new String[] { "MESSAGES" });

        imap.logout();
        imap.disconnect();
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:SheetStructure.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here.

    try {/*from   w w  w  .j av  a  2  s.  c  o m*/

        System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale...");
        //First Create a new sheet.
        String sheetName = "Betty's Bake Sale";
        //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON.
        //Their structure directly relates to the JSON that gets passed through the API.
        //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out.
        Sheet newSheet = new Sheet();
        newSheet.setName(sheetName);
        newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null),
                new Column("Baker", "CONTACT_LIST", null, null, null),
                new Column("Price Per Item", "TEXT_NUMBER", null, null, null),
                new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST",
                        null, null, Arrays.asList("Started", "Finished", "Delivered"))));
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Sheet>>() {
                });
        newSheet = newSheetResult.getResult();
        System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId());

        //Now add a column:
        String columnName = "Delivery Date";
        System.out.println("Adding column " + columnName + " to " + sheetName);
        Column newColumn = new Column(columnName, "DATE", 5);

        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newColumn);
        Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });

        System.out.println(
                "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName());

        //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it.
        System.out.println("Fetching " + newSheet.getName() + " sheet columns...");
        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        List<Column> allColumns = mapper.readValue(connection.getInputStream(),
                new TypeReference<List<Column>>() {
                });
        System.out.println("Fetched.");

        //Now we will be adding rows
        System.out.println("Inserting rows into " + newSheet.getName());
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"),
                new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"),
                new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-04"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"),
                new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Started"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"),
                new Cell(allColumns.get(1).id, "sandrassmart@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE),
                new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"),
                new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-05"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"),
                new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"),
                new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created.

        RowWrapper rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move a row to the top.
        System.out.println("Moving row 6 to the top.");
        RowWrapper moveToTop = new RowWrapper();
        moveToTop.setToTop(true);

        connection = (HttpURLConnection) new URL(
                ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection();
        connection.setRequestMethod("PUT");
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), moveToTop);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
        });

        System.out.println("Row 6 moved to top.");

        //Insert empty rows for spacing
        rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, ""))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move Delivered rows to be children of the last spacer row.
        System.out.println("Moving delivered rows to Delivered section...");
        Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(),
                newRowsResult.result.get(4).getId() };
        RowWrapper parentRowLocation = new RowWrapper();
        parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId());

        for (Long deliveredId : deliveredRowIds) {
            System.out.println("Moving " + deliveredId + " to Delivered.");
            connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection();
            connection.setRequestMethod("PUT");
            connection.addRequestProperty("Authorization", "Bearer " + accessToken);
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            mapper.writeValue(connection.getOutputStream(), parentRowLocation);
            mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
            });
            System.out.println("Row id " + deliveredId + " moved.");
        }

        System.out.println("Appending additional rows to items in progress...");

        List<Row> siblingRows = new ArrayList<Row>();
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"),
                new Cell(allColumns.get(1).id, "tomlively@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Finished"))));
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId());
        rowWrapper.setRows(siblingRows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName());

        System.out.println("Moving Status column to index 1...");
        Column statusColumn = allColumns.get(4);
        Column moveColumn = new Column();
        moveColumn.setIndex(1);
        moveColumn.setTitle(statusColumn.title);
        moveColumn.setSheetId(newSheet.getId());
        moveColumn.setType(statusColumn.getType());
        connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        mapper.writeValue(connection.getOutputStream(), moveColumn);
        Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });
        System.out.println("Moved column " + movedColumnResult.getResult().getId());
        System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale.");
    } catch (IOException e) {
        InputStream is = ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:edu.umn.cs.spatialHadoop.operations.KNN.java

public static void main(String[] args) throws IOException {
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*  w  w w.  j av a  2s.  com*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    int count = params.getInt("count", 1);
    double closeness = params.getFloat("closeness", -1.0f);
    final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
    final FileSystem fs = inputFile.getFileSystem(params);
    final int k = params.getInt("k", 1);
    int concurrency = params.getInt("concurrency", 100);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (queryPoints.length == 0) {
        printUsage();
        throw new RuntimeException("Illegal arguments");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;

    if (closeness >= 0) {
        // Get query points according to its closeness to grid intersections
        GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
        long seed = params.getLong("seed", System.currentTimeMillis());
        Random random = new Random(seed);
        for (int i = 0; i < count; i++) {
            int i_block = random.nextInt(gindex.size());
            int direction = random.nextInt(4);
            // Generate a point in the given direction
            // Get center point (x, y)
            Iterator<Partition> iterator = gindex.iterator();
            while (i_block-- >= 0)
                iterator.next();
            Partition partition = iterator.next();
            double cx = (partition.x1 + partition.x2) / 2;
            double cy = (partition.y1 + partition.y2) / 2;
            double cw = partition.x2 - partition.x1;
            double ch = partition.y2 - partition.y1;
            int signx = ((direction & 1) == 0) ? 1 : -1;
            int signy = ((direction & 2) == 1) ? 1 : -1;
            double x = cx + cw * closeness / 2 * signx;
            double y = cy + ch * closeness / 2 * signy;
            queryPoints[i] = new Point(x, y);
        }
    }

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    // Run each query in a separate thread
    final Vector<Thread> threads = new Vector<Thread>();
    for (int i = 0; i < queryPoints.length; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Point query_point = queryPoints[threads.indexOf(this)];
                    OperationsParams newParams = new OperationsParams(params);
                    OperationsParams.setShape(newParams, "point", query_point);
                    Job job = knn(inputFile, outputPath, params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.setUncaughtExceptionHandler(h);
        threads.add(thread);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();
    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");

    System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Total iterations: " + TotalIterations);
}

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

public static void main(String[] args) {
    VNFPackageManagement vnfPackageManagement = new VNFPackageManagement();

    try {/*  w w w  . j  ava2s  . c  om*/
        vnfPackageManagement.updateVims();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SDKException e) {
        e.printStackTrace();
    }
}