Example usage for java.io BufferedReader lines

List of usage examples for java.io BufferedReader lines

Introduction

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

Prototype

public Stream<String> lines() 

Source Link

Document

Returns a Stream , the elements of which are lines read from this BufferedReader .

Usage

From source file:au.org.ncallister.goodbudget.tools.coms.GoodBudgetSession.java

public String get(String path, List<NameValuePair> parameters) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(BASE_URI);
    builder.setPath(path);/*from  www.  j  a  va  2 s  . c  o  m*/
    builder.setParameters(parameters);
    HttpGet get = new HttpGet(builder.build());

    CloseableHttpResponse response = client.execute(get, sessionContext);
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        return reader.lines().collect(Collectors.joining("\n"));
    } finally {
        response.close();
    }
}

From source file:acmi.l2.clientmod.l2resources.Environment.java

public Environment(File ini) throws IOException {
    try (InputStream fis = new FileInputStream(ini)) {
        InputStream is = fis;/*from  w  w w .j av a 2 s  .  c  o m*/
        try {
            is = L2Crypt.decrypt(is, ini.getName());
        } catch (CryptoException e) {
            System.err.println(e.getMessage());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        paths = br.lines().filter(s -> PATHS_PATTERN.matcher(s).matches())
                .map(s -> s.substring(s.indexOf('=') + 1)).collect(Collectors.toList());
        if (paths.isEmpty())
            throw new IllegalStateException("Couldn't find any Path in file");
        startDir = ini.getParentFile();
    }
}

From source file:com.javafxpert.wikibrowser.WikiPageController.java

/**
 *
 *//* w w w  .  j ava  2 s.c  om*/
@RequestMapping("/wikipage")
String generateWikiBrowserPage(
        @RequestParam(value = "name", defaultValue = "Ada_Lovelace") String wikipediaPageName,
        @RequestParam(value = "lang") String lang) throws Exception {

    String language = wikiBrowserProperties.computeLang(lang);

    String mWikipediaBase = String.format(WikiClaimsController.WIKIPEDIA_MOBILE_BASE_TEMPLATE, language);
    String mWikipedia = String.format(WikiClaimsController.WIKIPEDIA_MOBILE_TEMPLATE, language);
    String mWikipediaPage = mWikipedia + wikipediaPageName;

    URL url = new URL(mWikipediaPage);
    InputStream inputStream = url.openStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

    String pageText = reader.lines().collect(Collectors.joining("\n"));
    pageText = pageText.replaceAll("\\\"/w/", "\"" + mWikipediaBase + "w/");
    pageText = pageText.replaceAll("\\\"/images/", "\"" + mWikipediaBase + "images/");
    pageText = pageText.replaceAll("\\\"/static/", "\"" + mWikipediaBase + "static/");

    pageText = pageText.replaceAll("\\\"href\\\":\\\"/w/", "\"href\":\"" + mWikipediaBase + "w/");
    pageText = pageText.replaceAll("\\\"href\\\":\\\"/wiki/", "\"href\":\"" + mWikipedia);

    pageText = pageText.replaceAll("href=\\\"/wiki/", "href=\"" + "/wikipage?lang=" + language + "&name=");

    pageText = pageText.replaceAll("href=\\\"//", "target=\"_blank\" href=\"//");

    pageText = pageText.replaceAll("href=\\\"http", "target=\"_blank\" href=\"http");

    // Remove the search menu at the top of the page
    int searchAnchorStartPos = pageText.indexOf("<a title");
    if (searchAnchorStartPos > 0) {
        int searchAnchorEndPos = pageText.indexOf("</a>", searchAnchorStartPos);
        if (searchAnchorEndPos > 0) {
            pageText = pageText.substring(0, searchAnchorStartPos)
                    + pageText.substring(searchAnchorEndPos + "</a>".length());
        }
    }

    // Remove the search form at the top of the page
    int searchFormStartPos = pageText.indexOf("<form");
    if (searchFormStartPos > 0) {
        int searchFormEndPos = pageText.indexOf("</form>", searchFormStartPos);
        if (searchFormEndPos > 0) {
            pageText = pageText.substring(0, searchFormStartPos)
                    + pageText.substring(searchFormEndPos + "</form>".length());
        }
    }

    return pageText;
}

From source file:de.tudarmstadt.lt.lm.app.LineProbPerp.java

void runParallel(Reader r) {
    BufferedReader br = new BufferedReader(r);
    br.lines().parallel().forEach(
            line -> processLine(line, new ModelPerplexity<>(_lm_prvdr), new ModelPerplexity<>(_lm_prvdr)));
}

From source file:org.apache.pulsar.broker.authentication.AuthenticationProviderBasic.java

@Override
public void initialize(ServiceConfiguration config) throws IOException {
    File confFile = new File(System.getProperty(CONF_SYSTEM_PROPERTY_KEY));
    if (!confFile.exists()) {
        throw new IOException("The password auth conf file does not exist");
    } else if (!confFile.isFile()) {
        throw new IOException("The path is not a file");
    }/*from ww w .j a va2  s.  c  o  m*/

    @Cleanup
    BufferedReader reader = new BufferedReader(new FileReader(confFile));
    users = new HashMap<>();
    for (String line : reader.lines().toArray(s -> new String[s])) {
        List<String> splitLine = Arrays.asList(line.split(":"));
        if (splitLine.size() != 2) {
            throw new IOException("The format of the password auth conf file is invalid");
        }
        users.put(splitLine.get(0), splitLine.get(1));
    }
}

From source file:org.codice.ddf.configuration.persistence.felix.FelixPersistenceStrategy.java

@Override
@SuppressWarnings("unchecked")
public Dictionary<String, Object> read(InputStream inputStream) throws ConfigurationFileException, IOException {
    notNull(inputStream, "InputStream cannot be null");

    final StringBuilder filteredOutput = new StringBuilder();

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    PropertyConverter propertyConverter = createPropertyConverter(filteredOutput);

    reader.lines().forEach(propertyConverter);

    LOGGER.debug("Calling ConfigurationHandler with {}", filteredOutput.toString());

    Dictionary properties;/*  w  w  w.j ava2  s .co  m*/

    try {
        properties = ConfigurationHandler
                .read(new ByteArrayInputStream(filteredOutput.toString().getBytes(StandardCharsets.UTF_8)));
    } catch (RuntimeException e) {
        LOGGER.error("ConfigurationHandler failed to read configuration from file", e);
        throw new ConfigurationFileException("Failed to read configuration from file", e);
    }

    checkForInvalidProperties(propertyConverter.getPropertyNames(), properties);

    return properties;
}

From source file:ac.simons.tweetarchive.web.ArchiveHandlingController.java

/**
 * As you can see, it get's nasty here...
 * <br>//from   w  ww  .  j av a 2  s.c om
 * Twitter4j doesn't offer an official way to parse Twitters JSON, so I
 * brute force my way into the twitter4j.StatusJSONImpl implementation of
 * Status.
 * <br>
 * And even if there was an official way, the JSON files inside the
 * official(!) Twitter archive differ from the API, even if they are said to
 * be identical. By the way, I'm not the only one, who
 * <a href="https://twittercommunity.com/t/why-does-twitter-json-archive-have-a-different-format-than-the-rest-api-1-1/35530">noticed
 * that</a>.
 * <br>
 * Furthermore, I didn't even bother to add error handling or tests.
 *
 * @param archive The uploaded archive
 * @return Redirect to the index
 * @throws java.io.IOException
 * @throws twitter4j.JSONException
 */
@PostMapping
public String store(@NotNull final MultipartFile archive, final RedirectAttributes redirectAttributes)
        throws IOException, JSONException {
    try (final ZipInputStream archiv = new ZipInputStream(archive.getInputStream())) {
        ZipEntry entry;
        while ((entry = archiv.getNextEntry()) != null) {
            if (!entry.getName().startsWith("data/js/tweets/") || entry.isDirectory()) {
                continue;
            }
            log.debug("Reading archive entry {}...", entry.getName());
            final BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(archiv, StandardCharsets.UTF_8));

            final String content = buffer.lines().skip(1).map(l -> {
                Matcher m = PATTERN_CREATED_AT.matcher(l);
                String rv = l;
                if (m.find()) {
                    try {
                        rv = m.replaceFirst(
                                "$1\"" + DATE_FORMAT_OUT.format(DATE_FORMAT_IN.parse(m.group(2))) + "\"");
                    } catch (ParseException ex) {
                        log.warn("Unexpected date format in twitter archive", ex);
                    }
                }
                return rv;
            }).collect(Collectors.joining("")).replaceAll("\"sizes\" : \\[.+?\\],", "\"sizes\" : {},");

            final JSONArray statuses = new JSONArray(content);
            for (int i = 0; i < statuses.length(); ++i) {
                final JSONObject rawJSON = statuses.getJSONObject(i);
                // https://twitter.com/lukaseder/status/772772372990586882 ;)
                final Status status = statusFactory.create(rawJSON).as(Status.class);
                this.tweetStorageService.store(status, rawJSON.toString());
            }
        }
    }
    redirectAttributes.addFlashAttribute("message", "Done.");
    return "redirect:/upload";
}

