org.apache.axis.encoding.SerializationContext Java Examples

The following examples show how to use org.apache.axis.encoding.SerializationContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AxisUtil.java    From j-road with Apache License 2.0 6 votes vote down vote up
public static String serialize(Object obj) throws IOException {
  TypeDesc desc = TypeDesc.getTypeDescForClass(obj.getClass());
  BeanSerializer serializer = new BeanSerializer(obj.getClass(), desc.getXmlType(), desc);

  MessageContext mctx = new MessageContext(null);
  mctx.setProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION, true);
  mctx.setProperty(AxisEngine.PROP_SEND_XSI, true);
  mctx.setTypeMappingRegistry(new TypeMappingRegistryImpl());

  StringWriter writer = new StringWriter();

  SerializationContext ctx = new SerializationContext(writer, mctx);
  ctx.setPretty(false);
  ctx.setSendDecl(true);
  ctx.setDoMultiRefs(false);

  serializer.serialize(new QName("keha"), new AttributesImpl(), obj, ctx);
  return writer.getBuffer().toString();
}
 
Example #2
Source File: XmlSerializer.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof XMLizable) {
    try {
      // System.out.println("AxisResourceServiceSerializer::serialize(" + name + ")");
      context.startElement(name, attributes);

      SerializerContentHandler contentHandler = new SerializerContentHandler(context);
      ((XMLizable) value).toXML(contentHandler);
      context.endElement();
    } catch (SAXException e) {
      throw new IOException("SAXException: " + e.getMessage());
    }
  } else {
    throw new IOException("Can't serialize a " + value.getClass().getName()
            + " with an XmlSerializer.");
  }
}
 
Example #3
Source File: XmlSerializer_Axis11.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof XMLizable) {
    try {
      // System.out.println("AxisResourceServiceSerializer::serialize(" + name + ")");
      context.startElement(name, attributes);

      SerializerContentHandler contentHandler = new SerializerContentHandler(context);
      ((XMLizable) value).toXML(contentHandler);
      context.endElement();
    } catch (SAXException e) {
      throw new IOException("SAXException: " + e.getMessage());
    }
  } else {
    throw new IOException("Can't serialize a " + value.getClass().getName()
            + " with an XmlSerializer.");
  }
}
 
Example #4
Source File: AxisSerializer.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
public <T extends Serializable> void serialize(
    T objectToSerialize, SerializationContext serializationContext) {
  try {
    QName xmlType = getXmlType(objectToSerialize.getClass());
    getSerializer(xmlType, objectToSerialize.getClass())
        .serialize(xmlType, null, objectToSerialize, serializationContext);
  } catch (RuntimeException
      | IOException
      | NoSuchMethodException
      | IllegalAccessException
      | InvocationTargetException e) {
    throw new RuntimeException("Failed to serialize: " + objectToSerialize, e);
  }
}
 
Example #5
Source File: AxisBatchJobUploadBodyProvider.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Override
public ByteArrayContent getHttpContent(BatchJobMutateRequestInterface request,
    boolean isFirstRequest, boolean isLastRequest) throws BatchJobException {
  Preconditions.checkNotNull(request, "Null request");

  StringWriter writer = new StringWriter();
  SerializationContext context = new SerializationContext(writer) {
    /**
     * Override the serialize method called by the Axis serializer and force it to
     * pass {@code includeNull = false}.
     */
    @SuppressWarnings("rawtypes")
    @Override
    public void serialize(QName elemQName, Attributes attributes, Object value, QName xmlType,
        Class javaType) throws IOException {
      super.serialize(elemQName, attributes, value, xmlType, javaType, false, null);
    }
  };
  context.setSendDecl(false);
  context.setPretty(true);
  
  // Pre-register namespaces using the *sorted* list of namespaces. This ensures that
  // when performing an incremental upload, the same namespace prefix will be used
  // for each namespace URI across all uploads.
  int namespaceIndex = 0;
  for(String namespaceUri : namespaceUris) {
    context.registerPrefixForURI(String.format("ns%d", namespaceIndex++),
        namespaceUri);
  }
  
  AxisSerializer serializer = new AxisSerializer();
  serializer.serialize(request, context);

  return new ByteArrayContent("application/xml", writer.toString().getBytes(UTF_8));
}
 
Example #6
Source File: AxisSerializerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialize() throws SAXException, IOException {
  BatchJobMutateRequest mutate = new BatchJobMutateRequest();

  List<Operation> ops = Lists.newArrayList();
  Campaign campaign = new Campaign();
  campaign.setId(-1L);
  campaign.setName("Test campaign");
  campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
  ops.add(new CampaignOperation(Operator.ADD, "ADD", campaign));

  AdGroup adGroup = new AdGroup();
  adGroup.setName("Test ad group");
  adGroup.setCampaignId(campaign.getId());

  ops.add(new AdGroupOperation(Operator.ADD, "ADD", adGroup));

  mutate.setOperations(ops.toArray(new Operation[0]));
  AxisSerializer serializer = new AxisSerializer();
  StringWriter writer = new StringWriter();
  SerializationContext context = new SerializationContext(writer);
  context.setSendDecl(true);
  context.setPretty(true);
  serializer.serialize(mutate, context);

  String serializedRequest = writer.toString();
  assertNotNull("Serialized request is null", serializedRequest);

  String expectedSerializedRequest =
      CharStreams.toString(
          new InputStreamReader(
              AxisSerializerTest.class.getResourceAsStream(
                  "resources/BatchJobMutate.request.xml"),
              UTF_8));
  XMLAssert.assertXMLEqual("Serialized request does not match expected XML",
      expectedSerializedRequest, serializedRequest);
}
 
