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:OldExtractor.java

/**
 * @param args the command line arguments
 *///  w w  w.jav  a 2  s  .  c  om
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            System.out.println(e);
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (IOException e) {
        System.out.println(e);
    }

    //The content string is the xml/json output from Bing.

}

From source file:cn.jumper.study.http.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    HttpHost proxy = new HttpHost("192.168.10.3", 8080, "http");

    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

    try {//from   w  w w . j  a  v  a 2 s  .  c om
        HttpGet httpget = new HttpGet("http://www.ksf-food.com/admin/Login.asp");
        httpget.setConfig(config);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        String code = "";
        try {
            HttpUriRequest httpgetCode = RequestBuilder.get()
                    .setUri("http://www.ksf-food.com/admin/inc/checkcode.asp").setConfig(config).build();

            /*
             * HttpGet httpgetCode = new HttpGet(
             * "http://www.qufuev.com/admin/inc/checkcode.asp");
             * httpgetCode.setConfig(config);
             */

            System.out.println("Executing request " + httpgetCode.getRequestLine());
            System.out.println("========================================================");
            System.out.println("==httpget header ==");
            for (Header header : httpgetCode.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            System.out.println("==httpget header ==");

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        System.out.println("==respons header ==");
                        for (Header header : response.getAllHeaders()) {
                            System.out.println(header.getName() + ":" + header.getValue());
                        }
                        System.out.println("==respons header ==");
                        String fileName = System.currentTimeMillis() + "";
                        DataOutputStream dataOutputStream = new DataOutputStream(
                                new FileOutputStream("d://test//e3//" + fileName + ".jpg"));
                        dataOutputStream.write(EntityUtils.toByteArray(entity));
                        dataOutputStream.close();
                        return ImageTest.getAllOcr("d://test//e3//" + fileName + ".jpg");
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            code = httpclient.execute(httpgetCode, responseHandler);
            System.out.println("ClientFormLogin.main()-CheckCode:" + code);
            System.out.println("----------------------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpUriRequest login = RequestBuilder.post()
                .setUri(new URI("http://www.ksf-food.com/admin/Admin_ChkLogin.asp"))
                .addParameter("UserName", "username").addParameter("Password", "password")
                .addParameter("CheckCode", code).setConfig(config).build();

        System.out.println("========================================================");
        System.out.println("==httpget header ==");
        for (Header header : login.getAllHeaders()) {
            System.out.println(header.getName() + ":" + header.getValue());
        }

        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form post: " + response2.getStatusLine());
            // EntityUtils.consume(entity);
            System.out.println("ClientFormLogin.main():\\n" + EntityUtils.toString(entity, "GBK"));

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:edu.vassar.cs.cmpu331.tvi.Main.java

public static void main(String[] args) {
    Options options = new Options().addOption("t", "trace", false, "Enable tracing.")
            .addOption("d", "debug", false, "Enable debug output.")
            .addOption("s", "size", true, "Sets amount of memory available.")
            .addOption("v", "version", false, "Prints the TVI version number.")
            .addOption("r", "renumber", true, "Renumbers the lines in a files.")
            .addOption("h", "help", false, "Prints this help message");
    CommandLineParser parser = new DefaultParser();
    try {/*  w  ww. j  a v  a2s  .c o  m*/
        CommandLine opts = parser.parse(options, args);
        if (opts.hasOption('h')) {
            help(options);
            return;
        }
        if (opts.hasOption('v')) {
            System.out.println();
            System.out.println("The Vassar Interpreter v" + Version.getVersion());
            System.out.println(COPYRIGHT);
            System.out.println();
            return;
        }
        if (opts.hasOption('r')) {
            int returnCode = 0;
            try {
                renumber(opts.getOptionValue('r'));
            } catch (IOException e) {
                e.printStackTrace();
                returnCode = 1;
            }
            System.exit(returnCode);
        }
        files = opts.getArgs();
        if (files.length == 0) {
            System.out.println("ERROR: No file names given.");
            help(options);
            System.exit(1);
        }
        if (opts.hasOption('s')) {
            try {
                memory = Integer.parseInt(opts.getOptionValue('s'));
            } catch (NumberFormatException e) {
                System.out.println("ERROR: Invalid --size parameter.");
                help(options);
                System.exit(1);
            }
        }
        if (opts.hasOption('t')) {
            tracing = true;
        }
        if (opts.hasOption('d')) {
            debugging = true;
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        help(options);
        System.exit(1);
    }
    Main app = new Main();
    Arrays.stream(files).forEach(app::run);
}

From source file:cn.lynx.emi.license.GenerateLicense.java

public static void main(String[] args) throws ClassNotFoundException, ParseException {
    if (args == null || args.length != 4) {
        System.err.println("Please provide [machine code] [cpu] [memory in gb] [yyyy-MM-dd] as parameter");
        return;/*from   w  w w.  j a  va2  s .  c o m*/
    }

    InputStream is = GenerateLicense.class.getResourceAsStream("/privatekey");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String key = null;
    try {
        key = br.readLine();
    } catch (IOException e) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        e.printStackTrace();
        return;
    }

    if (key == null) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        return;
    }

    String machineCode = args[0];
    int cpu = Integer.parseInt(args[1]);
    long mem = Long.parseLong(args[2]) * 1024 * 1024 * 1024;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    long expDate = sdf.parse(args[3]).getTime();

    LicenseBean lb = new LicenseBean();
    lb.setCpuCount(cpu);
    lb.setMemCount(mem);
    lb.setMachineCode(machineCode);
    lb.setExpireDate(expDate);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(lb);
        os.close();

        String serializedLicense = Base64.encodeBase64String(baos.toByteArray());
        System.out.println("License:" + encrypt(key, serializedLicense));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:CSVWriter.java

/**
 * Test driver//from w w w.j a v a  2s  . c om
 *
 * @param args  [0]: The name of the file.
 */
static public void main(String[] args) {
    try {
        // write out a test file
        PrintWriter pw = new PrintWriter(new FileWriter(args[0]));
        CSVWriter csv = new CSVWriter(pw, false, ',', System.getProperty("line.separator"));
        csv.writeCommentln("This is a test csv-file: '" + args[0] + "'");
        csv.write("abc");
        csv.write("def");
        csv.write("g h i");
        csv.write("jk,l");
        csv.write("m\"n\'o ");
        csv.writeln();
        csv.write("m\"n\'o ");
        csv.write("    ");
        csv.write("a");
        csv.write("x,y,z");
        csv.write("x;y;z");
        csv.writeln();
        csv.writeln(new String[] { "This", "is", "an", "array." });
        csv.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC);
    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC);
    options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC);
    options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC);
    options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter knnQueries = null;

    int maxNumQuery = Integer.MAX_VALUE;

    Float selProb = null;/*from w  w  w .ja v  a  2s.c o m*/

    try {
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null;

        if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) {
            queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM);
        } else {
            Usage("Specify 'query file'", options);
        }

        String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM);

        if (null == knnQueriesFile)
            Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options);

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options);
            }
        }

        String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM);
        if (null == tmps)
            Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options);
        String nmslibFieldList[] = tmps.split(",");

        knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile));
        knnQueries.write("isQueryFile=1");
        knnQueries.newLine();
        knnQueries.newLine();

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }

        String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM);

        if (tmpf != null) {
            try {
                selProb = Float.parseFloat(tmpf);
            } catch (NumberFormatException e) {
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
            }
            if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1)
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
        }

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(queryFile)));

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref);

        Random rnd = new Random();

        for (int docNum = 1; docNum <= maxNumQuery
                && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
            if (selProb != null) {
                if (rnd.nextFloat() > selProb)
                    continue;
            }

            Map<String, String> docFields = null;

            try {
                docFields = XmlHelper.parseXMLIndexEntry(docText);

                String queryObjStr = queryGen.getStrObjForKNNService(docFields);

                knnQueries.append(queryObjStr);
                knnQueries.newLine();
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum);
                throw new Exception("Parsing error.");
            }
        }

        knnQueries.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
        if (null != knnQueries)
            try {
                knnQueries.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        try {
            if (knnQueries != null)
                knnQueries.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }

    System.out.println("Terminated successfully!");
}

