Search in sources :

Example 1 with IonWriter

use of com.amazon.ion.IonWriter in project amazon-qldb-dmv-sample-java by aws-samples.

the class GetRevision method verifyRegistration.

/**
 * Verify each version of the registration for the given VIN.
 *
 * @param driver
 *              A QLDB driver.
 * @param ledgerName
 *              The ledger to get digest from.
 * @param vin
 *              VIN to query the revision history of a specific registration with.
 * @throws Exception if failed to verify digests.
 * @throws AssertionError if document revision verification failed.
 */
public static void verifyRegistration(final QldbDriver driver, final String ledgerName, final String vin) throws Exception {
    log.info(String.format("Let's verify the registration with VIN=%s, in ledger=%s.", vin, ledgerName));
    try {
        log.info("First, let's get a digest.");
        GetDigestResult digestResult = GetDigest.getDigest(ledgerName);
        ValueHolder digestTipAddress = digestResult.getDigestTipAddress();
        byte[] digestBytes = Verifier.convertByteBufferToByteArray(digestResult.getDigest());
        log.info("Got a ledger digest. Digest end address={}, digest={}.", QldbStringUtils.toUnredactedString(digestTipAddress), Verifier.toBase64(digestBytes));
        log.info(String.format("Next, let's query the registration with VIN=%s. " + "Then we can verify each version of the registration.", vin));
        List<IonStruct> documentsWithMetadataList = new ArrayList<>();
        driver.execute(txn -> {
            documentsWithMetadataList.addAll(queryRegistrationsByVin(txn, vin));
        });
        log.info("Registrations queried successfully!");
        log.info(String.format("Found %s revisions of the registration with VIN=%s.", documentsWithMetadataList.size(), vin));
        for (IonStruct ionStruct : documentsWithMetadataList) {
            QldbRevision document = QldbRevision.fromIon(ionStruct);
            log.info(String.format("Let's verify the document: %s", document));
            log.info("Let's get a proof for the document.");
            GetRevisionResult proofResult = getRevision(ledgerName, document.getMetadata().getId(), digestTipAddress, document.getBlockAddress());
            final IonValue proof = Constants.MAPPER.writeValueAsIonValue(proofResult.getProof());
            final IonReader reader = IonReaderBuilder.standard().build(proof);
            reader.next();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IonWriter writer = SYSTEM.newBinaryWriter(baos);
            writer.writeValue(reader);
            writer.close();
            baos.flush();
            baos.close();
            byte[] byteProof = baos.toByteArray();
            log.info(String.format("Got back a proof: %s", Verifier.toBase64(byteProof)));
            boolean verified = Verifier.verify(document.getHash(), digestBytes, proofResult.getProof().getIonText());
            if (!verified) {
                throw new AssertionError("Document revision is not verified!");
            } else {
                log.info("Success! The document is verified");
            }
            byte[] alteredDigest = Verifier.flipRandomBit(digestBytes);
            log.info(String.format("Flipping one bit in the digest and assert that the document is NOT verified. " + "The altered digest is: %s", Verifier.toBase64(alteredDigest)));
            verified = Verifier.verify(document.getHash(), alteredDigest, proofResult.getProof().getIonText());
            if (verified) {
                throw new AssertionError("Expected document to not be verified against altered digest.");
            } else {
                log.info("Success! As expected flipping a bit in the digest causes verification to fail.");
            }
            byte[] alteredDocumentHash = Verifier.flipRandomBit(document.getHash());
            log.info(String.format("Flipping one bit in the document's hash and assert that it is NOT verified. " + "The altered document hash is: %s.", Verifier.toBase64(alteredDocumentHash)));
            verified = Verifier.verify(alteredDocumentHash, digestBytes, proofResult.getProof().getIonText());
            if (verified) {
                throw new AssertionError("Expected altered document hash to not be verified against digest.");
            } else {
                log.info("Success! As expected flipping a bit in the document hash causes verification to fail.");
            }
        }
    } catch (Exception e) {
        log.error("Failed to verify digests.", e);
        throw e;
    }
    log.info(String.format("Finished verifying the registration with VIN=%s in ledger=%s.", vin, ledgerName));
}
Also used : IonValue(com.amazon.ion.IonValue) GetDigestResult(com.amazonaws.services.qldb.model.GetDigestResult) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ValueHolder(com.amazonaws.services.qldb.model.ValueHolder) IOException(java.io.IOException) IonStruct(com.amazon.ion.IonStruct) QldbRevision(software.amazon.qldb.tutorial.qldb.QldbRevision) IonReader(com.amazon.ion.IonReader) IonWriter(com.amazon.ion.IonWriter) GetRevisionResult(com.amazonaws.services.qldb.model.GetRevisionResult)

