Example usage for java.io FileReader FileReader

List of usage examples for java.io FileReader FileReader

Introduction

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

Prototype

public FileReader(FileDescriptor fd) 

Source Link

Document

Creates a new FileReader , given the FileDescriptor to read, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {/*from w  w  w  . ja v a2 s .c  o  m*/
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    HttpPost httpPost = new HttpPost("http://httpbin.org/post");
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("username", "vip"));
    nvps.add(new BasicNameValuePair("password", "secret"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
            
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }
    } finally {
    httpclient.close();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java

/**
 * @param args the command line arguments
 *///from w  ww. j ava 2  s  . c  o  m
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire LCMSID geneartor (version: " + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_LCMSIDGen.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_lcmsidgen.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }
            case "DecoyPrefix": {
                if (!"".equals(value)) {
                    tandemPara.DecoyPrefix = value;
                }
                break;
            }
            case "PeptideFDR": {
                tandemPara.PepFDR = Float.parseFloat(value);
                break;
            }
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();

    File folder = new File(WorkFolder);
    if (!folder.exists()) {
        Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
        System.exit(1);
    }
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isFile()
                && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                        | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
            AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
        }
        if (fileEntry.isDirectory()) {
            for (final File fileEntry2 : fileEntry.listFiles()) {
                if (fileEntry2.isFile()
                        && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                        && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                    AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                }
            }
        }
    }

    Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
    for (File fileEntry : AssignFiles.values()) {
        Logger.getRootLogger().info(fileEntry.getAbsolutePath());
    }

    //process each DIA file to genearate untargeted identifications
    for (File fileEntry : AssignFiles.values()) {
        String mzXMLFile = fileEntry.getAbsolutePath();
        if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
            long time = System.currentTimeMillis();

            DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
            FileList.add(DiaFile);
            Logger.getRootLogger().info(
                    "=================================================================================================");
            Logger.getRootLogger().info("Processing " + mzXMLFile);
            if (!DiaFile.LoadDIASetting()) {
                Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                System.exit(1);
            }
            if (!DiaFile.LoadParams()) {
                Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                System.exit(1);
            }
            Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

            DiaFile.ParsePepXML(tandemPara, null);
            DiaFile.BuildStructure();
            if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                System.exit(1);
            }
            DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
            //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
            DiaFile.GenerateClusterScanNomapping();
            //Doing quantification
            DiaFile.AssignQuant();
            DiaFile.ClearStructure();

            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(mzXMLFile + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }
        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");
    }
}

From source file:metaTile.Main.java

/**
 * @param args/*w  ww .j ava 2 s.  co  m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

        // parse the command line arguments
        CommandLine commandLine = parser.parse(options, args);

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.linkedin.pinotdruidbenchmark.DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(/*from   ww  w  .j a va2s  .  c o m*/
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            int length;
            while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                stringBuilder.append(new String(CHAR_BUFFER, 0, length));
            }
        }
        String query = stringBuilder.toString();
        httpPost.setEntity(new StringEntity(query));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:com.jff.searchapicluster.server.mina.Server.java

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

    org.apache.commons.configuration.Configuration config = new PropertiesConfiguration("settings.txt");

    int serverPort = config.getInt("listenPort");

    NioSocketAcceptor acceptor = new NioSocketAcceptor();

    acceptor.getFilterChain().addLast("com/jff/searchapicluster/core/mina/codec",
            new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

    acceptor.getFilterChain().addLast("logger", new LoggingFilter());

    acceptor.setHandler(new ServerSessionHandler());
    acceptor.bind(new InetSocketAddress(serverPort));

    System.out.println("Listening on port " + serverPort);
    System.out.println("Please enter filename");

    //  open up standard input
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (true) {
        String filepath = br.readLine();

        filepath = "/Users/admin/repos/study_repos/kurs_sp/search_api_cluster/SearchApiClusterServer/task.json";
        File file = new File(filepath);
        Logger.d(LOG_TAG, file.getAbsolutePath());

        if (file.exists() && file.isFile()) {

            Gson gson = new Gson();

            SearchTask taskMessage = gson.fromJson(new FileReader(file), SearchTask.class);

            ServerManager serverManager = ServerManager.getInstance();

            Logger.d(LOG_TAG, taskMessage.toString());
            serverManager.startProcessTask(taskMessage);
        } else {/*from  w  w  w  .  j  a  v  a2 s . co  m*/
            Logger.d(LOG_TAG, filepath + "not found");
        }
    }
}

From source file:com.chargebee.CSV.PhoneBook.PhoneBook2.PhoneBook.java

public static void main(String[] args) throws IOException, Exception {
    String source = System.getProperty("user.home") + "/input2.csv";

    PhoneBook pb = new PhoneBook();

    CSVParser parser = new CSVParser(new FileReader(source), CSVFormat.EXCEL.withHeader());

    pb.directory(parser);//from   w  w w .  j a v  a 2s .c o  m
    parser.close();

}

From source file:examples.mail.java