From source file:org.apache.metron.rest.service.impl.StormCLIWrapper.java

protected String stormClientVersionInstalled() throws RestException {
    String stormClientVersionInstalled = "Storm client is not installed";
    ProcessBuilder pb = getProcessBuilder("storm", "version");
    pb.redirectErrorStream(true);//  ww  w  .  ja  v a  2 s.  co  m
    Process p;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new RestException(e);
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    List<String> lines = reader.lines().collect(toList());
    lines.forEach(System.out::println);
    if (lines.size() > 1) {
        stormClientVersionInstalled = lines.get(1).replaceFirst("Storm ", "");
    }
    return stormClientVersionInstalled;
}

From source file:io.github.microcks.web.ResourceController.java

@RequestMapping(value = "/resources/{serviceId}/{resourceType}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getServiceResource(@PathVariable("serviceId") String serviceId,
        @PathVariable("resourceType") String resourceType, HttpServletResponse response) {
    log.info("Requesting {} resource for service {}", resourceType, serviceId);

    Service service = serviceRepository.findOne(serviceId);
    if (service != null && ServiceType.GENERIC_REST.equals(service.getType())) {
        // Prepare HttpHeaders.
        InputStream stream = null;
        String resource = findResource(service);
        HttpHeaders headers = new HttpHeaders();

        // Get the correct template depending on resource type.
        if (SWAGGER_20.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/swagger-2.0.json");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading swagger-2.0.json template", e);
            }/*from   w  w w.  j  av a  2 s.  com*/
            headers.setContentType(MediaType.APPLICATION_JSON);
        } else if (OPENAPI_30.equals(resourceType)) {
            org.springframework.core.io.Resource template = new ClassPathResource("templates/openapi-3.0.yaml");
            try {
                stream = template.getInputStream();
            } catch (IOException e) {
                log.error("IOException while reading openapi-3.0.yaml template", e);
            }
            headers.set("Content-Type", "text/yaml");
        }

        // Now process the stream, replacing patterns by value.
        if (stream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringWriter writer = new StringWriter();

            try (Stream<String> lines = reader.lines()) {
                lines.map(line -> replaceInLine(line, service, resource))
                        .forEach(line -> writer.write(line + "\n"));
            }
            return new ResponseEntity<>(writer.toString().getBytes(), headers, HttpStatus.OK);
        }
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

From source file:org.apache.hadoop.hive.metastore.dbinstall.DbInstallBase.java

private ProcessResults runCmd(String[] cmd, long secondsToWait) throws IOException, InterruptedException {
    LOG.info("Going to run: " + StringUtils.join(cmd, " "));
    Process proc = Runtime.getRuntime().exec(cmd);
    if (!proc.waitFor(secondsToWait, TimeUnit.SECONDS)) {
        throw new RuntimeException("Process " + cmd[0] + " failed to run in " + secondsToWait + " seconds");
    }// w  ww. ja  v a2 s. c o m
    BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    final StringBuilder lines = new StringBuilder();
    reader.lines().forEach(s -> lines.append(s).append('\n'));

    reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    final StringBuilder errLines = new StringBuilder();
    reader.lines().forEach(s -> errLines.append(s).append('\n'));
    return new ProcessResults(lines.toString(), errLines.toString(), proc.exitValue());
}