Example usage for com.google.common.base Splitter fixedLength

List of usage examples for com.google.common.base Splitter fixedLength

Introduction

In this page you can find the example usage for com.google.common.base Splitter fixedLength.

Prototype

@CheckReturnValue
public static Splitter fixedLength(final int length) 

Source Link

Document

Returns a splitter that divides strings into pieces of the given length.

Usage

From source file:org.springframework.yarn.support.console.UiUtils.java

/**
 * Renders a textual representation of the provided {@link Table}
 *
 * @param table Table data {@link Table}
 * @param withHeader with header/*from   w w w.j a  va2s  .  c  o  m*/
 * @return The rendered table representation as String
 */
public static String renderTextTable(Table table, boolean withHeader) {

    table.calculateColumnWidths();

    final String padding = "  ";
    final String headerBorder = getHeaderBorder(table.getHeaders());
    final StringBuilder textTable = new StringBuilder();

    if (withHeader) {
        final StringBuilder headerline = new StringBuilder();
        for (TableHeader header : table.getHeaders().values()) {

            if (header.getName().length() > header.getWidth()) {
                Iterable<String> chunks = Splitter.fixedLength(header.getWidth()).split(header.getName());
                int length = headerline.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + CommonUtils.padRight(chunk, header.getWidth());
                    } else {
                        lineToAppend = StringUtils.leftPad("", length) + padding
                                + CommonUtils.padRight(chunk, header.getWidth());
                    }
                    first = false;
                    headerline.append(lineToAppend);
                    headerline.append("\n");
                }
                headerline.deleteCharAt(headerline.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + CommonUtils.padRight(header.getName(), header.getWidth());
                headerline.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(headerline.toString()));
        textTable.append("\n");
    }

    textTable.append(headerBorder);

    for (TableRow row : table.getRows()) {
        StringBuilder rowLine = new StringBuilder();
        for (Entry<Integer, TableHeader> entry : table.getHeaders().entrySet()) {
            String value = row.getValue(entry.getKey());
            if (value.length() > entry.getValue().getWidth()) {
                Iterable<String> chunks = Splitter.fixedLength(entry.getValue().getWidth()).split(value);
                int length = rowLine.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + CommonUtils.padRight(chunk, entry.getValue().getWidth());
                    } else {
                        lineToAppend = StringUtils.leftPad("", length) + padding
                                + CommonUtils.padRight(chunk, entry.getValue().getWidth());
                    }
                    first = false;
                    rowLine.append(lineToAppend);
                    rowLine.append("\n");
                }
                rowLine.deleteCharAt(rowLine.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + CommonUtils.padRight(value, entry.getValue().getWidth());
                rowLine.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(rowLine.toString()));
        textTable.append("\n");
    }

    if (!withHeader) {
        textTable.append(headerBorder);
    }

    return textTable.toString();
}

From source file:org.springframework.xd.shell.util.UiUtils.java

/**
 * Renders a textual representation of the provided {@link Table}
 * /*w ww . java  2  s .c o  m*/
 * @param table Table data {@link Table}
 * @return The rendered table representation as String
 */
public static String renderTextTable(Table table, boolean withHeader) {

    table.calculateColumnWidths();

    final String padding = "  ";
    final String headerBorder = getHeaderBorder(table.getHeaders());
    final StringBuilder textTable = new StringBuilder();

    if (withHeader) {
        final StringBuilder headerline = new StringBuilder();
        for (TableHeader header : table.getHeaders().values()) {

            if (header.getName().length() > header.getWidth()) {
                Iterable<String> chunks = Splitter.fixedLength(header.getWidth()).split(header.getName());
                int length = headerline.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + CommonUtils.padRight(chunk, header.getWidth());
                    } else {
                        lineToAppend = StringUtils.leftPad("", length) + padding
                                + CommonUtils.padRight(chunk, header.getWidth());
                    }
                    first = false;
                    headerline.append(lineToAppend);
                    headerline.append("\n");
                }
                headerline.deleteCharAt(headerline.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + CommonUtils.padRight(header.getName(), header.getWidth());
                headerline.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(headerline.toString()));
        textTable.append("\n");
    }

    textTable.append(headerBorder);

    for (TableRow row : table.getRows()) {
        StringBuilder rowLine = new StringBuilder();
        for (Entry<Integer, TableHeader> entry : table.getHeaders().entrySet()) {
            String value = row.getValue(entry.getKey());
            if (null != value && (value.length() > entry.getValue().getWidth())) {
                Iterable<String> chunks = Splitter.fixedLength(entry.getValue().getWidth()).split(value);
                int length = rowLine.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + CommonUtils.padRight(chunk, entry.getValue().getWidth());
                    } else {
                        lineToAppend = StringUtils.leftPad("", length) + padding
                                + CommonUtils.padRight(chunk, entry.getValue().getWidth());
                    }
                    first = false;
                    rowLine.append(lineToAppend);
                    rowLine.append("\n");
                }
                rowLine.deleteCharAt(rowLine.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + CommonUtils.padRight(value, entry.getValue().getWidth());
                rowLine.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(rowLine.toString()));
        textTable.append("\n");
    }

    if (!withHeader) {
        textTable.append(headerBorder);
    }

    return textTable.toString();
}

