Package com.google.common.io

Examples of com.google.common.io.Closer


  {
    if (file.getLength() > prefixFileMaxSize) {
      throw new InvalidInputException("Prefix file size exceeds maximum allowed size (" + prefixFileMaxSize
          + "), refusing to load it.");
    }
    Closer closer = Closer.create();
    try {
      final BufferedReader reader =
          closer.register(new BufferedReader(new InputStreamReader(file.getInputStream(), CHARSET)));
      final ArrayList<String> entries = new ArrayList<String>();
      String line = reader.readLine();
      if (!MAGIC.equals(line) && !LEGACY_MAGIC.equals(line) && !UNSUPPORTED.equals(line)) {
        throw new InvalidInputException("Prefix file does not start with expected \"" + MAGIC
            + "\" header, refusing to load the file.");
      }
      while (line != null) {
        // check for unsupported. Before 2.7.0 it needed to be on 1st line, now it is obeyed if found on any
        // line, as Nexus 2.7.0+ will have it AFTER headers, whereas older Nexuses had it BEFORE headers (on 1st
        // line)
        if (UNSUPPORTED.equals(line)) {
          return RESULT_UNSUPPORTED;
        }
        // trim
        line = line.trim();
        if (!line.startsWith("#") && line.length() > 0) {
          // line length
          if (line.length() > prefixFileMaxLineLength) {
            throw new InvalidInputException("Prefix file contains line longer than allowed ("
                + prefixFileMaxLineLength + " characters), refusing to load the file.");
          }
          // line should be ASCII
          if (!CharMatcher.ASCII.matchesAllOf(line)) {
            throw new InvalidInputException(
                "Prefix file contains non-ASCII characters, refusing to load the file.");
          }
          // line should be actually a bit less than ASCII, filtering most certain characters
          if (line.contains(":") || line.contains("<") || line.contains(">")) {
            throw new InvalidInputException(
                "Prefix file contains forbidden characters (colon, less or greater signs), refusing to load the file.");
          }

          // Igor's find command makes path like "./org/apache/"
          while (line.startsWith(".")) {
            line = line.substring(1);
          }
          // win file separators? Highly unlikely but still...
          line = line.replace('\\', '/');
          // normalization
          entries.add(pathFrom(elementsOf(line)));
        }
        line = reader.readLine();

        // dump big files
        if (entries.size() > prefixFileMaxEntryCount) {
          throw new InvalidInputException("Prefix file entry count exceeds maximum allowed count ("
              + prefixFileMaxEntryCount + "), refusing to load it.");
        }
      }

      return new Result()
      {
        @Override
        public boolean supported() {
          return true;
        }

        @Override
        public List<String> entries() {
          return entries;
        }
      };
    }
    finally {
      closer.close();
    }
  }
View Full Code Here


  private File copyAndTranslateToTempFile(Reader reader) throws IOException {
    File tempFile = File.createTempFile("myrrix-", ".csv.gz");
    tempFile.deleteOnExit();
    log.debug("Translating ingest input to {}", tempFile);
    Closer closer = Closer.create();
    try {
      BufferedReader buffered = closer.register(IOUtils.buffer(reader));     
      Writer out = closer.register(IOUtils.buildGZIPWriter(tempFile));
      CharSequence line;
      while ((line = buffered.readLine()) != null) {
        Iterator<String> it = COMMA_SPLIT.split(line).iterator();
        String userIDString = it.next();
        String itemIDString = it.next();
        long longUserID = translateUser(userIDString);
        long longItemID = translateItem(itemIDString);
        String translatedLine;
        if (it.hasNext()) {
          String valueString = it.next();
          translatedLine = COMMA_JOIN.join(longUserID, longItemID, valueString);
        } else {
          translatedLine = COMMA_JOIN.join(longUserID, longItemID);
        }
        out.write(translatedLine);
        out.write('\n');
      }
    } finally {
      closer.close();
    }
    log.debug("Done translating ingest input to {}", tempFile);   
    return tempFile;
  }
View Full Code Here

    public static Optional<Style> loadStyleAsURI(final ClientHttpRequestFactory clientHttpRequestFactory, final String styleRef,
                                                 final Function<byte[], Optional<Style>> loadFunction) throws IOException {
        HttpStatus statusCode;
        final byte[] input;

        Closer closer = Closer.create();
        try {
            URI uri;
            try {
                uri = new URI(styleRef);
            } catch (URISyntaxException e) {
                uri = new File(styleRef).toURI();
            }

            final ClientHttpRequest request = clientHttpRequestFactory.createRequest(uri, HttpMethod.GET);
            final ClientHttpResponse response = closer.register(request.execute());
            statusCode = response.getStatusCode();
            input = ByteStreams.toByteArray(response.getBody());
        } catch (Exception e) {
            return Optional.absent();
        } finally {
            closer.close();
        }
        if (statusCode == HttpStatus.OK) {
            return loadFunction.apply(input);
        } else {
            return Optional.absent();
View Full Code Here

                    }
                }
            }
            if (this.request instanceof HttpEntityEnclosingRequest) {
                HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.request;
                Closer closer = Closer.create();
                try {
                    HttpEntity requestEntity = new ByteArrayEntity(this.outputStream.toByteArray());
                    entityEnclosingRequest.setEntity(requestEntity);
                } finally {
                    closer.close();
                }
            }
            HttpResponse response = this.client.execute(this.request, this.context);
            return new Response(response);
        }