Example 2 with IonWriter

use of com.amazon.ion.IonWriter in project amazon-qldb-dmv-sample-java by aws-samples.

the class QldbStringUtils method toUnredactedString.

/**
 * Returns the string representation of a given {@link ValueHolder}.
 * Adapted from the AWS SDK autogenerated {@code toString()} method, with sensitive values un-redacted.
 * Additionally, this method pretty-prints any IonText included in the {@link ValueHolder}.
 *
 * @param valueHolder the {@link ValueHolder} to convert to a String.
 * @return the String representation of the supplied {@link ValueHolder}.
 */
public static String toUnredactedString(ValueHolder valueHolder) {
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    if (valueHolder.getIonText() != null) {
        sb.append("IonText: ");
        IonWriter prettyWriter = IonTextWriterBuilder.pretty().build(sb);
        try {
            prettyWriter.writeValues(IonReaderBuilder.standard().build(valueHolder.getIonText()));
        } catch (IOException ioe) {
            sb.append("**Exception while printing this IonText**");
        }
    }
    sb.append("}");
    return sb.toString();
}
Also used : IonWriter(com.amazon.ion.IonWriter) IOException(java.io.IOException)

Example 3 with IonWriter

use of com.amazon.ion.IonWriter in project ion-java by amzn.

the class BinaryWriterTest method testNoIVMWrittenWhenNoValuesWritten.

