Example usage for com.google.common.io Closer rethrow

List of usage examples for com.google.common.io Closer rethrow

Introduction

In this page you can find the example usage for com.google.common.io Closer rethrow.

Prototype

public RuntimeException rethrow(Throwable e) throws IOException 

Source Link

Document

Stores the given throwable and rethrows it.

Usage

From source file:gobblin.metastore.FsStateStore.java

/**
 * See {@link StateStore#put(String, String, T)}.
 *
 * <p>/*from   ww  w  .j  a va2s  .  com*/
 *   This implementation does not support putting the state object into an existing store as
 *   append is to be supported by the Hadoop SequenceFile (HADOOP-7139).
 * </p>
 */
@Override
public void put(String storeName, String tableName, T state) throws IOException {
    String tmpTableName = this.useTmpFileForPut ? TMP_FILE_PREFIX + tableName : tableName;
    Path tmpTablePath = new Path(new Path(this.storeRootDir, storeName), tmpTableName);

    if (!this.fs.exists(tmpTablePath) && !create(storeName, tmpTableName)) {
        throw new IOException("Failed to create a state file for table " + tmpTableName);
    }

    Closer closer = Closer.create();
    try {
        @SuppressWarnings("deprecation")
        SequenceFile.Writer writer = closer.register(SequenceFile.createWriter(this.fs, this.conf, tmpTablePath,
                Text.class, this.stateClass, SequenceFile.CompressionType.BLOCK, new DefaultCodec()));
        writer.append(new Text(Strings.nullToEmpty(state.getId())), state);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    if (this.useTmpFileForPut) {
        Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
        HadoopUtils.renamePath(this.fs, tmpTablePath, tablePath);
    }
}

From source file:se.sics.caracaldb.store.SizeScan.java

@Override
public StorageResponse execute(Persistence store) throws IOException {
    long size = 0;
    long keys = 0;

    Closer closer = Closer.create();
    try {// ww  w.  ja va 2s  .c  om
        byte[] begin = range.begin.getArray();
        for (StoreIterator it = closer.register(store.iterator(begin)); it.hasNext(); it.next()) {
            byte[] key = it.peekKey();
            if (range.contains(key)) {
                byte[] value = it.peekRaw();
                keys++;
                size += key.length;
                size += value.length;
            } else {
                //special case (a,b) and key is a
                if (Key.compare(begin, key) != 0) {
                    break; // reached end of range
                }
            }
        }

    } catch (Throwable e) {
        closer.rethrow(e);
    } finally {
        closer.close();
    }
    return new SizeResp(this, new Diff(size, keys, true));
}

From source file:com.android.builder.internal.packaging.DexIncrementalRenameManager.java

/**
 * Writes incremental state./*w w  w .  j  a v  a  2  s  .c  om*/
 *
 * @throws IOException failed to write state
 */
private void writeState() throws IOException {
    File stateFile = new File(mIncrementalDir, STATE_FILE);

    Properties props = new Properties();
    int currIdx = 0;
    for (BiMap.Entry<RelativeFile, String> entry : mNameMap.entrySet()) {
        props.put(BASE_KEY_PREFIX + currIdx, entry.getKey().getBase().getPath());
        props.put(FILE_KEY_PREFIX + currIdx, entry.getKey().getFile().getPath());
        props.put(RENAMED_KEY_PREFIX + currIdx, entry.getValue());
        currIdx++;
    }

    Closer closer = Closer.create();
    try {
        props.store(closer.register(new FileWriter(stateFile)), null);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.googlecode.jmxtrans.test.TCPEchoServer.java

private void processRequests(ServerSocket server) throws IOException {
    Closer closer = Closer.create();
    try {//w  ww .j ava2  s .  co  m
        Socket socket = server.accept();
        synchronized (startSynchro) {
            startSynchro.notifyAll();
        }
        BufferedReader in = closer
                .register(new BufferedReader(new InputStreamReader(socket.getInputStream(), UTF_8)));
        PrintWriter out = closer
                .register(new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8)));
        String line;
        while ((line = in.readLine()) != null) {
            receivedMessages.add(line);
            out.print(line);
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.android.builder.internal.packaging.DexIncrementalRenameManager.java

/**
 * Reads previously saved incremental state.
 *
 * @throws IOException failed to read state; not thrown if no state exists
 *///from  www. j av a 2  s .co m
private void readState() throws IOException {
    File stateFile = new File(mIncrementalDir, STATE_FILE);
    if (!stateFile.isFile()) {
        return;
    }

    Properties props = new Properties();
    Closer closer = Closer.create();
    try {
        props.load(closer.register(new FileReader(stateFile)));
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    for (int i = 0;; i++) {
        String baseKey = BASE_KEY_PREFIX + i;
        String fileKey = FILE_KEY_PREFIX + i;
        String renamedKey = RENAMED_KEY_PREFIX + i;

        String base = props.getProperty(baseKey);
        String file = props.getProperty(fileKey);
        String rename = props.getProperty(renamedKey);

        if (base == null || file == null || rename == null) {
            break;
        }

        RelativeFile rf = new RelativeFile(new File(base), new File(file));
        mNameMap.put(rf, rename);
    }
}

From source file:com.tinspx.util.net.RequestFileLogger.java

private void doWriteResponse(Response response, @Nullable Throwable cause) throws IOException {
    Closer closer = Closer.create();
    try {// ww  w  .  j  av a 2  s .c  om
        Writer out = closer.register(new OutputStreamWriter(
                new BufferedOutputStream(new FileOutputStream(infoFile(response))), charset));
        out.write("REQUEST\n");
        out.write(response.request().toDetailString());
        out.write("\n\nRESPONSE\n");
        out.write(response.toDetailString());
        if (cause != null) {
            out.write("\n\nERROR\n");
            out.write(Throwables.getStackTraceAsString(cause));
        }
        out.write("\n");
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:gobblin.metastore.FsStateStore.java

/**
 * See {@link StateStore#putAll(String, String, Collection)}.
 *
 * <p>/* w  ww  .j  a va  2 s .c  om*/
 *   This implementation does not support putting the state objects into an existing store as
 *   append is to be supported by the Hadoop SequenceFile (HADOOP-7139).
 * </p>
 */
@Override
public void putAll(String storeName, String tableName, Collection<T> states) throws IOException {
    String tmpTableName = this.useTmpFileForPut ? TMP_FILE_PREFIX + tableName : tableName;
    Path tmpTablePath = new Path(new Path(this.storeRootDir, storeName), tmpTableName);

    if (!this.fs.exists(tmpTablePath) && !create(storeName, tmpTableName)) {
        throw new IOException("Failed to create a state file for table " + tmpTableName);
    }

    Closer closer = Closer.create();
    try {
        @SuppressWarnings("deprecation")
        SequenceFile.Writer writer = closer.register(SequenceFile.createWriter(this.fs, this.conf, tmpTablePath,
                Text.class, this.stateClass, SequenceFile.CompressionType.BLOCK, new DefaultCodec()));
        for (T state : states) {
            writer.append(new Text(Strings.nullToEmpty(state.getId())), state);
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    if (this.useTmpFileForPut) {
        Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
        HadoopUtils.renamePath(this.fs, tmpTablePath, tablePath);
    }
}

From source file:org.sonatype.nexus.repository.maven.internal.MavenIndexPublisher.java

/**
 * Publishes MI index into {@code target}, sourced from {@code repositories} repositories.
 *///from  ww w  .j  av  a2  s  .co  m
public static void publishMergedIndex(final Repository target, final List<Repository> repositories)
        throws IOException {
    checkNotNull(target);
    checkNotNull(repositories);
    Closer closer = Closer.create();
    try {
        List<Iterable<Record>> records = new ArrayList<>();
        for (Repository repository : repositories) {
            try {
                ResourceHandler resourceHandler = closer
                        .register(new Maven2WritableResourceHandler(repository));
                IndexReader indexReader = closer.register(new IndexReader(null, resourceHandler));
                ChunkReader chunkReader = closer.register(indexReader.iterator().next());
                records.add(filter(transform(chunkReader, RECORD_EXPANDER::apply),
                        new RecordTypeFilter(Type.ARTIFACT_ADD)));
            } catch (IllegalArgumentException e) {
                throw new IOException(e.getMessage(), e);
            }
        }

        try (Maven2WritableResourceHandler resourceHandler = new Maven2WritableResourceHandler(target)) {
            try (IndexWriter indexWriter = new IndexWriter(resourceHandler, target.getName(), false)) {
                indexWriter.writeChunk(
                        transform(decorate(filter(concat(records), new UniqueFilter()), target.getName()),
                                RECORD_COMPACTOR::apply).iterator());
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.jeffplaisance.util.fingertree.rope.Rope.java

@Override
public boolean equals(Object o) {
    if (o == null) {
        return false;
    }//from   ww  w.j a  v a 2 s  .co  m
    if (!(o instanceof Rope)) {
        return false;
    }
    final Rope other = (Rope) o;
    if (length() != other.length()) {
        return false;
    }
    final int bufLen = Math.max(length(), 1024);
    final char[] buf1 = new char[bufLen];
    final char[] buf2 = new char[bufLen];

    try {
        final Closer closer = Closer.create();
        try {
            final Reader in1 = closer.register(newReader());
            final Reader in2 = closer.register(other.newReader());
            while (true) {
                final int read1 = read(in1, buf1, 0, bufLen);
                final int read2 = read(in2, buf2, 0, bufLen);
                if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
                    return false;
                } else if (read1 != bufLen) {
                    return true;
                }
            }
        } catch (Throwable e) {
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.glowroot.agent.central.CentralCollector.java

private static void writeConfigSyncedFile(File file, String agentId) throws IOException {
    Closer closer = Closer.create();
    try {//from w  w  w.  j  a va2 s.  c  o  m
        PrintWriter out = closer.register(new PrintWriter(file, UTF_8.name()));
        out.println("# this file is created after the agent has pushed its local configuration"
                + " to the central collector");
        out.println("#");
        out.println("# when this file is present (and the agent.id below matches the running"
                + " agent's agent.id), the agent");
        out.println("# will overwrite its local configuration with the agent configuration it"
                + " retrieves from the central");
        out.println("# collector on JVM startup");
        out.println("#");
        out.println("# when this file is not present (or the agent.id below does not match the"
                + " running agent's agent.id),");
        out.println("# the agent will push its local configuration to the central collector on"
                + " JVM startup (overwriting");
        out.println("# any existing remote configuration), after which the agent will"
                + " (re-)create this file using the");
        out.println("# running agent's agent.id");
        out.println("");
        out.println("agent.id=" + agentId);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}