Search in sources :

Example 1 with TableAppender

use of org.apache.sis.io.TableAppender in project sis by apache.

the class AbstractMap method toString.

/**
 * Returns a string representation of this map. The default implementation is different than the
 * {@code java.util.AbstractMap} one, as it uses a tabular format rather than formatting all entries
 * on a single line.
 *
 * @return a string representation of this map.
 */
@Override
public String toString() {
    final TableAppender buffer = new TableAppender(" = ");
    buffer.setMultiLinesCells(true);
    final EntryIterator<K, V> it = entryIterator();
    if (it != null)
        while (it.next()) {
            buffer.append(String.valueOf(it.getKey()));
            buffer.nextColumn();
            buffer.append(AbstractMapEntry.firstLine(it.getValue()));
            buffer.nextLine();
        }
    return buffer.toString();
}
Also used : TableAppender(org.apache.sis.io.TableAppender)

Example 2 with TableAppender

use of org.apache.sis.io.TableAppender in project sis by apache.

the class CRSBuilder method toString.

/**
 * Returns a string representation of the keys and associated values in this {@code CRSBuilder}.
 */
@Debug
@Override
public final String toString() {
    final StringBuilder buffer = new StringBuilder("GeoTIFF keys ").append(majorRevision).append('.').append(minorRevision).append(" in ").append(reader.input.filename).append(System.lineSeparator());
    final TableAppender table = new TableAppender(buffer, " ");
    for (Map.Entry<Short, Object> entry : geoKeys.entrySet()) {
        final short key = entry.getKey();
        table.append(String.valueOf(key)).nextColumn();
        table.append(GeoKeys.name(key)).nextColumn();
        table.append(" = ").append(String.valueOf(entry.getValue())).nextLine();
    }
    try {
        table.flush();
    } catch (IOException e) {
        // Should never happen since we wrote to a StringBuffer.
        throw new AssertionError(e);
    }
    return buffer.toString();
}
Also used : TableAppender(org.apache.sis.io.TableAppender) IdentifiedObject(org.opengis.referencing.IdentifiedObject) NilReferencingObject(org.apache.sis.internal.referencing.NilReferencingObject) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) Debug(org.apache.sis.util.Debug)

Example 3 with TableAppender

use of org.apache.sis.io.TableAppender in project sis by apache.

the class TransformCommand method run.

/**
 * Transforms coordinates from the files given in argument or from the standard input stream.
 *
 * @return 0 on success, or an exit code if the command failed for a reason other than an uncaught Java exception.
 */
@Override
public int run() throws Exception {
    final CoordinateReferenceSystem sourceCRS = fetchCRS(Option.SOURCE_CRS);
    final CoordinateReferenceSystem targetCRS = fetchCRS(Option.TARGET_CRS);
    /*
         * Read all coordinates, so we can compute the area of interest.
         * This will be used when searching for a coordinate operation.
         */
    GeographicBoundingBox areaOfInterest = null;
    List<double[]> points = Collections.emptyList();
    final boolean useStandardInput = useStandardInput();
    if (useStandardInput || !files.isEmpty()) {
        if (useStandardInput) {
            try (LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in, encoding))) {
                points = readCoordinates(in, "stdin");
            }
        } else {
            for (final String file : files) {
                try (LineNumberReader in = new LineNumberReader(new InputStreamReader(new FileInputStream(file), encoding))) {
                    points = readCoordinates(in, file);
                }
            }
        }
        try {
            final GeographicCRS domainOfValidityCRS = ReferencingUtilities.toNormalizedGeographicCRS(sourceCRS);
            if (domainOfValidityCRS != null) {
                toDomainOfValidity = CRS.findOperation(sourceCRS, domainOfValidityCRS, null).getMathTransform();
                areaOfInterest = computeAreaOfInterest(points);
            }
        } catch (FactoryException e) {
            warning(e);
        }
    }
    operation = CRS.findOperation(sourceCRS, targetCRS, areaOfInterest);
    /*
         * Prints the header: source CRS, target CRS, operation steps and positional accuracy.
         */
    outHeader = new TableAppender(new LineAppender(out), " ");
    outHeader.setMultiLinesCells(true);
    printHeader(Vocabulary.Keys.Source);
    printNameAndIdentifier(operation.getSourceCRS(), false);
    printHeader(Vocabulary.Keys.Destination);
    printNameAndIdentifier(operation.getTargetCRS(), false);
    printHeader(Vocabulary.Keys.Operations);
    printOperations(operation, false);
    outHeader.nextLine();
    printDomainOfValidity(operation.getDomainOfValidity());
    printAccuracy(CRS.getLinearAccuracy(operation));
    if (options.containsKey(Option.VERBOSE)) {
        printDetails();
    }
    outHeader.flush();
    outHeader = null;
    /*
         * At this point we finished to write the header. If there is at least one input file,
         * compute the number of digits to format and perform the actual coordinate operations.
         */
    if (!points.isEmpty()) {
        // Must be set before computeNumFractionDigits(…).
        ordinateWidth = 15;
        coordinateFormat = NumberFormat.getInstance(Locale.US);
        coordinateFormat.setGroupingUsed(false);
        computeNumFractionDigits(operation.getTargetCRS().getCoordinateSystem());
        out.println();
        printAxes(operation.getTargetCRS().getCoordinateSystem());
        out.println();
        transform(points);
        if (errorMessage != null) {
            error(errorMessage, errorCause);
        }
    }
    return 0;
}
Also used : InputStreamReader(java.io.InputStreamReader) FactoryException(org.opengis.util.FactoryException) TableAppender(org.apache.sis.io.TableAppender) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) GeographicBoundingBox(org.opengis.metadata.extent.GeographicBoundingBox) DefaultGeographicBoundingBox(org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox) InternationalString(org.opengis.util.InternationalString) GeographicCRS(org.opengis.referencing.crs.GeographicCRS) LineAppender(org.apache.sis.io.LineAppender) FileInputStream(java.io.FileInputStream) LineNumberReader(java.io.LineNumberReader)

