Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:de.hybris.platform.integration.cis.payment.strategies.impl.CisPaymentIntegrationTestHelper.java

public static Map<String, String> createNewProfile(final String cybersourceUrl,
        final List<BasicNameValuePair> formData) throws Exception // NO PMD
{
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost postRequest = new HttpPost(cybersourceUrl);
    postRequest.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
    postRequest.setEntity(new UrlEncodedFormEntity(formData, "UTF-8"));
    // Execute HTTP Post Request
    final HttpResponse response = client.execute(postRequest);
    final Map<String, String> responseParams = new HashMap<String, String>();
    BufferedReader bufferedReader = null;
    try {/*from  w w w . ja  v  a 2s.  c o m*/
        bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

        while (bufferedReader.ready()) {
            final String currentLine = bufferedReader.readLine();
            if (currentLine.contains("value=\"") && currentLine.contains("name=\"")) {
                final String[] splittedLine = currentLine.split("name=\"");
                final String key = splittedLine[1].split("value=\"")[0].replace("\"", "").replace(">", "")
                        .trim();
                final String value = splittedLine[1].split("value=\"")[1].replace("\"", "").replace(">", "")
                        .trim();
                responseParams.put(key, value);
            }
        }
    } finally {
        IOUtils.closeQuietly(bufferedReader);
    }

    return responseParams;
}

From source file:org.forumj.dbextreme.db.tool.DbTool.java

