Fix generics in EppXmlTransformer.unmarshal to not be only on the return type.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=124914271
This commit is contained in:
cgoldfeder 2016-06-14 20:58:57 -07:00 committed by Ben McIlwain
parent 6466ad51f6
commit ec39f15a23
31 changed files with 133 additions and 62 deletions

View file

@ -56,7 +56,7 @@ public final class EppController {
public byte[] handleEppCommand(SessionMetadata sessionMetadata, byte[] inputXmlBytes) { public byte[] handleEppCommand(SessionMetadata sessionMetadata, byte[] inputXmlBytes) {
Trid trid = null; Trid trid = null;
try { try {
EppInput eppInput = unmarshal(inputXmlBytes); EppInput eppInput = unmarshal(EppInput.class, inputXmlBytes);
trid = Trid.create(eppInput.getCommandWrapper().getClTrid()); trid = Trid.create(eppInput.getCommandWrapper().getClTrid());
ImmutableList<String> targetIds = eppInput.getTargetIds(); ImmutableList<String> targetIds = eppInput.getTargetIds();
metrics.setCommandName(eppInput.getCommandName()); metrics.setCommandName(eppInput.getCommandName());

View file

@ -76,9 +76,15 @@ public class EppXmlTransformer {
OUTPUT_TRANSFORMER.validate(xml); OUTPUT_TRANSFORMER.validate(xml);
} }
public static <T> T unmarshal(byte[] bytes) throws EppException { /**
* Unmarshal bytes into Epp classes.
*
* @param clazz type to return, specified as a param to enforce typesafe generics
* @see "http://errorprone.info/bugpattern/TypeParameterUnusedInFormals"
*/
public static <T> T unmarshal(Class<T> clazz, byte[] bytes) throws EppException {
try { try {
return INPUT_TRANSFORMER.unmarshal(new ByteArrayInputStream(bytes)); return INPUT_TRANSFORMER.unmarshal(clazz, new ByteArrayInputStream(bytes));
} catch (XmlException e) { } catch (XmlException e) {
// If this XmlException is wrapping a known type find it. If not, it's a syntax error. // If this XmlException is wrapping a known type find it. If not, it's a syntax error.
FluentIterable<Throwable> causalChain = FluentIterable.from(Throwables.getCausalChain(e)); FluentIterable<Throwable> causalChain = FluentIterable.from(Throwables.getCausalChain(e));

View file

@ -87,7 +87,7 @@ public class DomainApplicationInfoFlow extends BaseDomainInfoFlow<DomainApplicat
if (includeMarks) { if (includeMarks) {
for (EncodedSignedMark encodedMark : existingResource.getEncodedSignedMarks()) { for (EncodedSignedMark encodedMark : existingResource.getEncodedSignedMarks()) {
try { try {
marksBuilder.add(((SignedMark) unmarshal(encodedMark.getBytes())).getMark()); marksBuilder.add(unmarshal(SignedMark.class, encodedMark.getBytes()).getMark());
} catch (EppException e) { } catch (EppException e) {
// This is a serious error; don't let the benign EppException propagate. // This is a serious error; don't let the benign EppException propagate.
throw new IllegalStateException("Could not decode a stored encoded signed mark"); throw new IllegalStateException("Could not decode a stored encoded signed mark");

View file

@ -497,7 +497,7 @@ public class DomainFlowUtils {
SignedMark signedMark; SignedMark signedMark;
try { try {
signedMark = unmarshal(signedMarkData); signedMark = unmarshal(SignedMark.class, signedMarkData);
} catch (EppException e) { } catch (EppException e) {
throw new SignedMarkParsingErrorException(); throw new SignedMarkParsingErrorException();
} }

View file

@ -184,7 +184,7 @@ public class RdeParser {
ByteArrayOutputStream bout = new ByteArrayOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream();
t.transform(new StAXSource(reader), new StreamResult(bout)); t.transform(new StAXSource(reader), new StreamResult(bout));
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
Object element = XjcXmlTransformer.unmarshal(bin); Object element = XjcXmlTransformer.unmarshal(Object.class, bin);
return element; return element;
} else { } else {
throw new IllegalStateException(String.format("Not at element %s:%s", uri, name)); throw new IllegalStateException(String.format("Not at element %s:%s", uri, name));

View file

@ -69,7 +69,8 @@ public class RdeReporter {
/** Uploads {@code reportBytes} to ICANN. */ /** Uploads {@code reportBytes} to ICANN. */
public void send(byte[] reportBytes) throws IOException, XmlException { public void send(byte[] reportBytes) throws IOException, XmlException {
XjcRdeReportReport report = XjcXmlTransformer.unmarshal(new ByteArrayInputStream(reportBytes)); XjcRdeReportReport report = XjcXmlTransformer.unmarshal(
XjcRdeReportReport.class, new ByteArrayInputStream(reportBytes));
XjcRdeHeader header = report.getHeader().getValue(); XjcRdeHeader header = report.getHeader().getValue();
// Send a PUT request to ICANN's HTTPS server. // Send a PUT request to ICANN's HTTPS server.
@ -109,8 +110,8 @@ public class RdeReporter {
private XjcIirdeaResult parseResult(HTTPResponse rsp) throws XmlException { private XjcIirdeaResult parseResult(HTTPResponse rsp) throws XmlException {
byte[] responseBytes = rsp.getContent(); byte[] responseBytes = rsp.getContent();
logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8)); logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8));
XjcIirdeaResponseElement response = XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal(
XjcXmlTransformer.unmarshal(new ByteArrayInputStream(responseBytes)); XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes));
XjcIirdeaResult result = response.getResult(); XjcIirdeaResult result = response.getResult();
return result; return result;
} }

View file

@ -38,7 +38,6 @@ import com.googlecode.objectify.VoidWork;
import com.googlecode.objectify.Work; import com.googlecode.objectify.Work;
import google.registry.flows.EppException; import google.registry.flows.EppException;
import google.registry.flows.EppXmlTransformer;
import google.registry.model.domain.DesignatedContact; import google.registry.model.domain.DesignatedContact;
import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainApplication;
import google.registry.model.domain.DomainCommand; import google.registry.model.domain.DomainCommand;
@ -89,7 +88,7 @@ final class AllocateDomainCommand extends MutatingEppToolCommand {
/** Extract the registration period from the XML used to create the domain application. */ /** Extract the registration period from the XML used to create the domain application. */
private static Period extractPeriodFromXml(byte[] xmlBytes) throws EppException { private static Period extractPeriodFromXml(byte[] xmlBytes) throws EppException {
EppInput eppInput = unmarshal(xmlBytes); EppInput eppInput = unmarshal(EppInput.class, xmlBytes);
return ((DomainCommand.Create) return ((DomainCommand.Create)
((ResourceCommandWrapper) eppInput.getCommandWrapper().getCommand()) ((ResourceCommandWrapper) eppInput.getCommandWrapper().getCommand())
.getResourceCommand()).getPeriod(); .getResourceCommand()).getPeriod();
@ -150,8 +149,10 @@ final class AllocateDomainCommand extends MutatingEppToolCommand {
"contacts", contactsMapBuilder.build(), "contacts", contactsMapBuilder.build(),
"authInfo", application.getAuthInfo().getPw().getValue(), "authInfo", application.getAuthInfo().getPw().getValue(),
"smdId", application.getEncodedSignedMarks().isEmpty() "smdId", application.getEncodedSignedMarks().isEmpty()
? null : EppXmlTransformer.<SignedMark>unmarshal( ? null
application.getEncodedSignedMarks().get(0).getBytes()).getId(), : unmarshal(
SignedMark.class,
application.getEncodedSignedMarks().get(0).getBytes()).getId(),
"applicationRoid", application.getRepoId(), "applicationRoid", application.getRepoId(),
"applicationTime", application.getCreationTime().toString(), "applicationTime", application.getCreationTime().toString(),
"launchNotice", launchNotice == null ? null : ImmutableMap.of( "launchNotice", launchNotice == null ? null : ImmutableMap.of(

View file

@ -138,7 +138,7 @@ final class GenerateApplicationsReportCommand implements RemoteApiCommand, Gtech
SignedMark signedMark; SignedMark signedMark;
try { try {
signedMark = unmarshal(signedMarkData); signedMark = unmarshal(SignedMark.class, signedMarkData);
} catch (EppException e) { } catch (EppException e) {
return Optional.of(makeLine(domainApplication, "Unparseable SMD")); return Optional.of(makeLine(domainApplication, "Unparseable SMD"));
} }

View file

@ -86,7 +86,7 @@ final class ValidateEscrowDepositCommand implements Command {
} }
private static void validateXmlStream(InputStream inputStream) throws XmlException { private static void validateXmlStream(InputStream inputStream) throws XmlException {
XjcRdeDeposit deposit = XjcXmlTransformer.unmarshal(inputStream); XjcRdeDeposit deposit = XjcXmlTransformer.unmarshal(XjcRdeDeposit.class, inputStream);
System.out.printf("ID: %s\n", deposit.getId()); System.out.printf("ID: %s\n", deposit.getId());
System.out.printf("Previous ID: %s\n", deposit.getPrevId()); System.out.printf("Previous ID: %s\n", deposit.getPrevId());
System.out.printf("Type: %s\n", deposit.getType()); System.out.printf("Type: %s\n", deposit.getType());

View file

@ -17,6 +17,7 @@ package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.io.Resources.getResource; import static com.google.common.io.Resources.getResource;
import static google.registry.flows.EppXmlTransformer.unmarshal;
import static google.registry.tools.CommandUtilities.runFlow; import static google.registry.tools.CommandUtilities.runFlow;
import static google.registry.util.X509Utils.getCertificateHash; import static google.registry.util.X509Utils.getCertificateHash;
import static google.registry.util.X509Utils.loadCertificate; import static google.registry.util.X509Utils.loadCertificate;
@ -30,7 +31,6 @@ import com.google.template.soy.data.SoyMapData;
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters; import com.beust.jcommander.Parameters;
import google.registry.flows.EppXmlTransformer;
import google.registry.flows.FlowRunner; import google.registry.flows.FlowRunner;
import google.registry.flows.FlowRunner.CommitMode; import google.registry.flows.FlowRunner.CommitMode;
import google.registry.flows.FlowRunner.UserPrivileges; import google.registry.flows.FlowRunner.UserPrivileges;
@ -104,7 +104,7 @@ final class ValidateLoginCredentialsCommand implements RemoteApiCommand, GtechCo
System.out.println(runFlow( System.out.println(runFlow(
new FlowRunner( new FlowRunner(
LoginFlow.class, LoginFlow.class,
EppXmlTransformer.<EppInput>unmarshal(inputXmlBytes), unmarshal(EppInput.class, inputXmlBytes),
Trid.create(null), Trid.create(null),
new HttpSessionMetadata( new HttpSessionMetadata(
new TlsCredentials( new TlsCredentials(

View file

@ -297,7 +297,7 @@ public class VerifyOteAction implements Runnable, JsonAction {
if (xmlBytes == null) { if (xmlBytes == null) {
return; return;
} }
final EppInput eppInput = unmarshal(xmlBytes); final EppInput eppInput = unmarshal(EppInput.class, xmlBytes);
if (!statCounts.addAll( if (!statCounts.addAll(
FluentIterable.from(EnumSet.allOf(StatType.class)) FluentIterable.from(EnumSet.allOf(StatType.class))
.filter( .filter(

View file

@ -17,6 +17,7 @@ package google.registry.ui.server.api;
import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN;
import static google.registry.flows.EppXmlTransformer.unmarshal;
import static google.registry.model.eppcommon.ProtocolDefinition.ServiceExtension.FEE_0_6; import static google.registry.model.eppcommon.ProtocolDefinition.ServiceExtension.FEE_0_6;
import static google.registry.model.registry.Registries.findTldForNameOrThrow; import static google.registry.model.registry.Registries.findTldForNameOrThrow;
import static google.registry.ui.server.SoyTemplateUtils.createTofuSupplier; import static google.registry.ui.server.SoyTemplateUtils.createTofuSupplier;
@ -36,7 +37,6 @@ import dagger.Provides;
import google.registry.config.RegistryEnvironment; import google.registry.config.RegistryEnvironment;
import google.registry.flows.EppException; import google.registry.flows.EppException;
import google.registry.flows.EppXmlTransformer;
import google.registry.flows.FlowRunner; import google.registry.flows.FlowRunner;
import google.registry.flows.FlowRunner.CommitMode; import google.registry.flows.FlowRunner.CommitMode;
import google.registry.flows.FlowRunner.UserPrivileges; import google.registry.flows.FlowRunner.UserPrivileges;
@ -118,7 +118,7 @@ public class CheckApiAction implements Runnable {
.getBytes(UTF_8); .getBytes(UTF_8);
EppResponse response = new FlowRunner( EppResponse response = new FlowRunner(
DomainCheckFlow.class, DomainCheckFlow.class,
EppXmlTransformer.<EppInput>unmarshal(inputXmlBytes), unmarshal(EppInput.class, inputXmlBytes),
Trid.create(getClass().getSimpleName()), Trid.create(getClass().getSimpleName()),
sessionMetadata, sessionMetadata,
inputXmlBytes, inputXmlBytes,

View file

@ -64,8 +64,8 @@ public class XjcXmlTransformer {
return INSTANCE; return INSTANCE;
} }
public static <T> T unmarshal(InputStream stream) throws XmlException { public static <T> T unmarshal(Class<T> clazz, InputStream stream) throws XmlException {
return INSTANCE.unmarshal(stream); return INSTANCE.unmarshal(clazz, stream);
} }
public static void marshalLenient(Object root, Writer writer) throws XmlException { public static void marshalLenient(Object root, Writer writer) throws XmlException {

View file

@ -136,21 +136,19 @@ public class XmlTransformer {
} }
/** /**
* Turns XML text into an object, validating against {@link #schema}. * Turns XML text into an object, validating against hard-coded xml {@link #schema}s.
*
* <p>You must specify the XML class you expect to receive as the root element. Validation is
* performed in accordance with the hard-coded XML schemas.
* *
* @param clazz the XML class you expect to receive as the root element
* @throws XmlException if failed to read from {@code bytes}, XML input is invalid, or root * @throws XmlException if failed to read from {@code bytes}, XML input is invalid, or root
* element doesn't match {@code expect}. * element doesn't match {@code expect}.
* @see com.google.common.io.Files#asByteSource * @see com.google.common.io.Files#asByteSource
* @see com.google.common.io.Resources#asByteSource * @see com.google.common.io.Resources#asByteSource
* @see "http://errorprone.info/bugpattern/TypeParameterUnusedInFormals"
*/ */
@SuppressWarnings("unchecked") public <T> T unmarshal(Class<T> clazz, InputStream stream) throws XmlException {
public <T> T unmarshal(InputStream stream) throws XmlException {
try (InputStream autoClosingStream = stream) { try (InputStream autoClosingStream = stream) {
return (T) getUnmarshaller().unmarshal( return clazz.cast(getUnmarshaller().unmarshal(
XML_INPUT_FACTORY.createXMLStreamReader(new StreamSource(autoClosingStream, SYSTEM_ID))); XML_INPUT_FACTORY.createXMLStreamReader(new StreamSource(autoClosingStream, SYSTEM_ID))));
} catch (UnmarshalException e) { } catch (UnmarshalException e) {
// Plain old parsing exceptions have a SAXParseException with no further cause. // Plain old parsing exceptions have a SAXParseException with no further cause.
if (e.getLinkedException() instanceof SAXParseException if (e.getLinkedException() instanceof SAXParseException

View file

@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
package google.registry.flows; package google.registry.flows;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View file

@ -0,0 +1,52 @@
// Copyright 2016 The Domain Registry Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.EppXmlTransformer.unmarshal;
import static google.registry.util.ResourceUtils.readResourceBytes;
import google.registry.model.eppinput.EppInput;
import google.registry.model.eppoutput.EppOutput;
import google.registry.testing.ExceptionRule;
import google.registry.testing.ShardableTestCase;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link EppXmlTransformer}. */
@RunWith(JUnit4.class)
public class EppXmlTransformerTest extends ShardableTestCase {
@Rule
public final ExceptionRule thrown = new ExceptionRule();
@Test
public void testUnmarshalingEppInput() throws Exception {
EppInput input = unmarshal(
EppInput.class, readResourceBytes(getClass(), "testdata/contact_info.xml").read());
assertThat(input.getCommandName()).isEqualTo("Info");
}
@Test
public void testUnmarshalingWrongClassThrows() throws Exception {
thrown.expect(ClassCastException.class);
EppXmlTransformer.unmarshal(
EppOutput.class, readResourceBytes(getClass(), "testdata/contact_info.xml").read());
}
}

View file

@ -1140,6 +1140,7 @@ public class DomainApplicationCreateFlowTest
.setCreateBillingCost(Money.of(EUR, 13)) .setCreateBillingCost(Money.of(EUR, 13))
.setRestoreBillingCost(Money.of(EUR, 11)) .setRestoreBillingCost(Money.of(EUR, 11))
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.setServerStatusChangeBillingCost(Money.of(EUR, 19)) .setServerStatusChangeBillingCost(Money.of(EUR, 19))
.build()); .build());
persistContactsAndHosts(); persistContactsAndHosts();

View file

@ -560,6 +560,7 @@ public class DomainCreateFlowTest extends ResourceFlowTestCase<DomainCreateFlow,
.setCreateBillingCost(Money.of(EUR, 13)) .setCreateBillingCost(Money.of(EUR, 13))
.setRestoreBillingCost(Money.of(EUR, 11)) .setRestoreBillingCost(Money.of(EUR, 11))
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.setServerStatusChangeBillingCost(Money.of(EUR, 19)) .setServerStatusChangeBillingCost(Money.of(EUR, 19))
.build()); .build());
persistContactsAndHosts(); persistContactsAndHosts();

View file

@ -341,6 +341,7 @@ public class DomainRenewFlowTest extends ResourceFlowTestCase<DomainRenewFlow, D
.setCreateBillingCost(Money.of(EUR, 13)) .setCreateBillingCost(Money.of(EUR, 13))
.setRestoreBillingCost(Money.of(EUR, 11)) .setRestoreBillingCost(Money.of(EUR, 11))
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.setServerStatusChangeBillingCost(Money.of(EUR, 19)) .setServerStatusChangeBillingCost(Money.of(EUR, 19))
.build()); .build());
persistDomain(); persistDomain();

View file

@ -285,6 +285,7 @@ public class DomainRestoreRequestFlowTest extends
.setCreateBillingCost(Money.of(EUR, 13)) .setCreateBillingCost(Money.of(EUR, 13))
.setRestoreBillingCost(Money.of(EUR, 11)) .setRestoreBillingCost(Money.of(EUR, 11))
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.setServerStatusChangeBillingCost(Money.of(EUR, 19)) .setServerStatusChangeBillingCost(Money.of(EUR, 19))
.build()); .build());
runFlow(); runFlow();

View file

@ -444,6 +444,7 @@ public class DomainTransferRequestFlowTest
.setCreateBillingCost(Money.of(EUR, 13)) .setCreateBillingCost(Money.of(EUR, 13))
.setRestoreBillingCost(Money.of(EUR, 11)) .setRestoreBillingCost(Money.of(EUR, 11))
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(EUR, 7)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(EUR)))
.setServerStatusChangeBillingCost(Money.of(EUR, 19)) .setServerStatusChangeBillingCost(Money.of(EUR, 19))
.build()); .build());
doFailingTest("domain_transfer_request_fee.xml"); doFailingTest("domain_transfer_request_fee.xml");

View file

@ -67,6 +67,7 @@ public final class RegistrarBillingUtilsTest {
.setCurrency(JPY) .setCurrency(JPY)
.setRenewBillingCostTransitions( .setRenewBillingCostTransitions(
ImmutableSortedMap.of(START_OF_TIME, Money.parse("JPY 110"))) ImmutableSortedMap.of(START_OF_TIME, Money.parse("JPY 110")))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.parse("JPY 0")))
.setCreateBillingCost(Money.parse("JPY 130")) .setCreateBillingCost(Money.parse("JPY 130"))
.setRestoreBillingCost(Money.parse("JPY 170")) .setRestoreBillingCost(Money.parse("JPY 170"))
.setServerStatusChangeBillingCost(Money.parse("JPY 190")) .setServerStatusChangeBillingCost(Money.parse("JPY 190"))

View file

@ -197,7 +197,7 @@ public class RdeReportActionTest {
private static XjcRdeReportReport parseReport(byte[] data) { private static XjcRdeReportReport parseReport(byte[] data) {
try { try {
return XjcXmlTransformer.unmarshal(new ByteArrayInputStream(data)); return XjcXmlTransformer.unmarshal(XjcRdeReportReport.class, new ByteArrayInputStream(data));
} catch (XmlException e) { } catch (XmlException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View file

@ -200,8 +200,9 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.run(); action.run();
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData()); XjcRdeDeposit.class,
Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData());
XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit); XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit);
assertThat(header.getTld()).isEqualTo("lol"); assertThat(header.getTld()).isEqualTo("lol");
@ -230,8 +231,9 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.run(); action.run();
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData()); XjcRdeDeposit.class,
Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData());
assertThat(deposit.getType()).isEqualTo(XjcRdeDepositTypeType.FULL); assertThat(deposit.getType()).isEqualTo(XjcRdeDepositTypeType.FULL);
assertThat(deposit.getId()).isEqualTo(RdeUtil.timestampToId(DateTime.parse("2000-01-01TZ"))); assertThat(deposit.getId()).isEqualTo(RdeUtil.timestampToId(DateTime.parse("2000-01-01TZ")));
assertThat(deposit.getWatermark()).isEqualTo(DateTime.parse("2000-01-01TZ")); assertThat(deposit.getWatermark()).isEqualTo(DateTime.parse("2000-01-01TZ"));
@ -271,8 +273,9 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.run(); action.run();
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData()); XjcRdeDeposit.class,
Ghostryde.decode(readGcsFile(gcsService, XML_FILE), decryptKey).getData());
XjcRdeRegistrar registrar1 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit); XjcRdeRegistrar registrar1 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit);
XjcRdeRegistrar registrar2 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit); XjcRdeRegistrar registrar2 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit);
XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit); XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit);
@ -349,8 +352,9 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
for (GcsFilename filename : asList( for (GcsFilename filename : asList(
new GcsFilename("rde-bucket", "fop_1971-01-01_full_S1_R0.xml.ghostryde"), new GcsFilename("rde-bucket", "fop_1971-01-01_full_S1_R0.xml.ghostryde"),
new GcsFilename("rde-bucket", "fop_1971-01-05_thin_S1_R0.xml.ghostryde"))) { new GcsFilename("rde-bucket", "fop_1971-01-05_thin_S1_R0.xml.ghostryde"))) {
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(Ghostryde.decode(readGcsFile(gcsService, filename), decryptKey).getData()); XjcRdeDeposit.class,
Ghostryde.decode(readGcsFile(gcsService, filename), decryptKey).getData());
XjcRdeRegistrar registrar1 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit); XjcRdeRegistrar registrar1 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit);
XjcRdeRegistrar registrar2 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit); XjcRdeRegistrar registrar2 = extractAndRemoveContentWithType(XjcRdeRegistrar.class, deposit);
XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit); XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit);
@ -377,8 +381,9 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
GcsFilename filename = new GcsFilename("rde-bucket", "fop_2000-01-01_full_S1_R0.xml.ghostryde"); GcsFilename filename = new GcsFilename("rde-bucket", "fop_2000-01-01_full_S1_R0.xml.ghostryde");
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(Ghostryde.decode(readGcsFile(gcsService, filename), decryptKey).getData()); XjcRdeDeposit.class,
Ghostryde.decode(readGcsFile(gcsService, filename), decryptKey).getData());
XjcRdeDomain domain = extractAndRemoveContentWithType(XjcRdeDomain.class, deposit); XjcRdeDomain domain = extractAndRemoveContentWithType(XjcRdeDomain.class, deposit);
XjcRdeIdn firstIdn = extractAndRemoveContentWithType(XjcRdeIdn.class, deposit); XjcRdeIdn firstIdn = extractAndRemoveContentWithType(XjcRdeIdn.class, deposit);
XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit); XjcRdeHeader header = extractAndRemoveContentWithType(XjcRdeHeader.class, deposit);
@ -494,16 +499,17 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
action.run(); action.run();
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
XjcRdeDeposit deposit = XjcRdeDeposit deposit = unmarshal(
unmarshal(readXml("fop_2000-01-01_full_S1_R0.xml.ghostryde").getBytes(UTF_8)); XjcRdeDeposit.class,
readXml("fop_2000-01-01_full_S1_R0.xml.ghostryde").getBytes(UTF_8));
assertThat(deposit.getResend()).isEqualTo(0); assertThat(deposit.getResend()).isEqualTo(0);
setCursor(Registry.get("fop"), RDE_STAGING, DateTime.parse("2000-01-01TZ")); setCursor(Registry.get("fop"), RDE_STAGING, DateTime.parse("2000-01-01TZ"));
action.response = new FakeResponse(); action.response = new FakeResponse();
action.run(); action.run();
executeTasksUntilEmpty("mapreduce", clock); executeTasksUntilEmpty("mapreduce", clock);
deposit = unmarshal(
deposit = unmarshal(readXml("fop_2000-01-01_full_S1_R1.xml.ghostryde").getBytes(UTF_8)); XjcRdeDeposit.class, readXml("fop_2000-01-01_full_S1_R1.xml.ghostryde").getBytes(UTF_8));
assertThat(deposit.getResend()).isEqualTo(1); assertThat(deposit.getResend()).isEqualTo(1);
} }
@ -621,7 +627,7 @@ public class RdeStagingActionTest extends MapreduceTestCase<RdeStagingAction> {
}}); }});
} }
public static <T> T unmarshal(byte[] xml) throws XmlException { public static <T> T unmarshal(Class<T> clazz, byte[] xml) throws XmlException {
return XjcXmlTransformer.unmarshal(new ByteArrayInputStream(xml)); return XjcXmlTransformer.unmarshal(clazz, new ByteArrayInputStream(xml));
} }
} }

View file

@ -230,6 +230,7 @@ public class DatastoreHelper {
.setTldStateTransitions(tldStates) .setTldStateTransitions(tldStates)
// Set billing costs to distinct small primes to avoid masking bugs in tests. // Set billing costs to distinct small primes to avoid masking bugs in tests.
.setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, 11))) .setRenewBillingCostTransitions(ImmutableSortedMap.of(START_OF_TIME, Money.of(USD, 11)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(USD)))
.setCreateBillingCost(Money.of(USD, 13)) .setCreateBillingCost(Money.of(USD, 13))
.setRestoreBillingCost(Money.of(USD, 17)) .setRestoreBillingCost(Money.of(USD, 17))
.setServerStatusChangeBillingCost(Money.of(USD, 19)) .setServerStatusChangeBillingCost(Money.of(USD, 19))

View file

@ -14,12 +14,12 @@
package google.registry.testing; package google.registry.testing;
import static google.registry.flows.EppXmlTransformer.unmarshal;
import static google.registry.testing.TestDataHelper.loadFileWithSubstitutions; import static google.registry.testing.TestDataHelper.loadFileWithSubstitutions;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import google.registry.flows.EppXmlTransformer;
import google.registry.model.eppinput.EppInput; import google.registry.model.eppinput.EppInput;
import java.util.Map; import java.util.Map;
@ -38,7 +38,7 @@ public class EppLoader {
} }
public EppInput getEpp() throws Exception { public EppInput getEpp() throws Exception {
return EppXmlTransformer.unmarshal(eppXml.getBytes(UTF_8)); return unmarshal(EppInput.class, eppXml.getBytes(UTF_8));
} }
public String getEppXml() { public String getEppXml() {

View file

@ -18,6 +18,7 @@ import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.io.Resources.getResource; import static com.google.common.io.Resources.getResource;
import static com.google.common.io.Resources.toByteArray; import static com.google.common.io.Resources.toByteArray;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.flows.EppXmlTransformer.unmarshal;
import static google.registry.flows.picker.FlowPicker.getFlowClass; import static google.registry.flows.picker.FlowPicker.getFlowClass;
import static google.registry.model.domain.DesignatedContact.Type.ADMIN; import static google.registry.model.domain.DesignatedContact.Type.ADMIN;
import static google.registry.model.domain.DesignatedContact.Type.BILLING; import static google.registry.model.domain.DesignatedContact.Type.BILLING;
@ -37,7 +38,6 @@ import com.google.common.collect.ImmutableSet;
import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParameterException;
import com.googlecode.objectify.Ref; import com.googlecode.objectify.Ref;
import google.registry.flows.EppXmlTransformer;
import google.registry.flows.domain.DomainAllocateFlow; import google.registry.flows.domain.DomainAllocateFlow;
import google.registry.model.domain.DesignatedContact; import google.registry.model.domain.DesignatedContact;
import google.registry.model.domain.DomainApplication; import google.registry.model.domain.DomainApplication;
@ -157,9 +157,8 @@ public class AllocateDomainCommandTest extends CommandTestCase<AllocateDomainCom
@Test @Test
public void testXmlInstantiatesFlow() throws Exception { public void testXmlInstantiatesFlow() throws Exception {
assertThat( byte[] xmlBytes = readResourceBytes(getClass(), "testdata/allocate_domain.xml").read();
getFlowClass(EppXmlTransformer.<EppInput>unmarshal( assertThat(getFlowClass(unmarshal(EppInput.class, xmlBytes)))
readResourceBytes(getClass(), "testdata/allocate_domain.xml").read()))) .isEqualTo(DomainAllocateFlow.class);
.isEqualTo(DomainAllocateFlow.class);
} }
} }

View file

@ -216,7 +216,7 @@ public class GenerateEscrowDepositCommandTest
} }
public static Object unmarshal(byte[] xml) throws XmlException { public static Object unmarshal(byte[] xml) throws XmlException {
return XjcXmlTransformer.unmarshal(new ByteArrayInputStream(xml)); return XjcXmlTransformer.unmarshal(Object.class, new ByteArrayInputStream(xml));
} }
private static ImmutableMap<String, Long> mapifyCounts(XjcRdeHeader header) { private static ImmutableMap<String, Long> mapifyCounts(XjcRdeHeader header) {

View file

@ -199,6 +199,7 @@ public class UpdateTldCommandTest extends CommandTestCase<UpdateTldCommand> {
.setRestoreBillingCost(Money.ofMajor(JPY, 1)) .setRestoreBillingCost(Money.ofMajor(JPY, 1))
.setRenewBillingCostTransitions( .setRenewBillingCostTransitions(
ImmutableSortedMap.of(START_OF_TIME, Money.ofMajor(JPY, 1))) ImmutableSortedMap.of(START_OF_TIME, Money.ofMajor(JPY, 1)))
.setEapFeeSchedule(ImmutableSortedMap.of(START_OF_TIME, Money.zero(JPY)))
.setServerStatusChangeBillingCost(Money.ofMajor(JPY, 1)) .setServerStatusChangeBillingCost(Money.ofMajor(JPY, 1))
.build()); .build());
runCommandForced( runCommandForced(

View file

@ -86,7 +86,7 @@ public class XjcObjectTest {
@Test @Test
public void testUnmarshalUTF16() throws Exception { public void testUnmarshalUTF16() throws Exception {
XjcRdeDeposit deposit = unmarshal(new ByteArrayInputStream( XjcRdeDeposit deposit = unmarshal(XjcRdeDeposit.class, new ByteArrayInputStream(
RDE_DEPOSIT_FULL.replaceFirst("UTF-8", "UTF-16").getBytes(UTF_16))); RDE_DEPOSIT_FULL.replaceFirst("UTF-8", "UTF-16").getBytes(UTF_16)));
assertThat(deposit).isNotNull(); assertThat(deposit).isNotNull();
assertThat(deposit.getType()).isEqualTo(XjcRdeDepositTypeType.FULL); assertThat(deposit.getType()).isEqualTo(XjcRdeDepositTypeType.FULL);
@ -96,7 +96,7 @@ public class XjcObjectTest {
@Test @Test
public void testUnmarshalValidation() throws Exception { public void testUnmarshalValidation() throws Exception {
thrown.expect(Throwable.class, "pattern '\\w{1,13}' for type 'depositIdType'"); thrown.expect(Throwable.class, "pattern '\\w{1,13}' for type 'depositIdType'");
unmarshal(new ByteArrayInputStream( unmarshal(XjcRdeDeposit.class, new ByteArrayInputStream(
RDE_DEPOSIT_FULL.replaceFirst("id=\"[^\"]+\"", "id=\"\"").getBytes(UTF_8))); RDE_DEPOSIT_FULL.replaceFirst("id=\"[^\"]+\"", "id=\"\"").getBytes(UTF_8)));
} }
@ -115,7 +115,7 @@ public class XjcObjectTest {
@Test @Test
public void testNamespaceEpp() throws Exception { public void testNamespaceEpp() throws Exception {
String xml = unmarshal(new ByteArrayInputStream(readResourceUtf8( String xml = unmarshal(XjcObject.class, new ByteArrayInputStream(readResourceUtf8(
XjcObjectTest.class, "testdata/greeting.xml").getBytes(UTF_8))).toString(); XjcObjectTest.class, "testdata/greeting.xml").getBytes(UTF_8))).toString();
assertWithMessage(xml).that(xml).startsWith("<epp:epp "); assertWithMessage(xml).that(xml).startsWith("<epp:epp ");
assertWithMessage(xml).that(xml).contains("\"urn:ietf:params:xml:ns:epp-1.0\""); assertWithMessage(xml).that(xml).contains("\"urn:ietf:params:xml:ns:epp-1.0\"");
@ -124,6 +124,7 @@ public class XjcObjectTest {
/** Unmarshals XML assuming UTF-8 encoding. */ /** Unmarshals XML assuming UTF-8 encoding. */
private static XjcRdeDeposit unmarshalFullDeposit() throws Exception { private static XjcRdeDeposit unmarshalFullDeposit() throws Exception {
return unmarshal(new ByteArrayInputStream(RDE_DEPOSIT_FULL.getBytes(UTF_8))); return unmarshal(
XjcRdeDeposit.class, new ByteArrayInputStream(RDE_DEPOSIT_FULL.getBytes(UTF_8)));
} }
} }

View file

@ -147,13 +147,13 @@ public class XmlTestdataTest {
@Theory @Theory
public void testValid(Good v) throws Exception { public void testValid(Good v) throws Exception {
XjcObject xml = unmarshal(v.xmlStream); XjcObject xml = unmarshal(XjcObject.class, v.xmlStream);
assertThat(xml).isInstanceOf(v.clazz); assertThat(xml).isInstanceOf(v.clazz);
} }
@Theory @Theory
public void testInvalid(Evil v) throws Exception { public void testInvalid(Evil v) throws Exception {
thrown.expectMessage(v.error); thrown.expectMessage(v.error);
unmarshal(v.xmlStream); unmarshal(XjcObject.class, v.xmlStream);
} }
} }