Example 4 with TableAppender

use of org.apache.sis.io.TableAppender in project sis by apache.

the class HelpCommand method help.

/**
 * Implementation of {@link #run()}, also shared by {@link CommandRunner#help(String)}.
 *
 * @param  showHeader    {@code true} for printing the "Apache SIS" header.
 * @param  commandNames  the names of the commands to list.
 * @param  validOptions  the options to list.
 * @throws IOException should never happen, because we are writing to a {@code PrintWriter}.
 */
void help(final boolean showHeader, final String[] commandNames, final EnumSet<Option> validOptions) throws IOException {
    final ResourceBundle commands = ResourceBundle.getBundle("org.apache.sis.console.Commands", locale);
    final ResourceBundle options = ResourceBundle.getBundle("org.apache.sis.console.Options", locale);
    final Vocabulary vocabulary = Vocabulary.getResources(locale);
    if (showHeader) {
        out.print("Apache SIS, ");
        out.println(commands.getString("SIS"));
        out.println(commands.getString("Usage"));
        out.println();
        out.print(vocabulary.getString(Vocabulary.Keys.Commands));
        out.println(':');
    }
    final TableAppender table = new TableAppender(out, "  ");
    for (final String command : commandNames) {
        if (showHeader) {
            table.append("  ");
        }
        table.append(command);
        if (!showHeader) {
            table.append(':');
        }
        table.nextColumn();
        table.append(commands.getString(command));
        table.nextLine();
    }
    table.flush();
    out.println();
    out.print(vocabulary.getString(Vocabulary.Keys.Options));
    out.println(':');
    for (final Option option : validOptions) {
        final String name = option.label();
        table.append("  ").append(Option.PREFIX).append(name);
        table.nextColumn();
        table.append(options.getString(name));
        table.nextLine();
    }
    table.flush();
}
Also used : Vocabulary(org.apache.sis.util.resources.Vocabulary) TableAppender(org.apache.sis.io.TableAppender) ResourceBundle(java.util.ResourceBundle)

Example 5 with TableAppender

use of org.apache.sis.io.TableAppender in project sis by apache.

the class ParameterFormat method formatSummary.

/**
 * Implementation of public {@code format(…)} methods for {@code NAME_SUMMARY} content level.
 *
 * @param  objects  the collection of objects to format.
 * @param  out      the stream or buffer where to write the summary.
 * @throws IOException if an error occurred will writing to the given appendable.
 */
