下面列出了javax.ws.rs.core.MediaType#APPLICATION_OCTET_STREAM_TYPE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Invokes an HTTP request to append to target file upload on target site.
*
* @param credential
* the credential containing the authentication token to use for
* this request
* @param siteId
* the ID of the target site
* @param uploadSessionId
* the session ID of the target file upload
* @param chunk
* the chunk of data to append to target file upload
* @param numChunkBytes
* the number of bytes in the chunk of data
*/
private void invokeAppendFileUpload(TableauCredentialsType credential, String siteId, String uploadSessionId,
byte[] chunk, int numChunkBytes) {
m_logger.info(String.format("Appending to file upload '%s'.", uploadSessionId));
String url = Operation.APPEND_FILE_UPLOAD.getUrl(siteId, uploadSessionId);
// Writes the chunk of data to a temporary file
try (FileOutputStream outputStream = new FileOutputStream("appendFileUpload.temp")) {
outputStream.write(chunk, 0, numChunkBytes);
} catch (IOException e) {
throw new IllegalStateException("Failed to create temporary file to append to file upload");
}
// Makes a multipart PUT request with specified credential's
// authenticity token and payload
BodyPart filePart = new FileDataBodyPart("tableau_file", new File("appendFileUpload.temp"),
MediaType.APPLICATION_OCTET_STREAM_TYPE);
putMultipart(url, credential.getToken(), null, filePart);
}
/**
* Invokes an HTTP request to publish a workbook to target site including
* the workbook in the request.
*
* @param credential
* the credential containing the authentication token to use for
* this request
* @param siteId
* the ID of the target site
* @param requestPayload
* the XML payload containing the workbook attributes used to
* publish the workbook
* @param workbookFile
* the workbook file to publish
* @return the workbook if it was published successfully, otherwise
* <code>null</code>
*/
private WorkbookType invokePublishWorkbookSimple(TableauCredentialsType credential, String siteId,
String projectId, String workbookName, File workbookFile) {
String url = Operation.PUBLISH_WORKBOOK.getUrl(siteId);
// Creates the payload to publish the workbook
TsRequest payload = createPayloadToPublishWorkbook(workbookName, projectId);
// Makes a multipart POST request with specified credential's
// authenticity token and payload
BodyPart filePart = new FileDataBodyPart("tableau_workbook", workbookFile,
MediaType.APPLICATION_OCTET_STREAM_TYPE);
TsResponse response = postMultipart(url, credential.getToken(), payload, filePart);
// Verifies that the response has a workbook element
if (response.getWorkbook() != null) {
m_logger.info("Publish workbook is successful!");
return response.getWorkbook();
}
// No workbook was published
return null;
}
private MediaType checkFinalContentType(MediaType mt, List<WriterInterceptor> writers, boolean checkWriters) {
if (checkWriters) {
int mbwIndex = writers.size() == 1 ? 0 : writers.size() - 1;
MessageBodyWriter<Object> writer = ((WriterInterceptorMBW)writers.get(mbwIndex)).getMBW();
Produces pm = writer.getClass().getAnnotation(Produces.class);
if (pm != null) {
List<MediaType> sorted =
JAXRSUtils.sortMediaTypes(JAXRSUtils.getMediaTypes(pm.value()), JAXRSUtils.MEDIA_TYPE_QS_PARAM);
mt = JAXRSUtils.intersectMimeTypes(sorted, mt).get(0);
}
}
if (mt.isWildcardType() || mt.isWildcardSubtype()) {
if ("application".equals(mt.getType()) || mt.isWildcardType()) {
mt = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else {
throw ExceptionUtils.toNotAcceptableException(null, null);
}
}
return mt;
}
static void testStoreResults( TestParams testParams ) throws Exception {
FormDataMultiPart part = new FormDataMultiPart();
File tmpFile = File.createTempFile("results", "tmp");
FileInputStream in = new FileInputStream( tmpFile );
FormDataBodyPart body = new FormDataBodyPart( RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
part.bodyPart( body );
ClientResponse response = testParams.addQueryParameters( QUERY_PARAMS )
.setEndpoint( RunManagerResource.ENDPOINT )
.newWebResource()
.queryParam( RestParams.RUNNER_HOSTNAME, "localhost" )
.queryParam( RestParams.RUN_ID, "112316437" )
.queryParam( RestParams.RUN_NUMBER, "3" )
.path( "/store" )
.type( MediaType.MULTIPART_FORM_DATA_TYPE )
.accept( MediaType.APPLICATION_JSON )
.post( ClientResponse.class, part );
tmpFile.delete();
assertEquals( Response.Status.CREATED.getStatusCode(), response.getStatus() );
assertEquals( UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity( String.class ) );
}
@Override
public void store( final Project project, final Summary summary, final File resultsFile,
final Class<?> testClass ) throws FileNotFoundException, MalformedURLException {
Preconditions.checkNotNull( summary, "The summary argument cannot be null." );
// upload the results file
InputStream in = new FileInputStream( resultsFile );
FormDataMultiPart part = new FormDataMultiPart();
part.field( FILENAME, resultsFile.getName() );
FormDataBodyPart body = new FormDataBodyPart( CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
part.bodyPart( body );
WebResource resource = Client.create().resource( coordinatorFig.getEndpoint() );
resource = addQueryParameters( resource, project, me );
String result = resource.path( coordinatorFig.getStoreResultsPath() )
.queryParam( RUN_ID, summary.getRunId() )
.queryParam( RUN_NUMBER, "" + summary.getRunNumber() )
.type( MediaType.MULTIPART_FORM_DATA_TYPE )
.post( String.class, part );
LOG.debug( "Got back result from results file store = {}", result );
}
public static MediaType parseMediaType(String extension) {
// FIXME: bigger list, and override in config
if(extension.equalsIgnoreCase("html"))
return MediaType.TEXT_HTML_TYPE;
if(extension.equalsIgnoreCase("xml"))
return MediaType.APPLICATION_XML_TYPE;
if(extension.equalsIgnoreCase("txt"))
return MediaType.TEXT_PLAIN_TYPE;
if(extension.equalsIgnoreCase("json"))
return MediaType.APPLICATION_JSON_TYPE;
System.err.println("Unknown extension type: "+extension);
return MediaType.APPLICATION_OCTET_STREAM_TYPE;
}
public static MediaType parseMediaType(String templatePath, String templateExtension) {
int lastSlash = templatePath.lastIndexOf('/');
String templateName;
if(lastSlash != -1)
templateName = templatePath.substring(lastSlash+1);
else
templateName = templatePath;
if(templateName.endsWith(templateExtension))
templateName = templateName.substring(0, templateName.length()-templateExtension.length());
int lastDot = templateName.lastIndexOf('.');
if(lastDot != -1)
return parseMediaType(templateName.substring(lastDot+1));
// no extension
return MediaType.APPLICATION_OCTET_STREAM_TYPE;
}
public void shouldNotUploadApiMediaBecauseWrongMediaType() {
StreamDataBodyPart filePart = new StreamDataBodyPart("file",
this.getClass().getResourceAsStream("/media/logo.svg"), "logo.svg", MediaType.APPLICATION_OCTET_STREAM_TYPE);
final MultiPart multiPart = new MultiPart(MediaType.MULTIPART_FORM_DATA_TYPE);
multiPart.bodyPart(filePart);
final Response response = target(API + "/media/upload").request().post(entity(multiPart, multiPart.getMediaType()));
assertEquals(BAD_REQUEST_400, response.getStatus());
final String message = response.readEntity(String.class);
assertTrue(message, message.contains("File format unauthorized"));
}
public Builder detectMediaType() {
mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
if (fileName != null) {
String type = MimeType.getByFilename(fileName);
if (type != null) {
mediaType = MediaType.valueOf(type);
}
}
return this;
}
static void testUpload(TestParams testParams) throws Exception {
FormDataMultiPart part = new FormDataMultiPart();
part.field( RestParams.COMMIT_ID, QUERY_PARAMS.get( RestParams.COMMIT_ID ) );
part.field( RestParams.MODULE_GROUPID, QUERY_PARAMS.get( RestParams.MODULE_GROUPID ) );
part.field( RestParams.MODULE_ARTIFACTID, QUERY_PARAMS.get( RestParams.MODULE_ARTIFACTID ) );
part.field( RestParams.MODULE_VERSION, QUERY_PARAMS.get( RestParams.MODULE_VERSION ) );
part.field( RestParams.USERNAME, QUERY_PARAMS.get( RestParams.USERNAME ) );
part.field( RestParams.VCS_REPO_URL, "ssh://[email protected]:7999/chop/main.git" );
part.field( RestParams.TEST_PACKAGE, QUERY_PARAMS.get( RestParams.TEST_PACKAGE ) );
part.field( RestParams.MD5, "d7d4829506f6cb8c0ab2da9cb1daca02" );
File tmpFile = File.createTempFile("runner", "jar");
FileInputStream in = new FileInputStream( tmpFile );
FormDataBodyPart body = new FormDataBodyPart( RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
part.bodyPart( body );
ClientResponse response = testParams.addQueryParameters( QUERY_PARAMS )
.setEndpoint( UploadResource.ENDPOINT )
.newWebResource()
.path( "/runner" )
.type( MediaType.MULTIPART_FORM_DATA )
.accept( MediaType.TEXT_PLAIN )
.post( ClientResponse.class, part );
assertEquals( Response.Status.CREATED.getStatusCode(), response.getStatus() );
assertEquals( UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity( String.class ) );
tmpFile.delete();
}
public boolean init() {
if ( super.init() ) {
data.resultFieldName = environmentSubstitute( meta.getFieldName() );
data.resultCodeFieldName = environmentSubstitute( meta.getResultCodeFieldName() );
data.resultResponseFieldName = environmentSubstitute( meta.getResponseTimeFieldName() );
data.resultHeaderFieldName = environmentSubstitute( meta.getResponseHeaderFieldName() );
// get authentication settings once
data.realProxyHost = environmentSubstitute( meta.getProxyHost() );
data.realProxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 );
data.realHttpLogin = environmentSubstitute( meta.getHttpLogin() );
data.realHttpPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) );
if ( !meta.isDynamicMethod() ) {
data.method = environmentSubstitute( meta.getMethod() );
if ( Utils.isEmpty( data.method ) ) {
logError( BaseMessages.getString( PKG, "Rest.Error.MethodMissing" ) );
return false;
}
}
data.trustStoreFile = environmentSubstitute( meta.getTrustStoreFile() );
data.trustStorePassword = environmentSubstitute( meta.getTrustStorePassword() );
String applicationType = Const.NVL( meta.getApplicationType(), "" );
if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XML ) ) {
data.mediaType = MediaType.APPLICATION_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_JSON ) ) {
data.mediaType = MediaType.APPLICATION_JSON_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_OCTET_STREAM ) ) {
data.mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XHTML ) ) {
data.mediaType = MediaType.APPLICATION_XHTML_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_FORM_URLENCODED ) ) {
data.mediaType = MediaType.APPLICATION_FORM_URLENCODED_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_ATOM_XML ) ) {
data.mediaType = MediaType.APPLICATION_ATOM_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_SVG_XML ) ) {
data.mediaType = MediaType.APPLICATION_SVG_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_TEXT_XML ) ) {
data.mediaType = MediaType.TEXT_XML_TYPE;
} else {
data.mediaType = MediaType.TEXT_PLAIN_TYPE;
}
try {
setConfig();
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "Rest.Error.Config" ), e );
return false;
}
return true;
}
return false;
}
@Test
public void testDatastreamEditorWriteReference_External() throws Exception {
LocalStorage storage = new LocalStorage();
LocalObject local = storage.create();
local.setLabel(test.getMethodName());
String dsID = "dsID";
MediaType mime = MediaType.TEXT_PLAIN_TYPE;
String label = "label";
DatastreamProfile dsProfile = FoxmlUtils.externalProfile(dsID, mime, label);
RemoteStorage fedora = new RemoteStorage(client);
fedora.ingest(local, support.getTestUser());
// prepare referenced contents
byte[] data = "data".getBytes("UTF-8");
File file = tmp.newFile();
FileUtils.writeByteArrayToFile(file, data);
RemoteObject remote = fedora.find(local.getPid());
XmlStreamEditor reditor = remote.getEditor(dsProfile);
assertNotNull(reditor);
reditor.write(file.toURI(), reditor.getLastModified(), "add");
// test read cached
InputStream is = reditor.readStream();
assertNotNull(is);
ByteArrayOutputStream resultData = new ByteArrayOutputStream();
FoxmlUtils.copy(is, resultData);
is.close();
assertArrayEquals(data, resultData.toByteArray());
assertEquals(mime.toString(), reditor.getProfile().getDsMIME());
assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
// test remote read
remote.flush();
remote = fedora.find(local.getPid());
reditor = remote.getEditor(dsProfile);
is = reditor.readStream();
assertNotNull(is);
resultData = new ByteArrayOutputStream();
FoxmlUtils.copy(is, resultData);
is.close();
assertArrayEquals(data, resultData.toByteArray());
assertEquals(mime.toString(), reditor.getProfile().getDsMIME());
assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
// test update MIME + location
MediaType mime2 = MediaType.APPLICATION_OCTET_STREAM_TYPE;
byte[] data2 = "data2".getBytes("UTF-8");
File file2 = tmp.newFile();
FileUtils.writeByteArrayToFile(file2, data2);
remote = fedora.find(local.getPid());
reditor = remote.getEditor(dsProfile);
DatastreamProfile dsProfile2 = FoxmlUtils.externalProfile(dsID, mime2, label);
reditor.setProfile(dsProfile2);
reditor.write(file2.toURI(), reditor.getLastModified(), "update");
remote.flush();
remote = fedora.find(local.getPid());
reditor = remote.getEditor(dsProfile);
is = reditor.readStream();
assertNotNull(is);
resultData = new ByteArrayOutputStream();
FoxmlUtils.copy(is, resultData);
is.close();
assertArrayEquals(data2, resultData.toByteArray());
assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
}
@Test
public void testDatastreamEditorRewriteControlGroup() throws Exception {
// prepare referenced contents
byte[] data1 = "data1".getBytes("UTF-8");
File file1 = tmp.newFile();
FileUtils.writeByteArrayToFile(file1, data1);
byte[] data2 = "data2".getBytes("UTF-8");
File file2 = tmp.newFile();
FileUtils.writeByteArrayToFile(file2, data2);
LocalStorage storage = new LocalStorage();
LocalObject local = storage.create();
System.out.println(local.getPid());
local.setLabel(test.getMethodName());
String dsID = "dsID";
String label = "label";
MediaType mime1 = MediaType.APPLICATION_OCTET_STREAM_TYPE;
DatastreamProfile dsProfile1 = FoxmlUtils.managedProfile(dsID, mime1, label);
XmlStreamEditor leditor = local.getEditor(dsProfile1);
assertNotNull(leditor);
leditor.write(file1.toURI(), leditor.getLastModified(), null);
local.flush();
RemoteStorage fedora = new RemoteStorage(client);
fedora.ingest(local, support.getTestUser());
MediaType mime2 = MediaType.TEXT_PLAIN_TYPE;
DatastreamProfile dsProfile2 = FoxmlUtils.externalProfile(dsID, mime2, label);
RemoteObject remote = fedora.find(local.getPid());
XmlStreamEditor reditor = remote.getEditor(dsProfile1);
assertNotNull(reditor);
reditor.setProfile(dsProfile2);
reditor.write(file2.toURI(), reditor.getLastModified(), null);
// test read cached
InputStream is = reditor.readStream();
assertNotNull(is);
ByteArrayOutputStream resultData = new ByteArrayOutputStream();
FoxmlUtils.copy(is, resultData);
is.close();
assertArrayEquals(data2, resultData.toByteArray());
assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
// test remote read
remote.flush();
remote = fedora.find(local.getPid());
reditor = remote.getEditor(dsProfile1);
is = reditor.readStream();
assertNotNull(is);
resultData = new ByteArrayOutputStream();
FoxmlUtils.copy(is, resultData);
is.close();
assertArrayEquals(data2, resultData.toByteArray());
assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
}
@SuppressWarnings("PMD.CloseResource") // PMD does not understand Closer.
private boolean debugPost(FileWriter outWriter, List<String> options, List<String> parameters) {
if (!isValidArgument(options, parameters, 2, 2, 2, Command.DEBUG_POST)) {
return false;
}
boolean file = false;
boolean raw = false;
for (String option : options) {
switch (option) {
case "-file":
file = true;
break;
case "-raw":
raw = true;
break;
default:
_logger.errorf("Unknown option: %s\n", options.get(0));
printUsage(Command.DEBUG_POST);
return false;
}
}
String urlTail = parameters.get(0);
String entityParam = parameters.get(1);
MediaType mediaType;
Object entity;
try (Closer closer = Closer.create()) {
if (file) {
InputStream inputStream = closer.register(Files.newInputStream(Paths.get(entityParam)));
if (raw) {
mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
entity = inputStream;
} else {
mediaType = MediaType.APPLICATION_JSON_TYPE;
entity = IOUtils.toString(inputStream, UTF_8);
}
} else {
mediaType = MediaType.APPLICATION_JSON_TYPE;
entity = BatfishObjectMapper.mapper().readTree(entityParam);
}
return _workHelper.debugV2(outWriter, HttpMethod.POST, urlTail, entity, mediaType);
} catch (IOException e) {
_logger.error(Throwables.getStackTraceAsString(e));
return false;
}
}
@SuppressWarnings("PMD.CloseResource") // PMD does not understand Closer.
private boolean debugPut(FileWriter outWriter, List<String> options, List<String> parameters) {
if (!isValidArgument(options, parameters, 2, 2, 2, Command.DEBUG_PUT)) {
return false;
}
boolean file = false;
boolean raw = false;
for (String option : options) {
switch (option) {
case "-file":
file = true;
break;
case "-raw":
raw = true;
break;
default:
_logger.errorf("Unknown option: %s\n", options.get(0));
printUsage(Command.DEBUG_PUT);
return false;
}
}
String urlTail = parameters.get(0);
String entityParam = parameters.get(1);
MediaType mediaType;
Object entity;
try (Closer closer = Closer.create()) {
if (file) {
InputStream inputStream = closer.register(Files.newInputStream(Paths.get(entityParam)));
if (raw) {
mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
entity = inputStream;
} else {
mediaType = MediaType.APPLICATION_JSON_TYPE;
entity = IOUtils.toString(inputStream, UTF_8);
}
} else {
mediaType = MediaType.APPLICATION_JSON_TYPE;
entity = BatfishObjectMapper.mapper().readTree(entityParam);
}
return _workHelper.debugV2(outWriter, HttpMethod.PUT, urlTail, entity, mediaType);
} catch (IOException e) {
_logger.error(Throwables.getStackTraceAsString(e));
return false;
}
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (RestMeta) smi;
data = (RestData) sdi;
if ( super.init( smi, sdi ) ) {
data.resultFieldName = environmentSubstitute( meta.getFieldName() );
data.resultCodeFieldName = environmentSubstitute( meta.getResultCodeFieldName() );
data.resultResponseFieldName = environmentSubstitute( meta.getResponseTimeFieldName() );
data.resultHeaderFieldName = environmentSubstitute( meta.getResponseHeaderFieldName() );
// get authentication settings once
data.realProxyHost = environmentSubstitute( meta.getProxyHost() );
data.realProxyPort = Const.toInt( environmentSubstitute( meta.getProxyPort() ), 8080 );
data.realHttpLogin = environmentSubstitute( meta.getHttpLogin() );
data.realHttpPassword = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( meta.getHttpPassword() ) );
if ( !meta.isDynamicMethod() ) {
data.method = environmentSubstitute( meta.getMethod() );
if ( Utils.isEmpty( data.method ) ) {
logError( BaseMessages.getString( PKG, "Rest.Error.MethodMissing" ) );
return false;
}
}
data.trustStoreFile = environmentSubstitute( meta.getTrustStoreFile() );
data.trustStorePassword = environmentSubstitute( meta.getTrustStorePassword() );
String applicationType = Const.NVL( meta.getApplicationType(), "" );
if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XML ) ) {
data.mediaType = MediaType.APPLICATION_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_JSON ) ) {
data.mediaType = MediaType.APPLICATION_JSON_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_OCTET_STREAM ) ) {
data.mediaType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_XHTML ) ) {
data.mediaType = MediaType.APPLICATION_XHTML_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_FORM_URLENCODED ) ) {
data.mediaType = MediaType.APPLICATION_FORM_URLENCODED_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_ATOM_XML ) ) {
data.mediaType = MediaType.APPLICATION_ATOM_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_SVG_XML ) ) {
data.mediaType = MediaType.APPLICATION_SVG_XML_TYPE;
} else if ( applicationType.equals( RestMeta.APPLICATION_TYPE_TEXT_XML ) ) {
data.mediaType = MediaType.TEXT_XML_TYPE;
} else {
data.mediaType = MediaType.TEXT_PLAIN_TYPE;
}
try {
setConfig();
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "Rest.Error.Config" ), e );
return false;
}
return true;
}
return false;
}