下面列出了javax.xml.bind.annotation.XmlAttachmentRef#javax.activation.DataHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void uploadResourcesToConfigRegistry() throws Exception {
ResourceAdminServiceClient resourceAdminServiceStub =
new ResourceAdminServiceClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
resourceAdminServiceStub.deleteResource("/_system/config/proxy");
resourceAdminServiceStub.addCollection("/_system/config/", "proxy", "",
"Contains test proxy tests files");
resourceAdminServiceStub.addResource(
"/_system/config/proxy/sample_proxy_1.wsdl", "application/wsdl+xml", "wsdl+xml files",
new DataHandler(new URL("file:///" + getESBResourceLocation() +
"/proxyconfig/proxy/utils/sample_proxy_1.wsdl")));
Thread.sleep(1000);
}
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
//Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
AttachmentSet attSet = context.packet.getMessage().getAttachments();
for (Entry<String, DataHandler> entry : atts.entrySet()) {
String cid = entry.getKey();
Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
attSet.add(att);
}
try {
//SERVER-SIDE
processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);
} catch (WebServiceException wse) {
//no rewrapping
throw wse;
} catch (RuntimeException re) {
throw re;
}
}
@Test(groups = "wso2.esb", description = "Tests for sequence from configuration registry")
public void testConfigurationEndPoint() throws Exception {
URL url =
new URL("file:///" + getESBResourceLocation() + "/mediatorconfig/iterate/iterateEndpoint.xml");
endPointAdminClient.addDynamicEndPoint("conf:/myEndpoint/iterateEndpoint", setEndpoints(new DataHandler(url)));
String response = client.getMultipleResponse(
getProxyServiceURLHttp("iterateWithConfigurationEndpoint"), "WSO2", 2);
Assert.assertNotNull(response);
OMElement envelope = client.toOMElement(response);
OMElement soapBody = envelope.getFirstElement();
Iterator iterator =
soapBody.getChildrenWithName(new QName("http://services.samples",
"getQuoteResponse"));
int i = 0;
while (iterator.hasNext()) {
i++;
OMElement getQuote = (OMElement) iterator.next();
Assert.assertTrue(getQuote.toString().contains("WSO2"));
}
Assert.assertEquals(i, 2, "Child Element count mismatched");
endPointAdminClient.deleteDynamicEndpoint("conf:/myEndpoint/iterateEndpoint");
}
/**
* return the artifact by name and type
* @param token. The token.
* @param user. The user.
* @param name. The artifact's name.
* @param type. The artifact's type.
* @return the content of the artifact.
*/
public DataHandler getArtifactContentByNameAndType(String token,String user, String name, String type){
logger.debug("IN");
Monitor monitor = MonitorFactory
.start("spagobi.service.artifact.getArtifactContentByNameAndType");
try {
validateTicket(token, user);
this.setTenantByUserId(user);
ArtifactServiceImplSupplier supplier = new ArtifactServiceImplSupplier();
return supplier.getArtifactContentByNameAndType(name, type);
} catch (Exception e) {
logger.error("Exception", e);
return null;
} finally {
this.unsetTenant();
monitor.stop();
logger.debug("OUT");
}
}
@SuppressWarnings("resource")
private void writeNonMtomAttachments(AttachmentSet attachments,
OutputStream out, String boundary) throws IOException {
for (Attachment att : attachments) {
DataHandler dh = att.asDataHandler();
if (dh instanceof StreamingDataHandler) {
StreamingDataHandler sdh = (StreamingDataHandler) dh;
// If DataHandler has href Content-ID, it is MTOM, so skip.
if (sdh.getHrefCid() != null)
continue;
}
// build attachment frame
writeln("--" + boundary, out);
writeMimeHeaders(att.getContentType(), att.getContentId(), out);
att.writeTo(out);
writeln(out); // write \r\n
}
}
public void oneWayUploadUsingMTOM(OMElement element) throws Exception {
OMText binaryNode = (OMText) element.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
File tempFile = File.createTempFile("mtom-", ".gif");
FileOutputStream fos = new FileOutputStream(tempFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
byte data[] = new byte[BUFFER];
int count;
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
System.out.println("Wrote to file : " + tempFile.getAbsolutePath());
}
DataHandler getDataHandler() {
DataSource ds = new DataSource() {
public OutputStream getOutputStream() throws IOException {
throw new IOException("Illegal Operation");
}
public String getContentType() {
return getContentTypeString();
}
public String getName() {
return getContentId();
}
public InputStream getInputStream() throws IOException {
return getContentAsStream();
}
};
return new DataHandler(ds);
}
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
DataSource source = new MyByteArrayDataSource(attachment.getContent());
String mimeType = FileTypesHelper.getMIMEType(attachment.getName());
String contentId = attachment.getContentId();
if (contentId == null) {
contentId = generateAttachmentContentId(attachment.getName());
}
String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
String charset = MimeUtility.mimeCharset(attachment.getEncoding() != null ?
attachment.getEncoding() : StandardCharsets.UTF_8.name());
String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, attachment.getName());
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
attachmentPart.setHeader("Content-Type", contentTypeValue);
attachmentPart.setFileName(attachment.getName());
attachmentPart.setDisposition(disposition);
return attachmentPart;
}
@Override
public DataHandler getAttachmentAsDataHandler(String contentId) {
if (contentId.startsWith(CID)) {
contentId = contentId.substring(CID.length());
try {
contentId = URLDecoder.decode(contentId, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
// ignore
}
contentId = '<' + contentId + '>';
}
DataHandler dataHandler = this.mimeContainer.getAttachment(contentId);
if (dataHandler == null) {
throw new IllegalArgumentException("No attachment found for " + contentId);
}
return dataHandler;
}
private void uploadResourcesToConfigRegistry() throws Exception {
ResourceAdminServiceClient resourceAdminServiceStub =
new ResourceAdminServiceClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
resourceAdminServiceStub.deleteResource("/_system/config/proxy");
resourceAdminServiceStub.addCollection("/_system/config/", "proxy", "",
"Contains test proxy tests files");
resourceAdminServiceStub.addResource(
"/_system/config/proxy/sample_proxy_1.wsdl", "application/wsdl+xml", "wsdl+xml files",
new DataHandler(new URL("file:///" + getESBResourceLocation() +
"/proxyconfig/proxy/utils/sample_proxy_1.wsdl")));
Thread.sleep(1000);
}
private void addAttachedFilePart( FileObject file ) throws Exception {
// create a data source
MimeBodyPart files = new MimeBodyPart();
// create a data source
URLDataSource fds = new URLDataSource( file.getURL() );
// get a data Handler to manipulate this file type;
files.setDataHandler( new DataHandler( fds ) );
// include the file in the data source
files.setFileName( file.getName().getBaseName() );
// insist on base64 to preserve line endings
files.addHeader( "Content-Transfer-Encoding", "base64" );
// add the part with the file in the BodyPart();
data.parts.addBodyPart( files );
if ( isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "Mail.Log.AttachedFile", fds.getName() ) );
}
}
/**
* Creates an AttachmentBuilder based on the parameter type
*
* @param param
* runtime Parameter that abstracts the annotated java parameter
* @param setter
* specifies how the obtained value is set into the argument. Takes
* care of Holder arguments.
*/
public static ResponseBuilder createAttachmentBuilder(ParameterImpl param, ValueSetter setter) {
Class type = (Class)param.getTypeInfo().type;
if (DataHandler.class.isAssignableFrom(type)) {
return new DataHandlerBuilder(param, setter);
} else if (byte[].class==type) {
return new ByteArrayBuilder(param, setter);
} else if(Source.class.isAssignableFrom(type)) {
return new SourceBuilder(param, setter);
} else if(Image.class.isAssignableFrom(type)) {
return new ImageBuilder(param, setter);
} else if(InputStream.class==type) {
return new InputStreamBuilder(param, setter);
} else if(isXMLMimeType(param.getBinding().getMimeType())) {
return new JAXBBuilder(param, setter);
} else if(String.class.isAssignableFrom(type)) {
return new StringBuilder(param, setter);
} else {
throw new UnsupportedOperationException("Unexpected Attachment type ="+type);
}
}
private void importDocument(File file, long parentId) throws Exception {
String fileExt = FilenameUtils.getExtension(file.getName());
if (!allowedExtensions.contains(fileExt.toLowerCase()))
return;
DataSource ds = new FileDataSource(file);
DataHandler content = new DataHandler(ds);
WSDocument document = new WSDocument();
document.setFolderId(parentId);
document.setFileName(file.getName());
WSDocument docRes = dclient.create(sid, document, content);
System.out.println("documentID = " + docRes.getId());
}
/**
* Creates an AttachmentBuilder based on the parameter type
*
* @param param
* runtime Parameter that abstracts the annotated java parameter
* @param setter
* specifies how the obtained value is set into the argument. Takes
* care of Holder arguments.
*/
public static EndpointArgumentsBuilder createAttachmentBuilder(ParameterImpl param, EndpointValueSetter setter) {
Class type = (Class)param.getTypeInfo().type;
if (DataHandler.class.isAssignableFrom(type)) {
return new DataHandlerBuilder(param, setter);
} else if (byte[].class==type) {
return new ByteArrayBuilder(param, setter);
} else if(Source.class.isAssignableFrom(type)) {
return new SourceBuilder(param, setter);
} else if(Image.class.isAssignableFrom(type)) {
return new ImageBuilder(param, setter);
} else if(InputStream.class==type) {
return new InputStreamBuilder(param, setter);
} else if(isXMLMimeType(param.getBinding().getMimeType())) {
return new JAXBBuilder(param, setter);
} else if(String.class.isAssignableFrom(type)) {
return new StringBuilder(param, setter);
} else {
throw new UnsupportedOperationException("Unknown Type="+type+" Attachment is not mapped.");
}
}
/**
* Creates an AttachmentBuilder based on the parameter type
*
* @param param
* runtime Parameter that abstracts the annotated java parameter
* @param setter
* specifies how the obtained value is set into the argument. Takes
* care of Holder arguments.
*/
public static EndpointArgumentsBuilder createAttachmentBuilder(ParameterImpl param, EndpointValueSetter setter) {
Class type = (Class)param.getTypeInfo().type;
if (DataHandler.class.isAssignableFrom(type)) {
return new DataHandlerBuilder(param, setter);
} else if (byte[].class==type) {
return new ByteArrayBuilder(param, setter);
} else if(Source.class.isAssignableFrom(type)) {
return new SourceBuilder(param, setter);
} else if(Image.class.isAssignableFrom(type)) {
return new ImageBuilder(param, setter);
} else if(InputStream.class==type) {
return new InputStreamBuilder(param, setter);
} else if(isXMLMimeType(param.getBinding().getMimeType())) {
return new JAXBBuilder(param, setter);
} else if(String.class.isAssignableFrom(type)) {
return new StringBuilder(param, setter);
} else {
throw new UnsupportedOperationException("Unknown Type="+type+" Attachment is not mapped.");
}
}
@POST
@Consumes("multipart/form-data")
public Response addBook(final MultipartBody body) throws Exception {
for (final Attachment attachment: body.getAllAttachments()) {
final DataHandler handler = attachment.getDataHandler();
if (handler != null) {
final String source = handler.getName();
final LuceneDocumentMetadata metadata = new LuceneDocumentMetadata()
.withSource(source)
.withField("modified", Date.class);
final Document document = extractor.extract(handler.getInputStream(), metadata);
if (document != null) {
try (IndexWriter writer = getIndexWriter()) {
writer.addDocument(document);
writer.commit();
}
}
}
}
return Response.ok().build();
}
void callHandlersOnResponse(MessageUpdatableContext context, boolean handleFault) {
//Lets copy all the MessageContext.OUTBOUND_ATTACHMENT_PROPERTY to the message
Map<String, DataHandler> atts = (Map<String, DataHandler>) context.get(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS);
AttachmentSet attSet = context.packet.getMessage().getAttachments();
for (Entry<String, DataHandler> entry : atts.entrySet()) {
String cid = entry.getKey();
Attachment att = new DataHandlerAttachment(cid, atts.get(cid));
attSet.add(att);
}
try {
//SERVER-SIDE
processor.callHandlersResponse(HandlerProcessor.Direction.OUTBOUND, context, handleFault);
} catch (WebServiceException wse) {
//no rewrapping
throw wse;
} catch (RuntimeException re) {
throw re;
}
}
@Override
public UploadMimeResponse uploadMime(String target, String operation, String id, DataHandler fail)
throws XRoadServiceConsumptionException {
UploadMime uploadMimeDocument = UploadMimeDocument.UploadMime.Factory.newInstance();
UploadMimeType request = uploadMimeDocument.addNewRequest();
request.setTarget(target);
request.setOperation(operation);
Props props = request.addNewProps();
Prop prop = props.addNewProp();
prop.setKey(UPLOAD_ID);
prop.setStringValue(id);
XmlBeansXRoadMessage<UploadMimeDocument.UploadMime> XRoadMessage =
new XmlBeansXRoadMessage<UploadMimeDocument.UploadMime>(uploadMimeDocument);
List<XRoadAttachment> attachments = XRoadMessage.getAttachments();
String failCid = AttachmentUtil.getUniqueCid();
request.addNewFile().setHref("cid:" + failCid);
attachments.add(new XRoadAttachment(failCid, fail));
XRoadMessage<UploadMimeResponse> response = send(XRoadMessage, METHOD_UPLOAD_MIME, V1, new TorCallback(), null);
return response.getContent();
}
@Test(groups = "wso2.esb", description = "Tests for sequence from governors registry ")
public void testGovernersSequence() throws Exception {
URL url =
new URL("file:///" + getESBResourceLocation() + "/mediatorconfig/iterate/iterateLogAndSendSequence.xml");
resourceAdminServiceClient.addResource("/_system/governance/sequences/iterate/iterateLogAndSendSequence",
"application/vnd.wso2.sequence", "configuration",
setEndpoints(new DataHandler(url)));
String response = client.getMultipleResponse(
getProxyServiceURLHttp("iterateWithTargetGovernanceTestProxy"), "WSO2",
2);
Assert.assertNotNull(response);
OMElement envelope = client.toOMElement(response);
OMElement soapBody = envelope.getFirstElement();
Iterator iterator =
soapBody.getChildrenWithName(new QName("http://services.samples",
"getQuoteResponse"));
int i = 0;
while (iterator.hasNext()) {
i++;
OMElement getQuote = (OMElement) iterator.next();
Assert.assertTrue(getQuote.toString().contains("WSO2"));
}
Assert.assertEquals(i, 2, "Child Element count mismatched");
resourceAdminServiceClient.deleteResource("/_system/governance/sequences/iterate/iterateLogAndSendSequence");
}
@BeforeClass(alwaysRun = true)
protected void uploadCarFileTest() throws Exception {
//start FTP server
startFTPServer();
super.init();
serverConfigurationManager = new ServerConfigurationManager(context);
//upload CAPP
CarbonAppUploaderClient carbonAppUploaderClient = new CarbonAppUploaderClient(
context.getContextUrls().getBackEndUrl(), sessionCookie);
carbonAppUploaderClient.uploadCarbonAppArtifact(carFileName, new DataHandler(new FileDataSource(
new File(getESBResourceLocation() + File.separator + "car" + File.separator + carFileName))));
log.info(carFileName + " uploaded successfully");
//deactivate proxy service
serviceAdminClient = new ServiceAdminClient(context.getContextUrls().getBackEndUrl(), sessionCookie);
isProxyDeployed(service);
serviceAdminClient.stopService(service);
//Wait and check till the service get deactivated maximum for ~20sec
for (int i = 0; i < 20; i++) {
if (!serviceAdminClient.getServicesData(service).getActive()) {
break;
}
log.info("Wait to service get deactivated");
Thread.sleep(1000);
}
Assert.assertFalse(serviceAdminClient.getServicesData(service).getActive(),
"Unable to stop service: " + service);
serverConfigurationManager.restartGracefully();
super.init();
}
@WebMethod(action = "checkinInitiatedSync")
SLongCheckinActionState checkinInitiatedSync(
@WebParam(name = "topicId", partName = "checkinInitiated.topicId") Long topicId,
@WebParam(name = "poid", partName = "checkinInitiated.poid") Long poid,
@WebParam(name = "comment", partName = "checkinInitiated.comment") String comment,
@WebParam(name = "deserializerOid", partName = "checkinInitiated.deserializerOid") Long deserializerOid,
@WebParam(name = "fileSize", partName = "checkinInitiated.fileSize") Long fileSize,
@WebParam(name = "fileName", partName = "checkinInitiated.fileName") String fileName,
@WebParam(name = "data", partName = "checkinInitiated.data") @XmlMimeType("application/octet-stream") DataHandler data,
@WebParam(name = "merge", partName = "checkinInitiated.merge") Boolean merge) throws ServerException, UserException;
@XmlElementDecl(
namespace = "urn:be:fgov:ehealth:commons:enc:v2",
name = "URI"
)
@XmlAttachmentRef
public JAXBElement<DataHandler> createURI(DataHandler value) {
return new JAXBElement(_URI_QNAME, DataHandler.class, (Class)null, value);
}
/**
* Gets the raw data. If the returned DataHandler is {@link StreamingDataHandler},
* callees may need to downcast to take advantage of its capabilities.
*
* @see StreamingDataHandler
* @return DataHandler for the data
*/
public DataHandler getDataHandler() {
if(dataHandler==null){
dataHandler = new Base64StreamingDataHandler(new Base64DataSource());
} else if (!(dataHandler instanceof StreamingDataHandler)) {
dataHandler = new FilterDataHandler(dataHandler);
}
return dataHandler;
}
public void addExistingConfiguration(DataHandler dh)
throws IOException, LocalEntryAdminException, XMLStreamException {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement configSourceElem = builder.getDocumentElement();
configServiceAdminStub.addExistingConfiguration(configSourceElem.toString());
}
@Test
public void testLargerThanDefaultHeader() throws Exception {
InputStream is1 =
getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
String address = "http://localhost:" + PORT + "/bookstore/books/image";
WebClient client = WebClient.create(address);
client.type("multipart/mixed").accept("multipart/mixed");
WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
"true");
StringBuilder sb = new StringBuilder(64);
sb.append("form-data;");
for (int i = 0; i < 35; i++) {
sb.append("aaaaaaaaaa");
}
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
headers.putSingle("Content-ID", "root");
headers.putSingle("Content-Type", "application/octet-stream");
headers.putSingle("Content-Disposition", sb.toString());
DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream"));
Attachment att = new Attachment(headers, handler, null);
Response response = client.post(att);
assertEquals(response.getStatus(), 200);
client.close();
}
private void uploadResourcesToConfigRegistry() throws Exception {
resourceAdminServiceClient.addCollection("/_system/config/", "test_ep_config", "",
"Contains test Default EP files");
resourceAdminServiceClient.addResource(
"/_system/config/test_ep_config/failoverEP_Test.xml", "application/xml", "xml files",
new DataHandler(new URL("file:///" + getClass().getResource(
"/artifacts/ESB/endpoint/failoverEndpointConfig/failoverEP_Test.xml").getPath())));
Thread.sleep(1000);
}
public static Attachment getAttachment(String id, Collection<Attachment> attachments) {
if (id == null) {
throw new DatabindingException("Cannot get attachment: null id");
}
int i = id.indexOf("cid:");
if (i != -1) {
id = id.substring(4).trim();
}
if (attachments == null) {
return null;
}
for (Iterator<Attachment> iter = attachments.iterator(); iter.hasNext();) {
Attachment a = iter.next();
if (a.getId().equals(id)) {
return a;
}
}
// Try loading the URL remotely
try {
URLDataSource source = new URLDataSource(new URL(id));
return new AttachmentImpl(id, new DataHandler(source));
} catch (MalformedURLException e) {
return null;
}
}
protected String getMessage(MimeMessage mimeMessage) throws MessagingException, IOException {
DataHandler dataHandler = mimeMessage.getDataHandler();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
dataHandler.writeTo(baos);
baos.flush();
return baos.toString();
}
/**
* Saves the specified content to the specified file
*
* @param content The content
* @param outFile The output file
* @throws IOException If an error occurs during saving
*/
static public long saveContentToFile(DataHandler content, File outFile) throws IOException {
long size = 0;
byte[] buffer = new byte[1024];
try (InputStream is = content.getInputStream()) {
try (OutputStream outStream = new FileOutputStream(outFile)) {
for (int readBytes; (readBytes = is.read(buffer, 0, buffer.length)) > 0;) {
size += readBytes;
outStream.write(buffer, 0, readBytes);
}
}
}
return size;
}
@BeforeClass(alwaysRun = true)
public void initialize() throws Exception {
super.init();
String resourceFileLocation;
resourceFileLocation = getResourceLocation();
deployService(serviceName,
new DataHandler(new URL("file:///" + resourceFileLocation +
File.separator + "samples" + File.separator +
"dbs" + File.separator + "web" + File.separator +
"WebResourceSample.dbs")));
log.info(serviceName + " uploaded");
}