public final static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    Vector ccList = new Vector();
    BufferedReader stdin;/*  www  .j a  v a2 s.c o  m*/
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;
    Enumeration en;

    if (args.length < 1) {
        System.err.println("Usage: mail smtpserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            cc = stdin.readLine().trim();

            if (cc.length() == 0)
                break;

            header.addCC(cc);
            ccList.addElement(cc);
        }

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        en = ccList.elements();

        while (en.hasMoreElements())
            client.addRecipient((String) en.nextElement());

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        fileReader.close();

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.opensoc.json.serialization.JSONKafkaSerializer.java

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

    //String Input = "/home/kiran/git/opensoc-streaming/OpenSOC-Common/BroExampleOutput";
    String Input = "/tmp/test";

    BufferedReader reader = new BufferedReader(new FileReader(Input));

    // String jsonString =
    // "{\"dns\":{\"ts\":[14.0,12,\"kiran\"],\"uid\":\"abullis@mail.csuchico.edu\",\"id.orig_h\":\"10.122.196.204\", \"endval\":null}}";
    String jsonString = "";// reader.readLine();
    JSONParser parser = new JSONParser();
    JSONObject json = null;/*from w w  w .  jav  a2 s . co  m*/
    int count = 1;

    if (args.length > 0)
        count = Integer.parseInt(args[0]);

    //while ((jsonString = reader.readLine()) != null) 
    jsonString = reader.readLine();
    {
        try {
            json = (JSONObject) parser.parse(jsonString);
            System.out.println(json);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String jsonString2 = null;

        JSONKafkaSerializer ser = new JSONKafkaSerializer();

        for (int i = 0; i < count; i++) {
            byte[] bytes = ser.toBytes(json);

            jsonString2 = ((JSONObject) ser.fromBytes(bytes)).toJSONString();
        }
        System.out.println((jsonString2));
        System.out.println(jsonString2.equalsIgnoreCase(json.toJSONString()));
    }

}

From source file:TaskManager.java

public static void main(String[] args) {
    String configFileName = "tasks.conf";

    if (args.length == 1) {
        configFileName = args[0];//from   w  w  w  .  ja v a  2s  . co  m
    }

    File configFile = new File(configFileName);

    if (!configFile.exists() || !configFile.canRead()) {
        System.err.println("Can't read config file '" + configFileName + "'");
        System.exit(1);
    }

    FileReader configReader = null;

    try {
        configReader = new FileReader(configFile);
    } catch (FileNotFoundException fnfX) {
    }

    Tasks taskList = new Tasks(configReader);

    try {
        configReader.close();
    } catch (IOException ioX) {
    }

    TaskManager ex = new TaskManager(taskList);
}

From source file:me.timothy.ddd.DrunkDuckDispatch.java

License:asdf

public static void main(String[] args) throws LWJGLException {
    try {/*from  w w w . ja v  a 2 s. c o m*/
        float defaultDisplayWidth = SizeScaleSystem.EXPECTED_WIDTH / 2;
        float defaultDisplayHeight = SizeScaleSystem.EXPECTED_HEIGHT / 2;
        boolean fullscreen = false, defaultDisplay = !fullscreen;
        File resolutionInfo = new File("graphics.json");

        if (resolutionInfo.exists()) {
            try (FileReader fr = new FileReader(resolutionInfo)) {
                JSONObject obj = (JSONObject) new JSONParser().parse(fr);
                Set<?> keys = obj.keySet();
                for (Object o : keys) {
                    if (o instanceof String) {
                        String key = (String) o;
                        switch (key.toLowerCase()) {
                        case "width":
                            defaultDisplayWidth = JSONCompatible.getFloat(obj, key);
                            break;
                        case "height":
                            defaultDisplayHeight = JSONCompatible.getFloat(obj, key);
                            break;
                        case "fullscreen":
                            fullscreen = JSONCompatible.getBoolean(obj, key);
                            defaultDisplay = !fullscreen;
                            break;
                        }
                    }
                }
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            float expHeight = defaultDisplayWidth
                    * (SizeScaleSystem.EXPECTED_HEIGHT / SizeScaleSystem.EXPECTED_WIDTH);
            float expWidth = defaultDisplayHeight
                    * (SizeScaleSystem.EXPECTED_WIDTH / SizeScaleSystem.EXPECTED_HEIGHT);
            if (Math.round(defaultDisplayWidth) != Math.round(expWidth)) {
                if (defaultDisplayHeight < expHeight) {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, defaultDisplayWidth, expHeight);
                    defaultDisplayHeight = expHeight;
                } else {
                    System.err.printf("%f x %f is an invalid resolution; adjusting to %f x %f\n",
                            defaultDisplayWidth, defaultDisplayHeight, expWidth, defaultDisplayHeight);
                    defaultDisplayWidth = expWidth;
                }
            }
        }
        File dir = null;
        String os = getOS();
        if (os.equals("windows")) {
            dir = new File(System.getenv("APPDATA"), "timgames/");
        } else {
            dir = new File(System.getProperty("user.home"), ".timgames/");
        }
        File lwjglDir = new File(dir, "lwjgl-2.9.1/");
        Resources.init();
        Resources.downloadIfNotExists(lwjglDir, "lwjgl-2.9.1.zip", "http://umad-barnyard.com/lwjgl-2.9.1.zip",
                "Necessary LWJGL natives couldn't be found, I can attempt "
                        + "to download it, but I make no promises",
                "Unfortunately I was unable to download it, so I'll open up the "
                        + "link to the official download. Make sure you get LWJGL version 2.9.1, "
                        + "and you put it at " + dir.getAbsolutePath() + "/lwjgl-2.9.1.zip",
                new Runnable() {

                    @Override
                    public void run() {
                        if (!Desktop.isDesktopSupported()) {
                            JOptionPane.showMessageDialog(null,
                                    "I couldn't " + "even do that! Download it manually and try again");
                            return;
                        }

                        try {
                            Desktop.getDesktop().browse(new URI("http://www.lwjgl.org/download.php"));
                        } catch (IOException | URISyntaxException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Oh cmon.. Address is http://www.lwjgl.org/download.php, good luck");
                            System.exit(1);
                        }
                    }

                }, 5843626);

        Resources.extractIfNotFound(lwjglDir, "lwjgl-2.9.1.zip", "lwjgl-2.9.1");
        System.setProperty("org.lwjgl.librarypath",
                new File(dir, "lwjgl-2.9.1/lwjgl-2.9.1/native/" + os).getAbsolutePath()); // deal w/ it
        System.setProperty("net.java.games.input.librarypath", System.getProperty("org.lwjgl.librarypath"));

        Resources.downloadIfNotExists("entities.json", "http://umad-barnyard.com/ddd/entities.json", 16142);
        Resources.downloadIfNotExists("map.binary", "http://umad-barnyard.com/ddd/map.binary", 16142);
        Resources.downloadIfNotExists("victory.txt", "http://umad-barnyard.com/ddd/victory.txt", 168);
        Resources.downloadIfNotExists("failure.txt", "http://umad-barnyard.com/ddd/failure.txt", 321);
        File resFolder = new File("resources/");
        if (!resFolder.exists() && !new File("player-still.png").exists()) {
            Resources.downloadIfNotExists("resources.zip", "http://umad-barnyard.com/ddd/resources.zip", 54484);
            Resources.extractIfNotFound(new File("."), "resources.zip", "player-still.png");
            new File("resources.zip").delete();
        }
        File soundFolder = new File("sounds/");
        if (!soundFolder.exists()) {
            soundFolder.mkdirs();
            Resources.downloadIfNotExists("sounds/sounds.zip", "http://umad-barnyard.com/ddd/sounds.zip",
                    1984977);
            Resources.extractIfNotFound(soundFolder, "sounds.zip", "asdfasdffadasdf");
            new File(soundFolder, "sounds.zip").delete();
        }
        AppGameContainer appgc;
        ddd = new DrunkDuckDispatch();
        appgc = new AppGameContainer(ddd);
        appgc.setTargetFrameRate(60);
        appgc.setShowFPS(false);
        appgc.setAlwaysRender(true);
        if (fullscreen) {
            DisplayMode[] modes = Display.getAvailableDisplayModes();
            DisplayMode current, best = null;
            float ratio = 0f;
            for (int i = 0; i < modes.length; i++) {
                current = modes[i];
                float rX = (float) current.getWidth() / SizeScaleSystem.EXPECTED_WIDTH;
                float rY = (float) current.getHeight() / SizeScaleSystem.EXPECTED_HEIGHT;
                System.out.println(current.getWidth() + "x" + current.getHeight() + " -> " + rX + "x" + rY);
                if (rX == rY && rX > ratio) {
                    best = current;
                    ratio = rX;
                }
            }
            if (best == null) {
                System.out.println("Failed to find an appropriately scaled resolution, using default display");
                defaultDisplay = true;
            } else {
                appgc.setDisplayMode(best.getWidth(), best.getHeight(), true);
                SizeScaleSystem.setRealHeight(best.getHeight());
                SizeScaleSystem.setRealWidth(best.getWidth());
                System.out.println("I choose " + best.getWidth() + "x" + best.getHeight());
            }
        }

        if (defaultDisplay) {
            SizeScaleSystem.setRealWidth(Math.round(defaultDisplayWidth));
            SizeScaleSystem.setRealHeight(Math.round(defaultDisplayHeight));
            appgc.setDisplayMode(Math.round(defaultDisplayWidth), Math.round(defaultDisplayHeight), false);
        }
        ddd.logger.info(
                "SizeScaleSystem: " + SizeScaleSystem.getRealWidth() + "x" + SizeScaleSystem.getRealHeight());
        appgc.start();
    } catch (SlickException ex) {
        LogManager.getLogger(DrunkDuckDispatch.class.getSimpleName()).catching(Level.ERROR, ex);
    }
}