From source file:ca.ualberta.physics.cssdp.file.service.CacheService.java

public ServiceResponse<String> put(final String filename, final String externalKey,
        final InputStream fileData) {

    final ServiceResponse<String> sr = new ServiceResponse<String>();

    File tempDir = Files.createTempDir();
    final File tempFile = new File(tempDir, UUID.randomUUID().toString());
    FileOutputStream fos = null;/*from ww  w. j a va 2 s  .co  m*/
    try {
        Files.touch(tempFile);
        fos = new FileOutputStream(tempFile);
        logger.debug("Shuffling bytes from input stream into " + tempFile.getAbsolutePath());
        ByteStreams.copy(fileData, fos);
    } catch (IOException e) {
        sr.error("Could not copy file data into temp file because " + e.getMessage());

    } finally {
        if (fos != null) {
            try {
                fos.flush();
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }

    final String md5 = getMD5(tempFile);
    new ManualTransaction(sr, emp.get()) {

        @Override
        public void onError(Exception e, ServiceResponse<?> sr) {
            Throwable t = Throwables.getRootCause(e);
            sr.error(t.getMessage());
        }

        @Override
        public void doInTransaction() {

            CachedFile existing = cachedFileDao.get(md5);
            if (existing != null) {
                if (existing.getExternalKeys().contains(externalKey)) {
                    sr.info("File with signature " + md5 + " already in cache with key " + externalKey);
                } else {
                    existing.getExternalKeys().add(externalKey);
                    cachedFileDao.update(existing);
                }
            } else {

                StringBuffer path = new StringBuffer();
                for (String subdir : Splitter.fixedLength(4).split(md5)) {
                    path.append("/" + subdir);
                }
                path.append("/");

                File cachePath = new File(cacheRoot, path.toString());
                cachePath.mkdirs();
                File cacheFile = new File(cachePath, "" + (cachePath.list().length + 1));

                try {
                    Files.touch(cacheFile);
                    Files.copy(tempFile, cacheFile);
                    logger.debug("Shuffling bytes from " + tempFile.getAbsolutePath() + " into "
                            + cacheFile.getAbsolutePath());
                } catch (IOException e) {
                    sr.error("Could not copy temp file into cache because " + e.getMessage());

                }

                // sanity check
                if (cacheFile.length() == 0) {
                    cacheFile.delete();
                    sr.error("Zero byte file, not caching.");
                }

                CachedFile cachedFile = new CachedFile(filename, md5, cacheFile);
                cachedFile.getExternalKeys().add(externalKey);

                cachedFileDao.save(cachedFile);

            }

        }
    };

    tempFile.delete();
    tempDir.delete();
    logger.debug("temp files and dirs cleared");

    if (sr.isRequestOk()) {
        sr.setPayload(md5);
    }
    logger.info("File with MD5 " + md5 + " is now in cache");
    return sr;
}

From source file:com.jhr.jarvis.table.TableRenderer.java

/**
 * Renders a textual representation of the provided {@link Table}
 * //from ww w . j a  v a2s.  c  om
 * @param table
 *            Table data {@link Table}
 * @return The rendered table representation as String
 */
public static String renderTextTable(Table table, boolean withHeader) {

    table.calculateColumnWidths();

    final String padding = "  ";
    final String headerBorder = getHeaderBorder(table.getHeaders());
    final StringBuilder textTable = new StringBuilder();

    if (withHeader) {
        final StringBuilder headerline = new StringBuilder();
        for (TableHeader header : table.getHeaders().values()) {

            if (header.getName().length() > header.getWidth()) {
                Iterable<String> chunks = Splitter.fixedLength(header.getWidth()).split(header.getName());
                int length = headerline.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + StringUtils.padRight(chunk, header.getWidth());
                    } else {
                        lineToAppend = StringUtils.padLeft("", length) + padding
                                + StringUtils.padRight(chunk, header.getWidth());
                    }
                    first = false;
                    headerline.append(lineToAppend);
                    headerline.append("\n");
                }
                headerline.deleteCharAt(headerline.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + StringUtils.padRight(header.getName(), header.getWidth());
                headerline.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(headerline.toString()));
        textTable.append("\n");
    }

    textTable.append(headerBorder);

    for (TableRow row : table.getRows()) {
        StringBuilder rowLine = new StringBuilder();
        for (Entry<Integer, TableHeader> entry : table.getHeaders().entrySet()) {
            String value = row.getValue(entry.getKey());
            if (value.length() > entry.getValue().getWidth()) {
                Iterable<String> chunks = Splitter.fixedLength(entry.getValue().getWidth()).split(value);
                int length = rowLine.length();
                boolean first = true;
                for (String chunk : chunks) {
                    final String lineToAppend;
                    if (first) {
                        lineToAppend = padding + StringUtils.padRight(chunk, entry.getValue().getWidth());
                    } else {
                        lineToAppend = StringUtils.padLeft("", length) + padding
                                + StringUtils.padRight(chunk, entry.getValue().getWidth());
                    }
                    first = false;
                    rowLine.append(lineToAppend);
                    rowLine.append("\n");
                }
                rowLine.deleteCharAt(rowLine.lastIndexOf("\n"));
            } else {
                String lineToAppend = padding + StringUtils.padRight(value, entry.getValue().getWidth());
                rowLine.append(lineToAppend);
            }
        }
        textTable.append(org.springframework.util.StringUtils.trimTrailingWhitespace(rowLine.toString()));
        textTable.append("\n");
    }

    if (!withHeader) {
        textTable.append(headerBorder);
    }

    return textTable.toString();
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public static String hashDataToDeviceIdString(byte[] hashData) {
    checkArgument(hashData.length == Hashing.sha256().bits() / 8);
    String string = BaseEncoding.base32().encode(hashData).replaceAll("=+$", "");
    string = Joiner.on("")
            .join(Iterables.transform(Splitter.fixedLength(13).split(string), new Function<String, String>() {
                @Override/*from   w  ww. j ava 2 s  .c om*/
                public String apply(String part) {
                    return part + generateLuhn32Checksum(part);
                }
            }));
    return Joiner.on("-").join(Splitter.fixedLength(7).split(string));
}

From source file:io.github.dre2n.factionscosmetics.scoreboards.BufferedObjective.java

@SuppressWarnings("deprecation")
public void flip() {
    if (!requiresUpdate) {
        return;/*from w ww .  j av a2 s.co m*/
    }
    requiresUpdate = false;

    Objective buffer = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy");
    buffer.setDisplayName(title);

    List<Team> bufferTeams = new ArrayList<>();

    for (Map.Entry<Integer, String> entry : contents.entrySet()) {
        if (entry.getValue().length() > 16) {
            Team team = scoreboard.registerNewTeam(getNextTeamName());
            bufferTeams.add(team);

            Iterator<String> split = Splitter.fixedLength(16).split(entry.getValue()).iterator();

            team.setPrefix(split.next());
            String name = split.next();
            if (split.hasNext()) { // We only guarantee two splits
                team.setSuffix(split.next());
            }

            try {
                addEntryMethod.invoke(team, name);
            } catch (ReflectiveOperationException ignored) {
            }
            buffer.getScore(name).setScore(entry.getKey());

        } else {
            buffer.getScore(entry.getValue()).setScore(entry.getKey());
        }
    }

    if (displaySlot != null) {
        buffer.setDisplaySlot(displaySlot);
    }

    // Unregister _ALL_ the old things
    current.unregister();

    Iterator<Team> it = currentTeams.iterator();
    while (it.hasNext()) {
        it.next().unregister();
        it.remove();
    }

    current = buffer;
    currentTeams = bufferTeams;
}

From source file:org.jclouds.chef.filters.SignedHeaderAuth.java

@VisibleForTesting
HttpRequest calculateAndReplaceAuthorizationHeaders(HttpRequest request, String toSign) throws HttpException {
    String signature = sign(toSign);
    if (signatureWire.enabled())
        signatureWire.input(Strings2.toInputStream(signature));
    String[] signatureLines = Iterables.toArray(Splitter.fixedLength(60).split(signature), String.class);

    Multimap<String, String> headers = ArrayListMultimap.create();
    for (int i = 0; i < signatureLines.length; i++) {
        headers.put("X-Ops-Authorization-" + (i + 1), signatureLines[i]);
    }// ww  w  . j  av a  2  s.  c o  m
    return request.toBuilder().replaceHeaders(headers).build();
}

From source file:uk.bl.wa.analyser.payload.WARCPayloadAnalysers.java

public void analyse(ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) {
    log.debug("Analysing " + header.getUrl());

    final long start = System.nanoTime();
    // Analyse with tika:
    try {// ww w  .j  ava  2  s  .  c o  m
        if (passUriToFormatTools) {
            solr = tika.extract(solr, tikainput, header.getUrl());
        } else {
            solr = tika.extract(solr, tikainput, null);
        }
    } catch (Exception i) {
        log.error(i + ": " + i.getMessage() + ";tika; " + header.getUrl() + "@" + header.getOffset());
    }
    Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "WARCPayloadAnalyzers.analyze#tikasolrextract",
            start);

    final long firstBytesStart = System.nanoTime();
    // Pull out the first few bytes, to hunt for new format by magic:
    try {
        tikainput.reset();
        byte[] ffb = new byte[this.firstBytesLength];
        int read = tikainput.read(ffb);
        if (read >= 4) {
            String hexBytes = Hex.encodeHexString(ffb);
            solr.addField(SolrFields.CONTENT_FFB, hexBytes.substring(0, 2 * 4));
            StringBuilder separatedHexBytes = new StringBuilder();
            for (String hexByte : Splitter.fixedLength(2).split(hexBytes)) {
                separatedHexBytes.append(hexByte);
                separatedHexBytes.append(" ");
            }
            if (this.extractContentFirstBytes) {
                solr.addField(SolrFields.CONTENT_FIRST_BYTES, separatedHexBytes.toString().trim());
            }
        }
    } catch (Exception i) {
        log.error(i + ": " + i.getMessage() + ";ffb; " + header.getUrl() + "@" + header.getOffset());
    }
    Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "WARCPayloadAnalyzers.analyze#firstbytes",
            firstBytesStart);

    // Also run DROID (restricted range):
    if (dd != null && runDroid == true) {
        final long droidStart = System.nanoTime();
        try {
            tikainput.reset();
            // Pass the URL in so DROID can fall back on that:
            Metadata metadata = new Metadata();
            if (passUriToFormatTools) {
                UsableURI uuri = UsableURIFactory.getInstance(header.getUrl());
                // Droid seems unhappy about spaces in filenames, so hack to avoid:
                String cleanUrl = uuri.getName().replace(" ", "+");
                metadata.set(Metadata.RESOURCE_NAME_KEY, cleanUrl);
            }
            // Run Droid:
            MediaType mt = dd.detect(tikainput, metadata);
            solr.addField(SolrFields.CONTENT_TYPE_DROID, mt.toString());
        } catch (Exception i) {
            // Note that DROID complains about some URLs with an IllegalArgumentException.
            log.error(i + ": " + i.getMessage() + ";dd; " + header.getUrl() + " @" + header.getOffset());
        }
        Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "WARCPayloadAnalyzers.analyze#droid",
                droidStart);
    }

    // Parse ARC name
    if (!arcname.getRules().isEmpty()) {
        final long nameStart = System.nanoTime();
        arcname.analyse(header, tikainput, solr);
        Instrument.timeRel("WARCPayloadAnalyzers.analyze#total", "WARCPayloadAnalyzers.analyze#arcname",
                nameStart);
    }

    try {
        tikainput.reset();
        String mime = (String) solr.getField(SolrFields.SOLR_CONTENT_TYPE).getValue();
        if (mime.startsWith("text") || mime.startsWith("application/xhtml+xml")) {
            html.analyse(header, tikainput, solr);

        } else if (mime.startsWith("image")) {
            if (this.extractImageFeatures) {
                image.analyse(header, tikainput, solr);
            }

        } else if (mime.startsWith("application/pdf")) {
            if (extractApachePreflightErrors) {
                pdf.analyse(header, tikainput, solr);
            }

        } else if (mime.startsWith("application/xml") || mime.startsWith("text/xml")) {
            xml.analyse(header, tikainput, solr);

        } else {
            log.debug("No specific additional parser for: " + mime);
        }
    } catch (Exception i) {
        log.error(i + ": " + i.getMessage() + ";x; " + header.getUrl() + "@" + header.getOffset());
    }
    Instrument.timeRel("WARCIndexer.extract#analyzetikainput", "WARCPayloadAnalyzers.analyze#total", start);

}

From source file:org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus.java

public final void addMessage(final String message) {
    if (message != null) {
        if (messages == null) {
            messages = new ArrayList<>((message.length() / MESSAGE_ENTRY_LENGTH) + 1);
        }/* w  ww.j  av a 2  s.com*/
        Splitter.fixedLength(MESSAGE_ENTRY_LENGTH).split(message).forEach(messages::add);
    }
}

From source file:com.microsoft.azure.management.dns.implementation.DnsRecordSetImpl.java

@Override
public DnsRecordSetImpl withText(String text) {
    if (text == null) {
        return this;
    }//w  ww  . ja  v  a  2s. co  m
    List<String> chunks = new ArrayList<>();
    for (String chunk : Splitter.fixedLength(255).split(text)) {
        chunks.add(chunk);
    }
    this.inner().txtRecords().add(new TxtRecord().withValue(chunks));
    return this;
}