下面列出了javax.xml.bind.annotation.XmlAttachmentRef#javax.activation.MimeType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String registerDownloadData( String temporaryFileName, MimeType mimeType, String downloadName, HttpSession session) {
Map<String, FileData> downloadData = getOrCreateDownloadDataMap( session);
// Create a random UUID
UUID uuid = UUID.randomUUID();
// For the very rare possibility of duplicate UUIDs in the map, verify UUID and create new one if necessary
while( downloadData.containsKey( uuid.toString())) {
if( logger.isInfoEnabled())
logger.info( "UUID " + uuid.toString() + " already used - renewing UUID");
uuid = UUID.randomUUID();
}
if( logger.isDebugEnabled()) {
logger.debug( "Registering download data (temp file: " + temporaryFileName + ", MIME type: " + mimeType + ", download name: " + downloadName + ", ID: " + uuid);
}
FileData fileData = new FileData( temporaryFileName, mimeType, downloadName);
downloadData.put( uuid.toString(), fileData);
return uuid.toString();
}
@Deprecated
public static InputStream create(
MimeType type,
String name,
InputStream stream,
UrlRewriter rewriter,
Resolver resolver,
UrlRewriter.Direction direction,
UrlRewriteFilterContentDescriptor config )
throws IOException {
UrlRewriteStreamFilter filter = create(type, name);
String charset = MimeTypes.getCharset( type, StandardCharsets.UTF_8.name() );
final InputStream filteredStream;
if( filter != null ) {
filteredStream = filter.filter( stream, charset, rewriter, resolver, direction, config );
} else {
filteredStream = stream;
}
return filteredStream;
}
private MimeType detect(ByteArrayInputStream copy) {
MimeType mimetype = null;
for (MimeTypeProvider provider : providers) {
try {
LOG.debug("Trying to get mime type from stream using {}", provider);
mimetype = provider.detect(copy);
LOG.debug("{} has detected mime type {} from stream", provider, mimetype);
break;
} catch (MimeTypeDetectionException e) {
// try next one => move read cursor to beginning
copy.reset();
LOG.debug("{} could not detect mime type from stream. Cause: {}", provider, e.getMessage(), e);
}
}
return mimetype;
}
static MimeType calcExpectedMediaType(AnnotationSource primarySource,
ModelBuilder builder ) {
XmlMimeType xmt = primarySource.readAnnotation(XmlMimeType.class);
if(xmt==null)
return null;
try {
return new MimeType(xmt.value());
} catch (MimeTypeParseException e) {
builder.reportError(new IllegalAnnotationException(
Messages.ILLEGAL_MIME_TYPE.format(xmt.value(),e.getMessage()),
xmt
));
return null;
}
}
/**
* Writes a type attribute (if the referenced type is a global type)
* or writes out the definition of the anonymous type in place (if the referenced
* type is not a global type.)
*
* Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
*
* ComplexTypeHost and SimpleTypeHost don't share an api for creating
* and attribute in a type-safe way, so we will compromise for now and
* use _attribute().
*/
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
// ID / IDREF handling
switch(typeRef.getSource().id()) {
case ID:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
return;
case IDREF:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
return;
case NONE:
// no ID/IDREF, so continue on and generate the type
break;
default:
throw new IllegalStateException();
}
// MTOM handling
MimeType mimeType = typeRef.getSource().getExpectedMimeType();
if( mimeType != null ) {
th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
}
// ref:swaRef handling
if(generateSwaRefAdapter(typeRef)) {
th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
return;
}
// type name override
if(typeRef.getSource().getSchemaType()!=null) {
th._attribute(refAttName,typeRef.getSource().getSchemaType());
return;
}
// normal type generation
writeTypeRef(th, typeRef.getTarget(), refAttName);
}
/**
* Match content type against expected type
*/
protected void matchResponseContentType(String expectedType) {
String fullType = getResponseContentType();
if (fullType == null) {
assertNull(expectedType);
} else {
try {
MimeType ctype = new MimeType(fullType);
assertTrue("Types "+fullType+" and "+expectedType+" do not match", ctype.match(expectedType));
} catch (MimeTypeParseException e) {
assertEquals(expectedType, fullType);
}
}
}
public TypeUseImpl(CNonElement itemType, boolean collection, ID id, MimeType expectedMimeType, CAdapter adapter) {
this.coreType = itemType;
this.collection = collection;
this.id = id;
this.expectedMimeType = expectedMimeType;
this.adapter = adapter;
}
@Override
public boolean isMimeTypeWhitelisted(final String mimeTypeString) {
try {
final MimeType mimeType = new MimeType(mimeTypeString);
return isMimeTypeWhitelisted(mimeType);
} catch (MimeTypeParseException e) {
return false;
}
}
/**
* Writes a type attribute (if the referenced type is a global type)
* or writes out the definition of the anonymous type in place (if the referenced
* type is not a global type.)
*
* Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
*
* ComplexTypeHost and SimpleTypeHost don't share an api for creating
* and attribute in a type-safe way, so we will compromise for now and
* use _attribute().
*/
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
// ID / IDREF handling
switch(typeRef.getSource().id()) {
case ID:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
return;
case IDREF:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
return;
case NONE:
// no ID/IDREF, so continue on and generate the type
break;
default:
throw new IllegalStateException();
}
// MTOM handling
MimeType mimeType = typeRef.getSource().getExpectedMimeType();
if( mimeType != null ) {
th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
}
// ref:swaRef handling
if(generateSwaRefAdapter(typeRef)) {
th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
return;
}
// type name override
if(typeRef.getSource().getSchemaType()!=null) {
th._attribute(refAttName,typeRef.getSource().getSchemaType());
return;
}
// normal type generation
writeTypeRef(th, typeRef.getTarget(), refAttName);
}
@Before
public void setup() throws MimeTypeDetectionException, MimeTypeParseException {
when(mimeTypeProvider.detect(any(InputStream.class))).thenReturn(new MimeType("image/gif"));
SequentialIdGenerator idGenerator = new SequentialIdGenerator();
ImageInliner inliner = new EveryImageInliner(
new JsoupAttachImageInliner(idGenerator),
new JsoupBase64ImageInliner(),
new RegexAttachBackgroudImageInliner(idGenerator),
new RegexBase64BackgroundImageInliner());
Map<String, List<String>> lookups = new HashMap<>();
lookups.put("classpath", asList("classpath:", ""));
RelativePathResolver relativePathResolver = new LookupAwareRelativePathResolver(lookups);
ResourceResolver resourceResolver = new RelativeResolver(new ClassPathResolver("classpath:", ""), SOURCE_FOLDER);
translator = new InlineImageTranslator(inliner, resourceResolver, mimeTypeProvider, relativePathResolver);
}
private static MimeType defaultMimeType() {
try {
return new MimeType("application", "json");
} catch (MimeTypeParseException o_O) {
throw new IllegalArgumentException(o_O);
}
}
@Override
public MimeType getMimeType(File file) throws MimeTypeDetectionException {
for (MimeTypeProvider provider : providers) {
try {
LOG.debug("Trying to get mime type for file {} using {}", file, provider);
MimeType mimetype = provider.getMimeType(file);
LOG.debug("{} has detected mime type {} for file {}", provider, mimetype, file);
return mimetype;
} catch (MimeTypeDetectionException e) {
// nothing to do => try next one
LOG.debug("{} could not detect mime type for file {}. Cause: {}", provider, file, e.getMessage(), e);
}
}
throw new NoMimetypeDetectorException("No mimetype provider could provide the mimetype for the file " + file);
}
@Override
public CharSequence print(V o) throws AccessorException {
XMLSerializer w = XMLSerializer.getInstance();
MimeType old = w.setExpectedMimeType(expectedMimeType);
try {
return core.print(o);
} finally {
w.setExpectedMimeType(old);
}
}
@Override
public void writeText(XMLSerializer w, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
MimeType old = w.setExpectedMimeType(expectedMimeType);
try {
core.writeText(w, o, fieldName);
} finally {
w.setExpectedMimeType(old);
}
}
public DataSourceSource(DataSource source) throws MimeTypeParseException {
this.source = source;
String ct = source.getContentType();
if(ct==null) {
charset = null;
} else {
MimeType mimeType = new MimeType(ct);
this.charset = mimeType.getParameter("charset");
}
}
public CElementPropertyInfo(String name, CollectionMode collection, ID id, MimeType expectedMimeType, XSComponent source,
CCustomizations customizations, Locator locator, boolean required) {
super(name, collection.col, source, customizations, locator);
this.required = required;
this.id = id;
this.expectedMimeType = expectedMimeType;
this.isValueList = collection.val;
}
@Test
public void happyCase() throws Exception {
final byte[] bytes = "{\"foo\": \"bar\"}".getBytes(Charset.forName("UTF-8"));
final Blob newAttachment = new Blob("myfile.json", new MimeType("application/json"), bytes);
// when
wrap(toDoItem).setAttachment(newAttachment);
// then
assertThat(wrap(toDoItem).getAttachment()).isEqualTo(newAttachment);
}
/**
* Writes a type attribute (if the referenced type is a global type)
* or writes out the definition of the anonymous type in place (if the referenced
* type is not a global type.)
*
* Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
*
* ComplexTypeHost and SimpleTypeHost don't share an api for creating
* and attribute in a type-safe way, so we will compromise for now and
* use _attribute().
*/
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
// ID / IDREF handling
switch(typeRef.getSource().id()) {
case ID:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
return;
case IDREF:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
return;
case NONE:
// no ID/IDREF, so continue on and generate the type
break;
default:
throw new IllegalStateException();
}
// MTOM handling
MimeType mimeType = typeRef.getSource().getExpectedMimeType();
if( mimeType != null ) {
th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
}
// ref:swaRef handling
if(generateSwaRefAdapter(typeRef)) {
th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
return;
}
// type name override
if(typeRef.getSource().getSchemaType()!=null) {
th._attribute(refAttName,typeRef.getSource().getSchemaType());
return;
}
// normal type generation
writeTypeRef(th, typeRef.getTarget(), refAttName);
}
@Override
public Entity transform(HttpRequestEntity entity) throws IOException {
logMessage(entity.getRequest());
final HttpRequestEntity request = cast(entity);
final ImmutablePair<MimeType, Properties> options = exporterOptions(request);
options.right.putAll(transformerConfig);
final File input = downloadInput(entity);
final File output = File.createTempFile("reply", "tmp");
final ITransformEngine engine = getEngine();
return new WritingEntity() {
@Override
public void writeData(OutputStream out) throws IOException {
try {
// Can't allow more than one transform at a time as OpenRefine is not
// designed for that.
synchronized (SynchronousTransformer.this) {
engine.transform(input.toURI(), fetchTransform(request), output.toURI(),
options.right);
}
try (FileInputStream stream = new FileInputStream(output)) {
IOUtils.copy(stream, out);
}
} finally {
input.delete();
output.delete();
}
}
@Override
public MimeType getType() {
return options.left;
}
};
}
/**
* Writes a type attribute (if the referenced type is a global type)
* or writes out the definition of the anonymous type in place (if the referenced
* type is not a global type.)
*
* Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
*
* ComplexTypeHost and SimpleTypeHost don't share an api for creating
* and attribute in a type-safe way, so we will compromise for now and
* use _attribute().
*/
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
// ID / IDREF handling
switch(typeRef.getSource().id()) {
case ID:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
return;
case IDREF:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
return;
case NONE:
// no ID/IDREF, so continue on and generate the type
break;
default:
throw new IllegalStateException();
}
// MTOM handling
MimeType mimeType = typeRef.getSource().getExpectedMimeType();
if( mimeType != null ) {
th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
}
// ref:swaRef handling
if(generateSwaRefAdapter(typeRef)) {
th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
return;
}
// type name override
if(typeRef.getSource().getSchemaType()!=null) {
th._attribute(refAttName,typeRef.getSource().getSchemaType());
return;
}
// normal type generation
writeTypeRef(th, typeRef.getTarget(), refAttName);
}
public TypeUseImpl(CNonElement itemType, boolean collection, ID id, MimeType expectedMimeType, CAdapter adapter) {
this.coreType = itemType;
this.collection = collection;
this.id = id;
this.expectedMimeType = expectedMimeType;
this.adapter = adapter;
}
@Override
public void writeLeafElement(XMLSerializer w, Name tagName, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
MimeType old = w.setExpectedMimeType(expectedMimeType);
try {
core.writeLeafElement(w, tagName, o, fieldName);
} finally {
w.setExpectedMimeType(old);
}
}
public MimeType getExpectedMimeType() {
for( Ref t : refs ) {
MimeType mt = t.getExpectedMimeType();
if(mt!=null) return mt;
}
return null;
}
@Override
public void writeLeafElement(XMLSerializer w, Name tagName, V o, String fieldName) throws IOException, SAXException, XMLStreamException, AccessorException {
MimeType old = w.setExpectedMimeType(expectedMimeType);
try {
core.writeLeafElement(w, tagName, o, fieldName);
} finally {
w.setExpectedMimeType(old);
}
}
public MimeType getExpectedMimeType() {
for( Ref t : refs ) {
MimeType mt = t.getExpectedMimeType();
if(mt!=null) return mt;
}
return null;
}
public MimeType getExpectedMimeType() {
for( Ref t : refs ) {
MimeType mt = t.getExpectedMimeType();
if(mt!=null) return mt;
}
return null;
}
@Test
public void testTransform() throws Exception {
File reference = findAndCopy("outputs/" + fInput + "_" + fTransform
+ "." + fFormat);
MimeType mime = mapContentType(fFormat);
Response response = doRequest(fInput, fTransform, fFormat, mime);
File output = EngineTestUtils
.toFile(response.getBody().asInputStream());
assertEquals(reference, output, mime);
}
/**
* Writes a type attribute (if the referenced type is a global type)
* or writes out the definition of the anonymous type in place (if the referenced
* type is not a global type.)
*
* Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref
*
* ComplexTypeHost and SimpleTypeHost don't share an api for creating
* and attribute in a type-safe way, so we will compromise for now and
* use _attribute().
*/
private void writeTypeRef(TypeHost th, NonElementRef<T, C> typeRef, String refAttName) {
// ID / IDREF handling
switch(typeRef.getSource().id()) {
case ID:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID"));
return;
case IDREF:
th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF"));
return;
case NONE:
// no ID/IDREF, so continue on and generate the type
break;
default:
throw new IllegalStateException();
}
// MTOM handling
MimeType mimeType = typeRef.getSource().getExpectedMimeType();
if( mimeType != null ) {
th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString());
}
// ref:swaRef handling
if(generateSwaRefAdapter(typeRef)) {
th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref"));
return;
}
// type name override
if(typeRef.getSource().getSchemaType()!=null) {
th._attribute(refAttName,typeRef.getSource().getSchemaType());
return;
}
// normal type generation
writeTypeRef(th, typeRef.getTarget(), refAttName);
}
private MimeTypeProvider validateProvider(MimeTypeProvider provider) {
String[] allowed = allowedMimetypesValueBuilder.getValue(new String[0]);
if (allowed.length <= 0) {
// no validation
return provider;
}
Predicate<MimeType> merged = m -> true;
for (int i=0 ; i<allowed.length ; i++) {
Predicate<MimeType> predicate = toPredicate(allowed[i]);
merged = merged.and(predicate);
}
return new AllowedMimetypeDecorator(merged, provider);
}
private Response doRequest(String input, String transform, String format,
MimeType contentType) throws Exception {
String transformURI = fServers.transformURI(input + "-" + transform + ".json").toString();
Response response = RestAssured.given()
.queryParam("refinejson", transformURI)
.header("Accept", contentType.toString() + ";q=1.0")
.contentType("text/csv")
.content(contentsAsBytes("inputs", input, "csv"))
.when().post();
Assert.assertEquals(HttpStatus.SC_ACCEPTED, response.getStatusCode());
String location = response.getHeader("location");
Assert.assertTrue(location != null);
/* Polls until ready. */
long start = System.currentTimeMillis();
do {
response = RestAssured.given()
.header("Accept", "text/turtle")
.header("Content-Type", "text/turtle")
.when().get(location);
if (System.currentTimeMillis() - start >= ASYNC_TIMEOUT) {
Assert.fail("Asynchronous call timed out.");
}
Thread.sleep(100);
} while (response.statusCode() == HttpStatus.SC_ACCEPTED);
return response;
}