@Test
public void testNoIVMWrittenWhenNoValuesWritten() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IonWriter writer = system().newBinaryWriter(out);
    writer.close();
    // no IVM written
    assertEquals(0, out.size());
}
Also used : IonWriter(com.amazon.ion.IonWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Test(org.junit.Test)

Example 4 with IonWriter

use of com.amazon.ion.IonWriter in project ion-java by amzn.

the class IonJavaCli method embeddedEventToIon.

private static int embeddedEventToIon(ProcessContext processContext, CommandArgs args, int count, IonType ionType) throws IOException {
    processContext.getIonWriter().addTypeAnnotation(EMBEDDED_STREAM_ANNOTATION);
    processContext.getIonWriter().stepIn(ionType);
    List<Event> events = processContext.getEventStream();
    int depth = 1;
    boolean finish = false;
    while (++count < events.size()) {
        StringBuilder out = new StringBuilder();
        ProcessContext embeddedContext = new ProcessContext(null, 0, null, null, ION_TEXT_WRITER_BUILDER.withImports(_Private_Utils.systemSymtab(1)).build(out));
        embeddedContext.setEmbeddedOut(out);
        try {
            do {
                Event event = events.get(count);
                processContext.setEventIndex(processContext.getEventIndex() + 1);
                processContext.setLastEventType(event.getEventType());
                if (event.getEventType() == EventType.STREAM_END) {
                    break;
                } else if (event.getEventType() == EventType.SCALAR) {
                    writeIonByType(event, embeddedContext.getIonWriter());
                } else if (event.getEventType() == EventType.CONTAINER_START) {
                    depth++;
                    setFieldName(event, embeddedContext.getIonWriter());
                    setAnnotations(event, embeddedContext.getIonWriter());
                    embeddedContext.getIonWriter().stepIn(event.getIonType());
                } else if (event.getEventType() == EventType.CONTAINER_END) {
                    depth--;
                    if (depth == 0) {
                        if (event.getIonType() == IonType.SEXP || event.getIonType() == IonType.LIST) {
                            finish = true;
                            break;
                        } else {
                            throw new IonException("invalid CONTAINER_END");
                        }
                    }
                    embeddedContext.getIonWriter().stepOut();
                } else if (event.getEventType() == EventType.SYMBOL_TABLE) {
                    handleSymbolTableEvent(embeddedContext, event, args, true);
                }
            } while (++count < events.size());
            if (!finish) {
                embeddedContext.getIonWriter().finish();
                processContext.getIonWriter().writeString(out.toString());
            }
        } finally {
            IonWriter ionWriter = embeddedContext.getIonWriter();
            if (ionWriter != null) {
                try {
                    ionWriter.close();
                } catch (IOException e) {
                    System.err.println(e.getMessage());
                    System.exit(IO_ERROR_EXIT_CODE);
                }
            }
        }
        if (finish) {
            break;
        }
    }
    processContext.getIonWriter().stepOut();
    return count;
}
Also used : IonException(com.amazon.ion.IonException) Event(com.amazon.tools.events.Event) IonWriter(com.amazon.ion.IonWriter) IOException(java.io.IOException)

Example 5 with IonWriter

use of com.amazon.ion.IonWriter in project ion-java by amzn.

the class IonJavaCli method main.

public static void main(final String[] args) {
    CommandArgs parsedArgs = new CommandArgs();
    CmdLineParser parser = new CmdLineParser(parsedArgs);
    parser.getProperties().withUsageWidth(CONSOLE_WIDTH);
    ComparisonType comparisonType = null;
    OutputFormat outputFormat = null;
    CommandType commandType = null;
    try {
        // parse
        parser.parseArgument(args);
        validateArgs(parsedArgs);
        // get value
        comparisonType = parsedArgs.getComparisonType();
        outputFormat = parsedArgs.getOutputFormat();
        commandType = parsedArgs.getCommand();
    } catch (CmdLineException | IllegalArgumentException e) {
        printHelpText(e.getMessage(), parser, parsedArgs);
        System.exit(USAGE_ERROR_EXIT_CODE);
    }
    if (commandType == CommandType.VERSION) {
        System.err.println(VERSION);
        System.exit(0);
    }
    ProcessContext processContext = commandType == CommandType.PROCESS ? new ProcessContext(null, -1, null, ErrorType.READ, null) : null;
    try (// Initialize output stream, never return null. (default value: STDOUT)
    OutputStream outputStream = initOutputStream(parsedArgs, SYSTEM_OUT_DEFAULT_VALUE, processContext);
        // Initialize error report, never return null. (default value: STDERR)
        OutputStream errorReportOutputStream = initOutputStream(parsedArgs, SYSTEM_ERR_DEFAULT_VALUE, processContext);
        IonWriter ionWriterForErrorReport = outputFormat.createIonWriter(errorReportOutputStream);
        IonWriter ionWriterForOutput = outputFormat.createIonWriter(outputStream)) {
        if (commandType == CommandType.COMPARE) {
            compareFiles(ionWriterForOutput, ionWriterForErrorReport, parsedArgs, comparisonType);
        } else if (commandType == CommandType.PROCESS) {
            processContext.setIonWriter(ionWriterForOutput);
            processFiles(ionWriterForErrorReport, parsedArgs, processContext);
        }
    } catch (IOException e) {
        System.err.println("Failed to close OutputStream: " + e.getMessage());
    } finally {
        if (processContext != null) {
            IonWriter ionWriter = processContext.getIonWriter();
            if (ionWriter != null) {
                try {
                    ionWriter.close();
                } catch (IOException e) {
                    System.err.println(e.getMessage());
                    System.exit(IO_ERROR_EXIT_CODE);
                }
            }
        }
    }
}
Also used : CmdLineParser(org.kohsuke.args4j.CmdLineParser) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IonWriter(com.amazon.ion.IonWriter) IOException(java.io.IOException) CmdLineException(org.kohsuke.args4j.CmdLineException)

Aggregations

IonWriter (com.amazon.ion.IonWriter)71 Test (org.junit.Test)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)35 IonReader (com.amazon.ion.IonReader)19 com.amazon.ion.impl._Private_IonWriter (com.amazon.ion.impl._Private_IonWriter)16 SymbolTable (com.amazon.ion.SymbolTable)12 IonDatagram (com.amazon.ion.IonDatagram)11 IOException (java.io.IOException)11 IonTextWriterBuilder (com.amazon.ion.system.IonTextWriterBuilder)10 com.amazon.ion.impl._Private_IonBinaryWriterBuilder (com.amazon.ion.impl._Private_IonBinaryWriterBuilder)9 IonSystem (com.amazon.ion.IonSystem)8 OutputStream (java.io.OutputStream)8 IonCatalog (com.amazon.ion.IonCatalog)4 IonReaderBuilder (com.amazon.ion.system.IonReaderBuilder)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ArrayList (java.util.ArrayList)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 IonException (com.amazon.ion.IonException)3 IonStruct (com.amazon.ion.IonStruct)3 StringWriter (java.io.StringWriter)3