public static void execute(String path) throws IOException, ConfigurationException, SQLException {
    ClassLoader classLoader = DbTool.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream(path);
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    StringBuffer result = new StringBuffer();
    Connection connection = null;
    Statement st = null;//from  w  w  w.j av a  2s  . com
    try {
        connection = FJDao.getConnection();
        while (br.ready()) {
            String line = br.readLine().trim();
            if (line.startsWith("--")) {
                continue;
            }
            if (line.endsWith(";")) {
                result.append(line);
                st = connection.createStatement();
                String query = result.toString();
                st.executeUpdate(query);
                result = new StringBuffer();
                continue;
            }
            result.append(line + "\n");
        }
    } finally {
        if (br != null) {
            br.close();
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:org.n52.ses.startupinit.StartupInitServlet.java

public static String getGetCapabilitiesRequest(String sesurl) throws IOException {
    InputStream capsstream = StartupInitServlet.class
            .getResourceAsStream("/sesconfig/wakeup_capabilities_start.xml");

    BufferedReader br = new BufferedReader(new InputStreamReader(capsstream));
    StringBuilder sb = new StringBuilder();
    while (br.ready()) {
        sb.append(br.readLine());/*from   w w  w .ja  v a 2  s  .  c  o m*/
    }
    br.close();

    sb.append(sesurl);

    capsstream = StartupInitServlet.class.getResourceAsStream("/sesconfig/wakeup_capabilities_end.xml");
    br = new BufferedReader(new InputStreamReader(capsstream));
    while (br.ready()) {
        sb.append(br.readLine());
    }
    br.close();

    return sb.toString();
}

From source file:org.kalypso.commons.runtime.LogAnalyzer.java

/**
 * Reads a reader into an array of statuses.
 * <p>//from  w  w w  . j  ava 2s  .c  o  m
 * The reader will not be closed.
 *
 * @throws IOException
 */
public static IStatus[] readerToStatus(final BufferedReader br) throws IOException {
    final List<IStatus> stati = new ArrayList<>();

    while (br.ready()) {
        final String line = br.readLine();
        if (line == null)
            break;

        final IStatus lineStatus = LoggerUtilities.lineToStatus(line);
        if (lineStatus != null)
            stati.add(lineStatus);
    }

    return stati.toArray(new IStatus[stati.size()]);
}

From source file:Zip.java

/**
 * Reads a GZIP file and dumps the contents to the console.
 *///from   w w  w .  ja v  a 2 s. c o  m
public static void readGZIPFile(String fileName) {
    // use BufferedReader to get one line at a time
    BufferedReader gzipReader = null;
    try {
        // simple loop to dump the contents to the console
        gzipReader = new BufferedReader(
                new InputStreamReader(new GZIPInputStream(new FileInputStream(fileName))));
        while (gzipReader.ready()) {
            System.out.println(gzipReader.readLine());
        }
        gzipReader.close();
    } catch (FileNotFoundException fnfe) {
        System.out.println("The file was not found: " + fnfe.getMessage());
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (gzipReader != null) {
            try {
                gzipReader.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:org.brunocvcunha.taskerbox.core.utils.TaskerboxFileUtils.java

/**
 * Imports lines to set/*from  ww w  .ja v  a2s .  c o  m*/
 *
 * @param channel
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static void deserializeMemory(TaskerboxChannel<?> channel) throws IOException, ClassNotFoundException {
    if (getPerformedFileForChannel(channel).exists()) {
        log.debug("Deserializing history for channel " + channel.getId());

        FileReader fr = new FileReader(getPerformedFileForChannel(channel));
        BufferedReader br = new BufferedReader(fr);

        synchronized (channel.getAlreadyPerformed()) {
            Set<String> alreadyPerformed = channel.getAlreadyPerformed();
            while (br.ready()) {
                alreadyPerformed.add(br.readLine());
            }
            br.close();
        }
    }

    if (getPersistentStorageFileForChannel(channel).exists()) {
        log.debug("Deserializing persistent storage for channel " + channel.getId());

        ObjectInputStream in = new ObjectInputStream(
                new FileInputStream(getPersistentStorageFileForChannel(channel)));
        channel.setStoredPropertyBag((Map<String, String>) in.readObject());
        in.close();
    }

}

From source file:edu.umd.cloud9.example.clustering.IterateGMM.java

public static boolean reNameFile(String input, String output, int iterations, Configuration conf,
        int reduceTasks) {
    String dstName = input + "/cluster" + iterations;
    try {/*w w w. jav a  2 s  . co  m*/
        FileSystem fs = FileSystem.get(conf);
        fs.delete(new Path(dstName), true);
        FSDataOutputStream clusterfile = fs.create(new Path(dstName));

        for (int i = 0; i < reduceTasks; i++) {
            String srcName = output + "/part-r-" + String.format("%05d", i);
            FSDataInputStream cluster = fs.open(new Path(srcName));
            BufferedReader reader = new BufferedReader(new InputStreamReader(cluster));
            while (reader.ready()) {
                String line = reader.readLine() + "\n";
                if (line.length() > 5)
                    clusterfile.write(line.getBytes());
            }
            reader.close();
            cluster.close();
        }
        clusterfile.flush();
        clusterfile.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:Emporium.Controle.ContrDestinatarioImporta.java

public static String importaPedido(FileItem item, int idCliente, int idDepartamento, String nomeBD) {

    try {/*from w  ww  .  ja  v a2 s.  c  om*/
        //CONTADOR DE LINHA
        int qtdLinha = 1;
        ArrayList<ArquivoImportacao> listaAi = new ArrayList<ArquivoImportacao>();
        BufferedReader le = new BufferedReader(new InputStreamReader(item.getInputStream(), "ISO-8859-1"));
        // LE UMA LINHA DO ARQUIVO PARA PULAR O CABEALHO
        le.readLine();
        while (le.ready()) {
            //LE UMA LINHA DO ARQUIVO E DIVIDE A LINHA POR PONTO E VIRGULA
            String[] aux = le.readLine().replace(";", " ; ").split(";");
            //System.out.println("aaa "+aux[0]);
            //ADICIONA CONTADOR DE LINHA
            qtdLinha++;
            //VERIFICA QUANTIDADE MAXIMA DE LINHAS PERMITIDAS
            if (aux != null && aux.length >= 10) {

                ArquivoImportacao ai = new ArquivoImportacao();
                ai.setIdCliente(idCliente);
                ai.setIdDepartamento(idDepartamento);
                ai.setNrLinha(qtdLinha + "");
                ai.setNome(aux[0].trim());
                ai.setEmpresa(aux[1].trim());
                ai.setCpf(aux[2].trim());
                ai.setCep(aux[3].trim());
                ai.setEndereco(aux[4].trim());
                ai.setNumero(aux[5].trim());
                ai.setComplemento(aux[6].trim());
                ai.setBairro(aux[7].trim());
                ai.setCidade(aux[8].trim());
                ai.setUf(aux[9].trim());
                ai.setCelular("");
                if (aux.length >= 12 && aux[11] != null) {
                    ai.setCelular(aux[10].trim() + aux[11].trim());
                }
                ai.setEmail("");
                if (aux.length >= 13 && aux[12] != null) {
                    ai.setEmail(aux[12].trim());
                }
                ai.setObs("");//campo usado para tags (Entidade reaproveitada)
                if (aux.length >= 14 && aux[13] != null) {
                    ai.setObs(aux[13].trim());
                }

                listaAi.add(ai);

            }
        }
        le.close();

        if (listaAi.size() > 0) {
            //valida os dados do arquivo para efetuar a importacao
            listaAi = validaCepArquivo(listaAi);
            if (!falha.equals("")) {
                //retorna mensagem de falha
                return falha;
            } else {
                //MONTA SQL
                insereDestinatarios(listaAi, nomeBD);
                return "Destinatarios Importados Com Sucesso!";
            }
        } else {
            return "Nenhum pedido no arquivo para importar!";
        }

    } catch (IOException e) {
        return "No foi possivel ler o arquivo: " + e;
    } catch (Exception e) {
        return "Falha na importacao dos pedidos: " + e;
    }

}

From source file:org.mfcrawler.model.export.config.LoadCrawlProjectConfig.java

/**
 * Load the filters (keyword list and blacklist domains)
 * @param filtersFile the file loaded//from  w w  w . j ava  2  s. c  om
 * @param keywordMap the map of the keywords modified
 * @param blacklistDomains the set of blacklisted domains modified
 */
public static void loadFilters(File filtersFile, Map<String, Integer> keywordMap,
        Set<Domain> blacklistDomains) {
    if (filtersFile.exists()) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(filtersFile));
            while (bufferedReader.ready()) {
                String line = bufferedReader.readLine().trim();
                int colonIndex = line.indexOf(':');

                if (colonIndex != -1) {
                    // Keyword List
                    String word = line.substring(colonIndex + 1).toLowerCase();
                    Integer weight = ConversionUtils.toInteger(line.substring(0, colonIndex));
                    keywordMap.put(word, weight);
                } else if (!line.isEmpty()) {
                    // Blacklist domains
                    Domain domain = new Domain(line);
                    blacklistDomains.add(domain);
                }
            }
            bufferedReader.close();
        } catch (Exception e) {
            Logger.getLogger(LoadCrawlProjectConfig.class.getName()).log(Level.SEVERE, "Error to read filters",
                    e);
        }
    } else {
        saveFilters(filtersFile, keywordMap, blacklistDomains);
    }
}

From source file:org.fiware.apps.repository.it.collectionService.CollectionServiceITTest.java

@BeforeClass
public static void setUpClass() throws IOException {
    //Delete test collection.
    IntegrationTestHelper client = new IntegrationTestHelper();
    List<Header> headers = new LinkedList<>();
    client.deleteCollection("collectionTest1", headers);

    String auxString = "";
    FileReader file = new FileReader("src/test/resources/rdf+xml.rdf");
    BufferedReader buffer = new BufferedReader(file);
    while (buffer.ready()) {
        auxString = auxString.concat(buffer.readLine());
    }/*from   ww w.j a  va 2s.c  o  m*/
    buffer.close();
    rdfxmlExample = auxString;

    auxString = "";
    file = new FileReader("src/test/resources/rdf+json.rdf");
    buffer = new BufferedReader(file);
    while (buffer.ready()) {
        auxString = auxString.concat(buffer.readLine());
    }
    buffer.close();
    rdfjsonExample = auxString;

}