private void formatSummary(final IdentifiedObject[] objects, final Appendable out) throws IOException {
    final Vocabulary resources = Vocabulary.getResources(displayLocale);
    /*
         * Prepares all rows before we write them to the output stream, because not all
         * identified objects may have names with the same scopes in the same order. We
         * also need to iterate over all rows in order to know the number of columns.
         *
         * The first column is reserved for the identifier. We put null as a sentinal key for
         * that column name, to be replaced later by "Identifier" in user locale. We can not
         * put the localized strings in the map right now because they could conflict with
         * the scope of some alias to be processed below.
         */
    boolean hasIdentifiers = false;
    final List<String[]> rows = new ArrayList<>();
    final Map<String, Integer> columnIndices = new LinkedHashMap<>();
    // See above comment for the meaning of "null" here.
    columnIndices.put(null, 0);
    if (preferredCodespaces != null) {
        for (final String codespace : preferredCodespaces) {
            columnIndices.put(codespace, columnIndices.size());
        }
    }
    for (final IdentifiedObject object : objects) {
        // Will growth later if needed.
        String[] row = new String[columnIndices.size()];
        /*
             * Put the first identifier in the first column. If no identifier has a codespace in the list
             * supplied by the user, then we will use the first identifier (any codespace) as a fallback.
             */
        final Set<ReferenceIdentifier> identifiers = object.getIdentifiers();
        if (identifiers != null) {
            // Paranoiac check.
            Identifier identifier = null;
            for (final ReferenceIdentifier candidate : identifiers) {
                if (candidate != null) {
                    // Paranoiac check.
                    if (isPreferredCodespace(candidate.getCodeSpace())) {
                        identifier = candidate;
                        // Format now.
                        break;
                    }
                    if (identifier == null) {
                        // To be used as a fallback if we find nothing better.
                        identifier = candidate;
                    }
                }
            }
            if (identifier != null) {
                row[0] = IdentifiedObjects.toString(identifier);
                hasIdentifiers = true;
            }
        }
        /*
             * If the name's codespace is in the list of codespaces asked by the user, add that name
             * in the current row and clear the 'name' locale variable. Otherwise, keep the 'name'
             * locale variable in case we found no alias to format.
             */
        ReferenceIdentifier name = object.getName();
        if (name != null) {
            // Paranoiac check.
            final String codespace = name.getCodeSpace();
            if (isPreferredCodespace(codespace)) {
                row = putIfAbsent(resources, row, columnIndices, codespace, name.getCode());
                name = null;
            }
        }
        /*
             * Put all aliases having a codespace in the list asked by the user.
             */
        final Collection<GenericName> aliases = object.getAlias();
        if (aliases != null) {
            // Paranoiac check.
            for (final GenericName alias : aliases) {
                if (alias != null) {
                    // Paranoiac check.
                    final String codespace = NameToIdentifier.getCodeSpace(alias, displayLocale);
                    if (isPreferredCodespace(codespace)) {
                        row = putIfAbsent(resources, row, columnIndices, codespace, alias.tip().toInternationalString().toString(displayLocale));
                        name = null;
                    }
                }
            }
        }
        /*
             * If no name and no alias have a codespace in the list of codespaces asked by the user,
             * force the addition of primary name regardless its codespace.
             */
        if (name != null) {
            row = putIfAbsent(resources, row, columnIndices, name.getCodeSpace(), name.getCode());
        }
        rows.add(row);
    }
    /*
         * Writes the table. The header will contain one column for each codespace in the order declared
         * by the user. If the user did not specified any codespace, or if we had to write codespace not
         * on the user list, then those codespaces will be written in the order we found them.
         */
    final boolean hasColors = (colors != null);
    final TableAppender table = new TableAppender(out, columnSeparator);
    table.setMultiLinesCells(true);
    table.appendHorizontalSeparator();
    for (String codespace : columnIndices.keySet()) {
        if (codespace == null) {
            // Skip empty column.
            if (!hasIdentifiers)
                continue;
            codespace = resources.getString(Vocabulary.Keys.Identifier);
        }
        if (hasColors) {
            codespace = X364.BOLD.sequence() + codespace + X364.NORMAL.sequence();
        }
        table.append(codespace);
        nextColumn(table);
    }
    table.appendHorizontalSeparator();
    /*
         * Writes row content.
         */
    final int numColumns = columnIndices.size();
    for (final String[] row : rows) {
        for (int i = hasIdentifiers ? 0 : 1; i < numColumns; i++) {
            if (i < row.length) {
                final String name = row[i];
                if (name != null) {
                    table.append(name);
                }
            }
            nextColumn(table);
        }
        table.nextLine();
    }
    table.appendHorizontalSeparator();
    table.flush();
}
Also used : Vocabulary(org.apache.sis.util.resources.Vocabulary) ArrayList(java.util.ArrayList) TableAppender(org.apache.sis.io.TableAppender) LinkedHashMap(java.util.LinkedHashMap) GenericName(org.opengis.util.GenericName) ReferenceIdentifier(org.opengis.referencing.ReferenceIdentifier) NameToIdentifier(org.apache.sis.internal.metadata.NameToIdentifier) Identifier(org.opengis.metadata.Identifier) ReferenceIdentifier(org.opengis.referencing.ReferenceIdentifier) IdentifiedObject(org.opengis.referencing.IdentifiedObject)

Aggregations

TableAppender (org.apache.sis.io.TableAppender)15 IOException (java.io.IOException)7 Vocabulary (org.apache.sis.util.resources.Vocabulary)6 IdentifiedObject (org.opengis.referencing.IdentifiedObject)4 InternationalString (org.opengis.util.InternationalString)4 Format (java.text.Format)3 NumberFormat (java.text.NumberFormat)3 TabularFormat (org.apache.sis.io.TabularFormat)3 Debug (org.apache.sis.util.Debug)3 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)3 FieldPosition (java.text.FieldPosition)2 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 GeographicBoundingBox (org.opengis.metadata.extent.GeographicBoundingBox)2 GeographicCRS (org.opengis.referencing.crs.GeographicCRS)2 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 LineNumberReader (java.io.LineNumberReader)1