Package au.com.bytecode.opencsv

Examples of au.com.bytecode.opencsv.CSVReader


    private void createTrainingData() {
        String number;
        double[][] INPUT = new double[30][4];
        double[][] IDEAL = new double[30][6];
        try {
            CSVReader reader = new CSVReader(new FileReader("test.csv"), ';');
            List myEntries = reader.readAll();

            for (int i = 0; i < myEntries.size(); i++) {
                for (int j = 0; j < 4; j++) {
                    number = ((String[]) (myEntries.get(i)))[j].replace(",", ".");
                    INPUT[i][j] = Double.valueOf(number);
View Full Code Here


     * @throws FileNotFoundException
     * @throws IOException
     */
    protected void testRawCsvRead(String originalCommentText)
            throws FileNotFoundException, IOException {
        CSVReader reader = new CSVReader(new FileReader(filePath));
        String[] nextLine = null;
        int count = 0;
        while ((nextLine = reader.readNext()) != null) {
            if (!nextLine[0].equals("field1")) {
                System.out.println("RawCsvRead Assert Error: Name is wrong.");
            }
            if (!nextLine[1].equals("3.0")) {
                System.out.println("RawCsvRead Assert Error: Value is wrong.");
View Full Code Here

        mappingStrategy.setType(MyBean.class);
        String[] columns = new String[]{"name", "value", "amount1", "currency", "comments"}; // the fields to bind to in your JavaBean
        mappingStrategy.setColumnMapping(columns);

        CsvToBean csv = new CsvToBean();
        CSVReader reader = new CSVReader(new FileReader(filePath), CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, CSVParser.DEFAULT_ESCAPE_CHARACTER, 0, false, false);
        List<MyBean> list = csv.parse(mappingStrategy, reader);

        if (list.size() != 3) {
            System.out.println("Error - list size is wrong.");
        }
View Full Code Here

            "kyle,abc123456,123\n" +
            "jimmy,def098765,456 ";

    private CSVReader createReader() {
        StringReader reader = new StringReader(TEST_STRING);
        return new CSVReader(reader);
    }
View Full Code Here

     * @param csvContent
     * @return
     * @throws IOException
     */
    private List<String[]> readLines(String csvContent) throws IOException  {
        CSVReader reader = new CSVReader(new StringReader(csvContent));
       
        List<String[]> result = new ArrayList<String[]>();
        String [] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            result.add(nextLine);
        }
        return result;
    }
View Full Code Here

                logger.error("Couldn't find CSV file in form parameter name 'csvFile' aborting batch creation !");
                displayUsers( request, response, session);
                return;
            }
            String csvSeparator = jParams.getParameter("csvSeparator");
            CSVReader csvReader = new CSVReader(new InputStreamReader(fileItem.getInputStream()), csvSeparator.charAt(0));
            // the first line contains the column names;
            String[] headerElements = csvReader.readNext();
            List<String> headerElementList = Arrays.asList(headerElements);
            int userNamePos = headerElementList.indexOf("j:nodename");
            int passwordPos = headerElementList.indexOf("j:password");
            if ((userNamePos < 0) || (passwordPos < 0)) {
                logger.error("Couldn't find user name or password column in CSV file, aborting batch creation !");
                displayUsers( request, response, session);
                return;
            }
            String[] lineElements = null;
            int errorsCreatingUsers = 0;
            int usersCreatedSuccessfully = 0;
            JahiaPasswordPolicyService pwdPolicyService = ServicesRegistry.getInstance().getJahiaPasswordPolicyService();
            JahiaUserManagerService userService = ServicesRegistry.getInstance().getJahiaUserManagerService();
           
            while ((lineElements = csvReader.readNext()) != null) {
                List<String> lineElementList = Arrays.asList(lineElements);
                Properties properties = buildProperties(headerElementList, lineElementList);
                String userName = lineElementList.get(userNamePos);
                String password = lineElementList.get(passwordPos);
                if (userService.isUsernameSyntaxCorrect(userName)) {
View Full Code Here

        }

        int importedCount = 0;

        InputStream is = null;
        CSVReader reader = null;
        try {
            is = new BufferedInputStream(new FileInputStream(subscribersCSVFile));
            char separator = ',';
            reader = new CSVReader(new InputStreamReader(is, "UTF-8"), separator);
            String[] columns = reader.readNext();
            if (columns == null) {
                logger.warn("No data for importing subscriptions is found" + " or the file is not well-formed");
                return;
            }
            if (columns.length == 1 && columns[0].contains(";")) {
                // semicolon is used as a separator
                reader.close();
                IOUtils.closeQuietly(is);
                is = new BufferedInputStream(new FileInputStream(subscribersCSVFile));
                separator = ';';
                reader = new CSVReader(new InputStreamReader(is, "UTF-8"), separator);
                columns = reader.readNext();
            }
            int usernamePosition = ArrayUtils.indexOf(columns, "j:nodename");
            int emailPosition = ArrayUtils.indexOf(columns, J_EMAIL);
            if (usernamePosition == -1 && emailPosition == -1) {
                logger.warn("No data for importing subscriptions is found" + " or the file is not well-formed");
                return;
            }
            Map<String, Map<String, Object>> subscribers = new HashMap<String, Map<String, Object>>();
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                String username = usernamePosition != -1 ? nextLine[usernamePosition] : null;
                String email = emailPosition != -1 ? nextLine[emailPosition] : null;
                boolean registered = true;
                if (StringUtils.isNotEmpty(username)) {
                    // registered Jahia user is provided
                    JahiaUser user = username.charAt(0) == '{' ? userManagerService.lookupUserByKey(username) :
                            userManagerService.lookupUser(username);
                    if (user != null) {
                        if (username.charAt(0) != '{') {
                            username = "{" + user.getProviderName() + "}" + username;
                        }
                    } else {
                        logger.warn("No user can be found for the specified username '" + username +
                                "'. Skipping subscription: " + StringUtils.join(nextLine, separator));
                        continue;
                    }
                } else if (StringUtils.isNotEmpty(email)) {
                    username = email;
                    registered = false;
                } else {
                    logger.warn("Neither a j:nodename nor j:email is provided." + "Skipping subscription: " +
                            StringUtils.join(nextLine, separator));
                    continue;
                }
                Map<String, Object> props = new HashMap<String, Object>(columns.length);
                for (int i = 0; i < columns.length; i++) {
                    String column = columns[i];
                    if ("j:nodename".equals(column) || !registered && J_EMAIL.equals(column)) {
                        continue;
                    }
                    props.put(column, nextLine[i]);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Subscribing '" + username + "' with properties: " + props);
                }

                subscribers.put(username, props);
                if (subscribers.size() > 1000) {
                    // flush
                    subscribe(subscribableIdentifier, subscribers, session);
                    importedCount += subscribers.size();
                    subscribers = new HashMap<String, Map<String, Object>>();
                }
            }
            if (!subscribers.isEmpty()) {
                // subscribe the rest
                importedCount += subscribers.size();
                subscribe(subscribableIdentifier, subscribers, session);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    // ignore
                }
            }
            IOUtils.closeQuietly(is);
View Full Code Here

        this.reader = new BufferedReader(new InputStreamReader(config.getInStream()));
    }

    public void addUserList(UserStoreManager userStore) throws UserAdminException {
        try {
            CSVReader csvReader = new CSVReader(reader, ',', '"', 1);
            String password = config.getDefaultPassword();
            String[] line = csvReader.readNext();
            boolean isDuplicate = false;
            while (line != null && line.length > 0) {
                String userName = line[0];
                if (!userStore.isExistingUser(userName)) {
                    userStore.addUser(userName, password, null, null, null, true);
                } else {
                    isDuplicate = true;
                }
                line = csvReader.readNext();
            }
           
            if (isDuplicate == true) {
                throw new UserAdminException(
                        "Detected duplicate usernames. Failed to import duplicate users. Non-duplicate user names were successfually imported.");
View Full Code Here

  private CSVReader createCSVReader(int skipLineNo)
      throws IOException, DataServiceFault {
    InputStream ins = DBUtils.getInputStreamFromPath(
        this.getCsvDataSourcePath());
    InputStreamReader insr = new InputStreamReader(ins);
    return new CSVReader(insr, this.getColumnSeparator(),
        CSVConfig.DEFAULT_QUOTE_CHAR, skipLineNo);
  }
View Full Code Here

   
    private String[] getHeader() throws IOException, DataServiceFault {
      if (!this.isHasHeader()) {
        return null;
      }
      CSVReader reader = null;
      try {
        reader = this.createCSVReader(0);
        String[] header = reader.readNext();
        return header;
      } finally {
        if (reader != null) {
          try {
              reader.close();
          } catch (IOException e) {
          log.error("Error in closing CSV reader", e);
        }
        }
      }
View Full Code Here

TOP

Related Classes of au.com.bytecode.opencsv.CSVReader

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.