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) {
Trid trid = null;
try {
EppInput eppInput = unmarshal(inputXmlBytes);
EppInput eppInput = unmarshal(EppInput.class, inputXmlBytes);
trid = Trid.create(eppInput.getCommandWrapper().getClTrid());
ImmutableList<String> targetIds = eppInput.getTargetIds();
metrics.setCommandName(eppInput.getCommandName());

View file

@ -76,9 +76,15 @@ public class EppXmlTransformer {
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 {
return INPUT_TRANSFORMER.unmarshal(new ByteArrayInputStream(bytes));
return INPUT_TRANSFORMER.unmarshal(clazz, new ByteArrayInputStream(bytes));
} catch (XmlException e) {
// 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));

View file

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

View file

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

View file

@ -184,7 +184,7 @@ public class RdeParser {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
t.transform(new StAXSource(reader), new StreamResult(bout));
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
Object element = XjcXmlTransformer.unmarshal(bin);
Object element = XjcXmlTransformer.unmarshal(Object.class, bin);
return element;
} else {
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. */
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();
// Send a PUT request to ICANN's HTTPS server.
@ -109,8 +110,8 @@ public class RdeReporter {
private XjcIirdeaResult parseResult(HTTPResponse rsp) throws XmlException {
byte[] responseBytes = rsp.getContent();
logger.infofmt("Received response:\n%s", new String(responseBytes, UTF_8));
XjcIirdeaResponseElement response =
XjcXmlTransformer.unmarshal(new ByteArrayInputStream(responseBytes));
XjcIirdeaResponseElement response = XjcXmlTransformer.unmarshal(
XjcIirdeaResponseElement.class, new ByteArrayInputStream(responseBytes));
XjcIirdeaResult result = response.getResult();
return result;
}

View file

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

View file

@ -138,7 +138,7 @@ final class GenerateApplicationsReportCommand implements RemoteApiCommand, Gtech
SignedMark signedMark;
try {
signedMark = unmarshal(signedMarkData);
signedMark = unmarshal(SignedMark.class, signedMarkData);
} catch (EppException e) {
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 {
XjcRdeDeposit deposit = XjcXmlTransformer.unmarshal(inputStream);
XjcRdeDeposit deposit = XjcXmlTransformer.unmarshal(XjcRdeDeposit.class, inputStream);
System.out.printf("ID: %s\n", deposit.getId());
System.out.printf("Previous ID: %s\n", deposit.getPrevId());
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.Strings.isNullOrEmpty;
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.util.X509Utils.getCertificateHash;
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.Parameters;
import google.registry.flows.EppXmlTransformer;
import google.registry.flows.FlowRunner;
import google.registry.flows.FlowRunner.CommitMode;
import google.registry.flows.FlowRunner.UserPrivileges;
@ -104,7 +104,7 @@ final class ValidateLoginCredentialsCommand implements RemoteApiCommand, GtechCo
System.out.println(runFlow(
new FlowRunner(
LoginFlow.class,
EppXmlTransformer.<EppInput>unmarshal(inputXmlBytes),
unmarshal(EppInput.class, inputXmlBytes),
Trid.create(null),
new HttpSessionMetadata(
new TlsCredentials(

View file

@ -297,7 +297,7 @@ public class VerifyOteAction implements Runnable, JsonAction {
if (xmlBytes == null) {
return;
}
final EppInput eppInput = unmarshal(xmlBytes);
final EppInput eppInput = unmarshal(EppInput.class, xmlBytes);
if (!statCounts.addAll(
FluentIterable.from(EnumSet.allOf(StatType.class))
.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.Strings.nullToEmpty;
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.registry.Registries.findTldForNameOrThrow;
import static google.registry.ui.server.SoyTemplateUtils.createTofuSupplier;
@ -36,7 +37,6 @@ import dagger.Provides;
import google.registry.config.RegistryEnvironment;
import google.registry.flows.EppException;
import google.registry.flows.EppXmlTransformer;
import google.registry.flows.FlowRunner;
import google.registry.flows.FlowRunner.CommitMode;
import google.registry.flows.FlowRunner.UserPrivileges;
@ -118,7 +118,7 @@ public class CheckApiAction implements Runnable {
.getBytes(UTF_8);
EppResponse response = new FlowRunner(
DomainCheckFlow.class,
EppXmlTransformer.<EppInput>unmarshal(inputXmlBytes),
unmarshal(EppInput.class, inputXmlBytes),
Trid.create(getClass().getSimpleName()),
sessionMetadata,
inputXmlBytes,

View file

@ -64,8 +64,8 @@ public class XjcXmlTransformer {
return INSTANCE;
}
public static <T> T unmarshal(InputStream stream) throws XmlException {
return INSTANCE.unmarshal(stream);
public static <T> T unmarshal(Class<T> clazz, InputStream stream) throws XmlException {
return INSTANCE.unmarshal(clazz, stream);
}
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}.
*
* <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.
* Turns XML text into an object, validating against hard-coded xml {@link #schema}s.
*
* @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
* element doesn't match {@code expect}.
* @see com.google.common.io.Files#asByteSource
* @see com.google.common.io.Resources#asByteSource
* @see "http://errorprone.info/bugpattern/TypeParameterUnusedInFormals"
*/
@SuppressWarnings("unchecked")
public <T> T unmarshal(InputStream stream) throws XmlException {
public <T> T unmarshal(Class<T> clazz, InputStream stream) throws XmlException {
try (InputStream autoClosingStream = stream) {
return (T) getUnmarshaller().unmarshal(
XML_INPUT_FACTORY.createXMLStreamReader(new StreamSource(autoClosingStream, SYSTEM_ID)));
return clazz.cast(getUnmarshaller().unmarshal(
XML_INPUT_FACTORY.createXMLStreamReader(new StreamSource(autoClosingStream, SYSTEM_ID))));
} catch (UnmarshalException e) {
// Plain old parsing exceptions have a SAXParseException with no further cause.
if (e.getLinkedException() instanceof SAXParseException