From source file:edu.harvard.i2b2.Icd9.BinResourceFromIcd9Data.java

public static void main(String[] args) {

    try {//from   w w w .j a  va2 s  . c  o m
        new BinResourceFromIcd9Data(//"/Users/kbw19/Downloads/");
                "/Users/kbw19/Downloads/cmsv31-master-descriptions/");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println(e.getMessage());

        e.printStackTrace();
    }
}

From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java

public static void main(String[] args) throws FileNotFoundException, JAXBException {
    String path = "tmp1";
    File dir = new File(path);
    String[] files = dir.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return (name.startsWith("device") && name.endsWith(".xml"));
        }// w ww  . j a v a 2s.  c  o m
    });
    TopologyDeviceLogger logger = new TopologyDeviceLogger(path);
    String host = "10.33.0.5";
    String snmpROComm = "public";
    Map<String, String> resourceParams = new HashMap<String, String>();
    resourceParams.put("community", snmpROComm);
    resourceParams.put("version", "1");
    Resource resource = new Resource(host, null, resourceParams);

    for (String fileName : files) {
        FileInputStream is = new FileInputStream(path + File.separator + fileName);
        DiscoveredDeviceData discoveredDeviceData = null;
        try {
            discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length());
        logger.handleDevice(deviceName, null, discoveredDeviceData, resource);
    }

}