Example #7
Source File: BinarySerializer.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof Serializable) {
    byte[] bytes = SerializationUtils.serialize((Serializable) value);

    // Should we use an attachment? Do so if:
    // (a) attachment support exists and mUseAttachments == true and
    // (b) if we are the server, the client sent us an attachment
    // (so we know client wants attachment support as well)]
    Message msg = context.getCurrentMessage();
    Attachments attachments = msg.getAttachmentsImpl();
    boolean useAttachments = (attachments != null) && mUseAttachments;
    if (useAttachments) {
      useAttachments = !context.getMessageContext().getPastPivot()
              || context.getMessageContext().getRequestMessage().getAttachments().hasNext();
    }
    // if we have attachment support, do this as an attachment
    if (useAttachments) {
      // System.out.println("Creating attachment"); //DEBUG
      SOAPConstants soapConstants = context.getMessageContext().getSOAPConstants();
      DataHandler dataHandler = new DataHandler(new OctetStreamDataSource("test",
              new OctetStream(bytes)));
      Part attachmentPart = attachments.createAttachmentPart(dataHandler);

      AttributesImpl attrs = new AttributesImpl();
      if (attributes != null && 0 < attributes.getLength())
        attrs.setAttributes(attributes); // copy the existing ones.

      int typeIndex = -1;
      if ((typeIndex = attrs.getIndex(Constants.URI_DEFAULT_SCHEMA_XSI, "type")) != -1) {
        // Found a xsi:type which should not be there for attachments.
        attrs.removeAttribute(typeIndex);
      }

      attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
              attachmentPart.getContentIdRef());
      context.startElement(name, attrs);
      context.endElement();
    } else {
      // no attachment support - Base64 encode
      // System.out.println("No attachment support"); //DEBUG
      context.startElement(name, attributes);

      String base64str = Base64.encode(bytes);
      context.writeChars(base64str.toCharArray(), 0, base64str.length());
      context.endElement();
    }

  } else {
    throw new IOException(value.getClass().getName() + " is not serializable.");
  }
}
 
Example #8
Source File: BinarySerializer_Axis11.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Serialize an element named name, with the indicated attributes and value.
 *
 * @param name          is the element name
 * @param attributes          are the attributes...serializer is free to add more.
 * @param value          is the value
 * @param context          is the SerializationContext
 * @throws IOException Signals that an I/O exception has occurred.
 */
@Override
public void serialize(QName name, Attributes attributes, Object value,
        SerializationContext context) throws IOException {
  if (value instanceof Serializable) {
    byte[] bytes = SerializationUtils.serialize((Serializable) value);

    // Should we use an attachment? Do so if:
    // (a) attachment support exists and mUseAttachments == true and
    // (b) if we are the server, the client sent us an attachment
    // (so we know client wants attachment support as well)]
    Message msg = context.getCurrentMessage();
    Attachments attachments = msg.getAttachmentsImpl();
    boolean useAttachments = (attachments != null) && mUseAttachments;
    if (useAttachments) {
      useAttachments = !context.getMessageContext().getPastPivot()
              || context.getMessageContext().getRequestMessage().getAttachments().hasNext();
    }
    // if we have attachment support, do this as an attachment
    if (useAttachments) {
      // System.out.println("Creating attachment"); //DEBUG
      SOAPConstants soapConstants = context.getMessageContext().getSOAPConstants();
      DataHandler dataHandler = new DataHandler(new OctetStreamDataSource("test",
              new OctetStream(bytes)));
      Part attachmentPart = attachments.createAttachmentPart(dataHandler);

      AttributesImpl attrs = new AttributesImpl();
      if (attributes != null && 0 < attributes.getLength())
        attrs.setAttributes(attributes); // copy the existing ones.

      int typeIndex = -1;
      if ((typeIndex = attrs.getIndex(Constants.URI_DEFAULT_SCHEMA_XSI, "type")) != -1) {
        // Found a xsi:type which should not be there for attachments.
        attrs.removeAttribute(typeIndex);
      }

      attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(), "CDATA",
              attachmentPart.getContentIdRef());
      context.startElement(name, attrs);
      context.endElement();
    } else {
      // no attachment support - Base64 encode
      // System.out.println("No attachment support"); //DEBUG
      context.startElement(name, attributes);

      String base64str = Base64.encode(bytes);
      context.writeChars(base64str.toCharArray(), 0, base64str.length());
      context.endElement();
    }

  } else {
    throw new IOException(value.getClass().getName() + " is not serializable.");
  }
}
 
Example #9
Source File: XmlSerializer.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new serializer content handler.
 *
 * @param aContext the a context
 */
SerializerContentHandler(SerializationContext aContext) {
  mContext = aContext;
}
 
Example #10
Source File: XmlSerializer_Axis11.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new serializer content handler.
 *
 * @param aContext the a context
 */
SerializerContentHandler(SerializationContext aContext) {
  mContext = aContext;
}