View Full Code Here

                        final File geotiffFile;
                        if (url.getProtocol().equalsIgnoreCase("file")) {
                            geotiffFile = new File(url.toURI());
                        } else {
                            geotiffFile = File.createTempFile("downloadedGeotiff", ".tiff");
                            Closer closer = Closer.create();

                            try {
                                final ClientHttpRequest request = requestFactory.createRequest(url.toURI(), HttpMethod.GET);
                                final ClientHttpResponse httpResponse = closer.register(request.execute());
                                FileOutputStream output = closer.register(new FileOutputStream(geotiffFile));
                                ByteStreams.copy(httpResponse.getBody(), output);
                            } finally {
                                closer.close();
                            }
                        }

                        return new GeoTiffFormat().getReader(geotiffFile);
                    } catch (Throwable t) {
View Full Code Here

        } catch (MalformedURLException e) {
            return null;
        }

        final String geojsonString;
        Closer closer = Closer.create();
        try {
            Reader input;
            if (url.getProtocol().equalsIgnoreCase("file")) {
                final CharSource charSource = Files.asCharSource(new File(url.getFile()), Constants.DEFAULT_CHARSET);
                input = closer.register(charSource.openBufferedStream());
            } else {
                final ClientHttpResponse response = closer.register(this.httpRequestFactory.createRequest(url.toURI(),
                        HttpMethod.GET).execute());

                input = closer.register(new BufferedReader(new InputStreamReader(response.getBody(), Constants.DEFAULT_CHARSET)));
            }
            geojsonString = CharStreams.toString(input);
        } catch (URISyntaxException e) {
            throw ExceptionUtils.getRuntimeException(e);
        } finally {
            closer.close();
        }

        return treatStringAsGeoJson(geojsonString);
    }
View Full Code Here

     *
     * @param configFile the file to read the configuration from.
     */
    @VisibleForTesting
    public final Configuration getConfig(final File configFile) throws IOException {
        Closer closer = Closer.create();
        try {
            FileInputStream in = closer.register(new FileInputStream(configFile));
           return getConfig(configFile, in);
        } finally {
            closer.close();
        }
    }
View Full Code Here

        final Rectangle paintArea = transformer.getPaintArea();
        ReferencedEnvelope envelope = transformer.getBounds().toReferencedEnvelope(paintArea, transformer.getDPI());
        URI uri = WmsUtilities.makeWmsGetLayerRequest(requestFactory, wmsLayerParam, commonUri, paintArea.getSize(), envelope);

        Closer closer = Closer.create();
        try {
            final ClientHttpResponse response = closer.register(requestFactory.createRequest(uri, HttpMethod.GET).execute());

            Assert.equals(HttpStatus.OK, response.getStatusCode(), "Http status code for " + uri + " was not OK.  It was: " + response
                    .getStatusCode() + ".  The response message was: '" + response.getStatusText() + "'");

            final BufferedImage image = ImageIO.read(response.getBody());
            if (image == null) {
                LOGGER.warn("The URI: " + uri + " is an image format that can be decoded");
                return createErrorImage(paintArea);
            }

            return image;
        } finally {
            closer.close();
        }
    }
View Full Code Here

     *
     * @param graphics2d The SVG graphic to save.
     * @param path       The file.
     */
    public static void saveSvgFile(final SVGGraphics2D graphics2d, final File path) throws IOException {
        Closer closer = Closer.create();
        try {
            final FileOutputStream fs = closer.register(new FileOutputStream(path));
            final OutputStreamWriter outputStreamWriter = closer.register(new OutputStreamWriter(fs, "UTF-8"));
            Writer osw = closer.register(new BufferedWriter(outputStreamWriter));

            graphics2d.stream(osw, true);
        } finally {
            closer.close();
        }
    }
View Full Code Here

        final URL[] icons = legendAttributes.icons;
        if (icons != null) {
            for (URL icon : icons) {
                Image image = null;
                Closer closer = Closer.create();
                try {
                    checkCancelState(context);
                    final ClientHttpRequest request = clientHttpRequestFactory.createRequest(icon.toURI(), HttpMethod.GET);
                    final ClientHttpResponse httpResponse = closer.register(request.execute());
                    if (httpResponse.getStatusCode() == HttpStatus.OK) {
                        image = ImageIO.read(httpResponse.getBody());
                        if (image == null) {
                            LOGGER.warn("The URL: " + icon + " is NOT an image format that can be decoded");
                        }
                    } else {
                        LOGGER.warn("Failed to load image from: " + icon + " due to server side error.\n\tResponse Code: " +
                                    httpResponse.getStatusCode() + "\n\tResponse Text: " + httpResponse.getStatusText());
                    }
                } catch (Exception e) {
                    LOGGER.warn("Failed to load image from: " + icon, e);
                } finally {
                    closer.close();
                }

                if (image == null) {
                    image = this.getMissingImage();
                }
View Full Code Here

TOP

Related Classes of com.google.common.io.Closer

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.