From source file:com.mozilla.socorro.RawDumpSizeScan.java

public static void main(String[] args) throws ParseException {
    String startDateStr = args[0];
    String endDateStr = args[1];/*from  w ww  .  j  a v  a  2s.c om*/

    // Set both start/end time and start/stop row
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    if (!StringUtils.isBlank(startDateStr)) {
        startCal.setTime(sdf.parse(startDateStr));
    }
    if (!StringUtils.isBlank(endDateStr)) {
        endCal.setTime(sdf.parse(endDateStr));
    }

    DescriptiveStatistics stats = new DescriptiveStatistics();
    long numNullRawBytes = 0L;
    HTable table = null;
    Map<String, Integer> rowValueSizeMap = new HashMap<String, Integer>();
    try {
        table = new HTable(TABLE_NAME_CRASH_REPORTS);
        Scan[] scans = generateScans(startCal, endCal);
        for (Scan s : scans) {
            ResultScanner rs = table.getScanner(s);
            Iterator<Result> iter = rs.iterator();
            while (iter.hasNext()) {
                Result r = iter.next();
                ImmutableBytesWritable rawBytes = r.getBytes();
                //length = r.getValue(RAW_DATA_BYTES, DUMP_BYTES);
                if (rawBytes != null) {
                    int length = rawBytes.getLength();
                    if (length > 20971520) {
                        rowValueSizeMap.put(new String(r.getRow()), length);
                    }
                    stats.addValue(length);
                } else {
                    numNullRawBytes++;
                }

                if (stats.getN() % 10000 == 0) {
                    System.out.println("Processed " + stats.getN());
                    System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(),
                            stats.getMax(), stats.getMean()));
                    System.out.println(
                            String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f",
                                    stats.getPercentile(25.0d), stats.getPercentile(50.0d),
                                    stats.getPercentile(75.0d)));
                    System.out.println("Number of large entries: " + rowValueSizeMap.size());
                }
            }
            rs.close();
        }

        System.out.println("Finished Processing!");
        System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(), stats.getMax(),
                stats.getMean()));
        System.out.println(String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f",
                stats.getPercentile(25.0d), stats.getPercentile(50.0d), stats.getPercentile(75.0d)));

        for (Map.Entry<String, Integer> entry : rowValueSizeMap.entrySet()) {
            System.out.println(String.format("RowId: %s => Length: %d", entry.getKey(), entry.getValue()));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (table != null) {
            try {
                table.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:ByteFIFOTest.java

public static void main(String[] args) {
    try {//  w ww .  j a  v a2 s .co m
        new ByteFIFOTest();
    } catch (IOException iox) {
        iox.printStackTrace();
    }
}