Example usage for java.nio.file Files newBufferedReader

List of usage examples for java.nio.file Files newBufferedReader

Introduction

In this page you can find the example usage for java.nio.file Files newBufferedReader.

Prototype

public static BufferedReader newBufferedReader(Path path) throws IOException 

Source Link

Document

Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.

Usage

From source file:Main.java

public static void main(String[] args) {
    String scriptFileName = "c:/test.js";
    Path scriptPath = Paths.get(scriptFileName);
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    try {// w  w w  .j  a  v  a 2 s.co m
        Reader scriptReader = Files.newBufferedReader(scriptPath);
        engine.eval(scriptReader);
    } catch (IOException | ScriptException e) {
        e.printStackTrace();
    }
}

From source file:com.me.jvmi.Main.java

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

    final Path localProductImagesPath = Paths.get("/Volumes/jvmpubfs/WEB/images/products/");
    final Path uploadCSVFile = Paths.get("/Users/jbabic/Documents/products/upload.csv");
    final Config config = new Config(Paths.get("../config.properties"));

    LuminateOnlineClient luminateClient2 = new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/",
            3);/*  w w w.ja  va 2  s . c o  m*/
    luminateClient2.login(config.luminateUser(), config.luminatePassword());

    Set<String> completed = new HashSet<>(
            IOUtils.readLines(Files.newBufferedReader(Paths.get("completed.txt"))));

    try (InputStream is = Files.newInputStream(Paths.get("donforms.csv"));
            PrintWriter pw = new PrintWriter(new FileOutputStream(new File("completed.txt"), true))) {

        for (String line : IOUtils.readLines(is)) {
            if (completed.contains(line)) {
                System.out.println("completed: " + line);
                continue;
            }
            try {
                luminateClient2.editDonationForm(line, "-1");
                pw.println(line);
                System.out.println("done: " + line);
                pw.flush();
            } catch (Exception e) {
                System.out.println("skipping: " + line);
                e.printStackTrace();
            }
        }
    }

    //        luminateClient2.editDonationForm("8840", "-1");
    //        Collection<String> ids = luminateClient2.donFormSearch("", true);
    //        
    //        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    //        try (FileWriter fileWriter = new FileWriter(new File("donforms.csv"));
    //                CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) {
    //
    //            for (String id : ids) {
    //                csvFilePrinter.printRecord(id);
    //            }
    //        }
    //        

    if (true) {
        return;
    }

    Collection<InputRecord> records = parseInput(uploadCSVFile);

    LuminateFTPClient ftp = new LuminateFTPClient("customerftp.convio.net");
    ftp.login(config.ftpUser(), config.ftpPassword());

    ProductImages images = new ProductImages(localProductImagesPath, ftp);

    validateImages(records, images);

    Map<String, DPCSClient> dpcsClients = new HashMap<>();
    dpcsClients.put("us", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvm"));
    dpcsClients.put("ca", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvcn"));
    dpcsClients.put("uk", new DPCSClient("https://donor.dpconsulting.com/NewDDI/Logon.asp?client=jvuk"));

    for (DPCSClient client : dpcsClients.values()) {
        client.login(config.dpcsUser(), config.dpcsPassword());
    }

    Map<String, LuminateOnlineClient> luminateClients = new HashMap<>();
    luminateClients.put("us", new LuminateOnlineClient("https://secure2.convio.net/jvmi/admin/", 10));
    luminateClients.put("ca", new LuminateOnlineClient("https://secure3.convio.net/jvmica/admin/", 10));
    luminateClients.put("uk", new LuminateOnlineClient("https://secure3.convio.net/jvmiuk/admin/", 10));

    Map<String, EcommerceProductFactory> ecommFactories = new HashMap<>();
    ecommFactories.put("us", new EcommerceProductFactory(dpcsClients.get("us"), images, Categories.us));
    ecommFactories.put("ca", new EcommerceProductFactory(dpcsClients.get("ca"), images, Categories.ca));
    ecommFactories.put("uk", new EcommerceProductFactory(dpcsClients.get("uk"), images, Categories.uk));

    List<String> countries = Arrays.asList("us", "ca", "uk");

    boolean error = false;
    for (InputRecord record : records) {
        for (String country : countries) {
            if (record.ignore(country)) {
                System.out.println("IGNORE: " + country + " " + record);
                continue;
            }
            try {
                EcommerceProductFactory ecommFactory = ecommFactories.get(country);
                LuminateOnlineClient luminateClient = luminateClients.get(country);
                luminateClient.login(config.luminateUser(), config.luminatePassword());

                ECommerceProduct product = ecommFactory.createECommerceProduct(record);
                luminateClient.createOrUpdateProduct(product);
            } catch (Exception e) {
                System.out.println("ERROR: " + country + " " + record);
                //System.out.println(e.getMessage());
                error = true;
                e.printStackTrace();
            }
        }
    }

    if (!error) {
        for (String country : countries) {
            LuminateOnlineClient luminateClient = luminateClients.get(country);
            DPCSClient dpcsClient = dpcsClients.get(country);
            luminateClient.close();
            dpcsClient.close();
        }
    }
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

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

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*ww w.  jav  a 2 s  . c  o m*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:io.github.robolib.util.mapper.RobotMap.java

public static void setMapFile(String file) {
    m_mapFile = file;// w w w.j  a va 2s  . c  o m
    m_enabled = true;
    File f = new File(m_mapFile);
    try {
        m_jMap = new JSONObject(new JSONTokener(Files.newBufferedReader(f.toPath())));
    } catch (JSONException | IOException e) {
        Logger.get(RobotMap.class).fatal("Failed to load config file", e);
    }
}

From source file:ch.uzh.phys.ecn.oboma.map.api.MapFactory.java

public static INodeMap buildDefaultSBBMap() throws Exception {
    NodeMap map = new NodeMap();
    Random rand = new Random();
    int stationCount = 0;
    int trainCount = 0;

    JSONParser parser = new JSONParser();

    try {/*from ww w .  j  a  v a2s.c o  m*/
        JSONArray stations = (JSONArray) parser.parse(Files.newBufferedReader(Paths.get("data/stations.json")));
        for (Object o : stations) {
            JSONObject station = (JSONObject) o;

            String id = (String) station.get("id");
            String name = (String) station.get("name");
            JSONObject coord = (JSONObject) ((JSONObject) station.get("location")).get("wgs");
            Double lat = (Double) coord.get("y");
            Double lng = (Double) coord.get("x");

            Node node = new Node(id, name, lat, lng, 0, 0);
            map.add(node);
            stationCount++;

            LOGGER.info(String.format("Station Node %s (%s) added", id, name));
        }

        JSONArray connections = (JSONArray) parser
                .parse(Files.newBufferedReader(Paths.get("data/connections.json")));
        for (Object o : connections) {
            JSONObject connection = (JSONObject) o;

            String from = (String) connection.get("from");
            String to = (String) connection.get("to");
            int time = (int) ((long) connection.get("time"));

            String id1 = String.format("%s-%s", from, to);
            String name1 = String.format("Train %s - %s", from, to);
            String id2 = String.format("%s-%s", to, from);
            String name2 = String.format("Train %s - %s", to, from);
            int seats = rand.nextInt(1000) + 1;

            Node node1 = new TrainNode(id1, name1, 0, 0, time, seats);
            Node node2 = new TrainNode(id2, name2, 0, 0, time, seats);
            try {
                map.add(node1, from, to);
                map.add(node2, to, from);
                trainCount++;
                LOGGER.info(String.format("Train Node %s (%s -> %s) added (%d seats)", id1, from, to, seats));
            } catch (Exception pEx) {
                // either from or to do not exist
            }
        }

        LOGGER.info(String.format("%d stations added / %d trains added", stationCount, trainCount));
    } catch (Exception pEx) {
        throw new Exception("Could not build map", pEx);
    }

    return map;
}

From source file:ninja.siden.internal.RendererSelectorTest.java

@Parameters(name = "{0}")
public static Iterable<Object[]> parameters() throws Exception {
    int port = 8000;
    return Arrays.asList(new Object[][] { { "String", "Hello", port++ }, { "File", tmp().toFile(), port++ },
            { "Path", tmp(), port++ }, { "FileChannel", FileChannel.open(tmp()), port++ },
            { "byteArray", "Hello".getBytes(), port++ },
            { "ByteBuffer", ByteBuffer.wrap("Hello".getBytes()), port++ }, { "URI", tmp().toUri(), port++ },
            { "URL", tmp().toUri().toURL(), port++ }, { "Reader", Files.newBufferedReader(tmp()), port++ },
            { "InputStream", new ByteArrayInputStream("Hello".getBytes()), port++ },
            { "CharSequence", new StringBuilder("Hello"), port++ },

    });/*ww w. ja  v a 2s  .  c  o m*/
}

From source file:org.dbflute.intro.app.logic.dfprop.DfpropUpdateLogic.java

public void replaceSchemaSyncCheckMap(String project, SchemaSyncCheckMap schemaSyncCheckMap) {
    final File documentMapFile = dfpropPhysicalLogic.findDfpropFile(project, "documentMap.dfprop");
    try (BufferedReader br = Files.newBufferedReader(documentMapFile.toPath())) {
        boolean inSetting = false;
        boolean inSyncSchemeSetting = false;
        final StringBuilder sb = new StringBuilder();

        while (true) {
            String line = br.readLine();
            if (line == null) {
                break;
            }/*w w w  .  j  a  v a  2 s  . co m*/
            if (StringUtils.equals(line, "map:{")) {
                inSetting = true;
            }
            if (inSetting) {
                if (line.contains("; schemaSyncCheckMap = map:{")) {
                    inSyncSchemeSetting = true;
                }
                if (inSyncSchemeSetting) {
                    if (line.contains("# - - - - - - - - - -/")) {
                        inSyncSchemeSetting = false;
                        line = schemaSyncCheckMap.convertToDfpropStr() + "\n" + line;
                    } else {
                        continue;
                    }
                }
            }
            sb.append(line).append("\n");
        }
        flutyFileLogic.writeFile(documentMapFile, sb.toString());
    } catch (IOException e) {
        throw new LaSystemException("Cannot replace schema sync check map", e);
    }
}

From source file:de.sanandrew.mods.turretmod.registry.electrolytegen.ElectrolyteRegistry.java

private static boolean processJson(Path root, Path file) {
    if (!"json".equals(FilenameUtils.getExtension(file.toString()))
            || root.relativize(file).toString().startsWith("_")) {
        return true;
    }/*from   w ww  .j  a  v a 2  s  .com*/

    try (BufferedReader reader = Files.newBufferedReader(file)) {
        JsonObject json = JsonUtils.fromJson(reader, JsonObject.class);

        if (json == null || json.isJsonNull()) {
            throw new JsonSyntaxException("Json cannot be null");
        }

        NonNullList<ItemStack> inputItems = JsonUtils.getItemStacks(json.get("electrolytes"));
        float effectiveness = JsonUtils.getFloatVal(json.get("effectiveness"));
        int ticksProcessing = JsonUtils.getIntVal(json.get("timeProcessing"));
        ItemStack trash = ItemStackUtils.getEmpty();
        ItemStack treasure = ItemStackUtils.getEmpty();

        JsonElement elem = json.get("trash");
        if (elem != null && !elem.isJsonNull()) {
            trash = JsonUtils.getItemStack(elem);
        }
        elem = json.get("treasure");
        if (elem != null && !elem.isJsonNull()) {
            treasure = JsonUtils.getItemStack(elem);
        }

        registerFuels(inputItems, effectiveness, ticksProcessing, trash, treasure);
    } catch (JsonParseException e) {
        TmrConstants.LOG.log(Level.ERROR,
                String.format("Parsing error loading electrolyte generator recipe from %s", file), e);
        return false;
    } catch (IOException e) {
        TmrConstants.LOG.log(Level.ERROR, String.format("Couldn't read recipe from %s", file), e);
        return false;
    }

    return true;
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public BufferedReader createReader() throws IOException {
    return Files.newBufferedReader(p);
}

From source file:org.thingsboard.server.service.install.DatabaseHelper.java

public static void upgradeTo40_assignDashboards(Path dashboardsDump, DashboardService dashboardService,
        boolean sql) throws Exception {
    JavaType assignedCustomersType = objectMapper.getTypeFactory().constructCollectionType(HashSet.class,
            ShortCustomerInfo.class);
    try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(dashboardsDump),
            CSV_DUMP_FORMAT.withFirstRecordAsHeader())) {
        csvParser.forEach(record -> {
            String customerIdString = record.get(CUSTOMER_ID);
            String assignedCustomersString = record.get(ASSIGNED_CUSTOMERS);
            DashboardId dashboardId = new DashboardId(toUUID(record.get(ID), sql));
            List<CustomerId> customerIds = new ArrayList<>();
            if (!StringUtils.isEmpty(assignedCustomersString)) {
                try {
                    Set<ShortCustomerInfo> assignedCustomers = objectMapper.readValue(assignedCustomersString,
                            assignedCustomersType);
                    assignedCustomers.forEach((customerInfo) -> {
                        CustomerId customerId = customerInfo.getCustomerId();
                        if (!customerId.isNullUid()) {
                            customerIds.add(customerId);
                        }/*from   w  ww  .ja  va  2 s  . c om*/
                    });
                } catch (IOException e) {
                    log.error("Unable to parse assigned customers field", e);
                }
            }
            if (!StringUtils.isEmpty(customerIdString)) {
                CustomerId customerId = new CustomerId(toUUID(customerIdString, sql));
                if (!customerId.isNullUid()) {
                    customerIds.add(customerId);
                }
            }
            for (CustomerId customerId : customerIds) {
                dashboardService.assignDashboardToCustomer(new TenantId(EntityId.NULL_UUID), dashboardId,
                        customerId);
            }
        });
    }
}