JAX-RS 2.0 MULTIPART_FORM_DATA file upload not library specific - jax-rs

I need to create a JAX-RS 2.0 client that posts a file and a couple of parameters using MULTIPART_FORM_DATA content type. (Don't need the service, just the client) I’ve seen some examples that depend on an specific implementation, like Jersey or RESTEasy, but I’d like not to bind my code to any... in particular, to Apache CXF (I am using WAS Liberty Profile). Any ideas on how to do it? Do I have to stick to some specific classes? If so, how can I do it using Apache CXF 3.0 (Liberty uses CXF for JAX-RS 2.0)
Thanks

[I currently cannot comment under the already written answer]
If someone is searching for the maven dependency of IMultipartBody from the answer of Anatoly:
<dependency>
<groupId>com.ibm.websphere.appserver.api</groupId>
<artifactId>com.ibm.websphere.appserver.api.jaxrs20</artifactId>
<version>1.0.39</version>
<scope>provided</scope>
</dependency>
Thanks to andymc12 from https://github.com/OpenLiberty/open-liberty/issues/11942#issuecomment-619996093

You can use this example how to implement it by using jax-rs 2.0 feature: https://www.ibm.com/support/knowledgecenter/SSD28V_8.5.5/com.ibm.websphere.wlp.nd.doc/ae/twlp_jaxrs_multipart_formdata_from_html.html this is almost working example (some statements should be wrapped in try-catch block, but you'll see when'll post it to IDE.
package com.example.jaxrs;
#POST
#Consumes("multipart/form-data")
#Produces("multipart/form-data")
public Response postFormData(IMultipartBody multipartBody) {
List <IAttachment> attachments = multipartBody.getAllAttachments();
String formElementValue = null;
InputStream stream = null;
for (Iterator<IAttachment> it = attachments.iterator(); it.hasNext();) {
IAttachment attachment = it.next();
if (attachment == null) {
continue;
}
DataHandler dataHandler = attachment.getDataHandler();
stream = dataHandler.getInputStream();
MultivaluedMap<String, String> map = attachment.getHeaders();
String fileName = null;
String formElementName = null;
String[] contentDisposition = map.getFirst("Content-Disposition").split(";");
for (String tempName : contentDisposition) {
String[] names = tempName.split("=");
formElementName = names[1].trim().replaceAll("\"", "");
if ((tempName.trim().startsWith("filename"))) {
fileName = formElementName;
}
}
if (fileName == null) {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
formElementValue = sb.toString();
System.out.println(formElementName + ":" + formElementValue);
} else {
//handle the file as you want
File tempFile = new File(fileName);
...
}
}
if (stream != null) {
stream.close();
}
return Response.ok("test").build();
}

Related

RallyApi in Java - Trying to return project hierarchy for a feature

Given a Feature result set passed into this function, I am trying to traverse up the project hierarchy up to the subscription. I can't I get a null pointer on the projResponse =... No even sure of the approach for this.
private static void getProjHierarchyForFeature(RallyRestApi restApi, QueryResponse featureSet,
Time2Market time2market, Integer featureInSet) {
String tempHierarchy = "";
JsonArray tempFeatures = featureSet.getResults();
//time2market.setProjectName(projectName);
try {
JsonObject obj1 = tempFeatures.get(featureInSet).getAsJsonObject();
JsonObject proj = obj1.get("Project").getAsJsonObject();
String url = proj.get("_ref").getAsString();
QueryRequest projQuery = new QueryRequest(url);
projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse projResponse = restApi.query(projQuery);
if (projResponse.wasSuccessful()) {
JsonArray tempProj = projResponse.getResults();
// Here we have the project object, now process Parents...
Boolean moreParents = true;
while (moreParents) {
QueryRequest parentQuery = new QueryRequest(url);
//projQuery.setFetch(new Fetch("_ref", "_refObjectUUID", "_refObjectName"));
QueryResponse parentResponse = restApi.query(parentQuery);
if (parentResponse.wasSuccessful()) {
System.out.println ("proj Response... " + parentResponse.toString());
JsonArray projParent = parentResponse.getResults();
tempHierarchy.concat(projParent.get(0).getAsString());
JsonArray tempParent = parentResponse.getResults();
proj = tempParent.getAsJsonObject();
} else {
moreParents = false;
}
}
} else {
System.err.println("The following errors occurred: ");
for (String err : projResponse.getErrors()) {
System.err.println("\t" + err);
}
throw new java.lang.Error("Rally API Call Error Occurred");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You probably want to use a GetRequest instead of a QueryRequest since you're just reading a single object. Also, include Parent in your fetch. Then you should have the data to be able to determine whether there is a parent and to continue looping or not.

autodesk design automation

FATAL ERROR: Unhandled Access Violation Reading 0x0008 Exception at 1d8257a5h
Failed missing output
I finally made it work with HostApplicationServices.getRemoteFile in local AutoCAD, then migrated it to Design Automation. It is also working now. The below is the command of .NET plugin.
To have a simple test, I hard-coded the URL in the plugin. you could replace the URL with the workflow at your side (either by an json file, or input argument of Design Automation)
My demo ReadDWG the entities from the remote URL file, then wblock the entities to current drawing (HostDWG), finally save current drawing.
Hope it helps to address the problem at your side.
.NET command
namespace PackageNetPlugin
{
class DumpDwgHostApp: HostApplicationServices
{
public override string FindFile(string fileName,
Database database,
FindFileHint hint)
{
throw new NotImplementedException();
}
public override string GetRemoteFile(Uri url,
bool ignoreCache)
{
//return base.GetRemoteFile(url, ignoreCache);
Database db =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Database;
string localPath = string.Empty;
if (ignoreCache)
{
localPath =
Autodesk.AutoCAD.ApplicationServices.Application.
GetSystemVariable("STARTINFOLDER") as string;
string filename =
System.IO.Path.GetFileName(url.LocalPath);
localPath += filename;
using (var client = new WebClient())
{
client.DownloadFile(url, localPath);
}
}
return localPath;
}
public override bool IsUrl(string filePath)
{
Uri uriResult;
bool result = Uri.TryCreate(filePath,
UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp ||
uriResult.Scheme == Uri.UriSchemeHttps);
return result;
}
}
public class Class1
{
[CommandMethod("MyPluginCommand")]
public void MyPluginCommand()
{
try {
string drawingPath =
#"https://s3-us-west-2.amazonaws.com/xiaodong-test-da/remoteurl.dwg";
DumpDwgHostApp oDDA = new DumpDwgHostApp();
string localFileStr = "";
if (oDDA.IsUrl(drawingPath)){
localFileStr = oDDA.GetRemoteFile(
new Uri(drawingPath), true);
}
if(!string.IsNullOrEmpty(localFileStr))
{
//source drawing from drawingPath
Database source_db = new Database(false, true);
source_db.ReadDwgFile(localFileStr,
FileOpenMode.OpenTryForReadShare, false, null);
ObjectIdCollection sourceIds =
new ObjectIdCollection();
using (Transaction tr =
source_db.TransactionManager.StartTransaction())
{
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
SymbolUtilityServices.GetBlockModelSpaceId(source_db),
OpenMode.ForRead);
foreach (ObjectId id in btr)
{
sourceIds.Add(id);
}
tr.Commit();
}
//current drawing (main drawing working with workitem)
Document current_doc =
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument;
Database current_db = current_doc.Database;
Editor ed = current_doc.Editor;
//copy the objects in source db to current db
using (Transaction tr =
current_doc.TransactionManager.StartTransaction())
{
IdMapping mapping = new IdMapping();
source_db.WblockCloneObjects(sourceIds,
SymbolUtilityServices.GetBlockModelSpaceId(current_db),
mapping, DuplicateRecordCloning.Replace, false);
tr.Commit();
}
}
}
catch(Autodesk.AutoCAD.Runtime.Exception ex)
{
Autodesk.AutoCAD.ApplicationServices.Application.
DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString());
}
}
}
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

Adding new revision for document in DropBox through android api

I want to add a new revision to the document(Test.doc) in Dropbox using android api. Can anyone share me any sample code or links. I tried
FileInputStream inputStream = null;
try {
DropboxInputStream temp = mDBApi.getFileStream("/Test.doc", null);
String revision = temp.getFileInfo().getMetadata().rev;
Log.d("REVISION : ",revision);
File file = new File("/sdcard0/renamed.doc");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/Test.doc", inputStream, file.length(), revision, new ProgressListener() {
#Override
public void onProgress(long arg0, long arg1) {
Log.d("","Uploading.. "+arg0+", Total : "+arg1);
}
});
} catch (Exception e) {
System.out.println("Something went wrong: " + e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
New revision is created for first time. When i execute again, another new revision is not getting created.

Managing trace files on Sql Server 2005

I need to manage the trace files for a database on Sql Server 2005 Express Edition. The C2 audit logging is turned on for the database, and the files that it's creating are eating up a lot of space.
Can this be done from within Sql Server, or do I need to write a service to monitor these files and take the appropriate actions?
I found the [master].[sys].[trace] table with the trace file properties. Does anyone know the meaning of the fields in this table?
Here's what I came up with that is working pretty good from a console application:
static void Main(string[] args)
{
try
{
Console.WriteLine("CcmLogManager v1.0");
Console.WriteLine();
// How long should we keep the files around (in months) 12 is the PCI requirement?
var months = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RemoveMonths") ?? "12");
var currentFilePath = GetCurrentAuditFilePath();
Console.WriteLine("Path: {0}", new FileInfo(currentFilePath).DirectoryName);
Console.WriteLine();
Console.WriteLine("------- Removing Files --------------------");
var fileInfo = new FileInfo(currentFilePath);
if (fileInfo.DirectoryName != null)
{
var purgeBefore = DateTime.Now.AddMonths(-months);
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc.zip");
foreach (var file in files)
{
try
{
var fi = new FileInfo(file);
if (PurgeLogFile(fi, purgeBefore))
{
Console.WriteLine("Deleting: {0}", fi.Name);
try
{
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Removed ---------------------");
Console.WriteLine();
Console.WriteLine("------- Compressing Files -----------------");
if (fileInfo.DirectoryName != null)
{
var files = Directory.GetFiles(fileInfo.DirectoryName, "audittrace*.trc");
foreach (var file in files)
{
// Don't attempt to compress the current log file.
if (file.ToLower() == fileInfo.FullName.ToLower())
continue;
var zipFileName = file + ".zip";
var fi = new FileInfo(file);
var zipEntryName = fi.Name;
Console.WriteLine("Zipping: \"{0}\"", fi.Name);
try
{
using (var fileStream = File.Create(zipFileName))
{
var zipFile = new ZipOutputStream(fileStream);
zipFile.SetLevel(9);
var zipEntry = new ZipEntry(zipEntryName);
zipFile.PutNextEntry(zipEntry);
using (var ostream = File.OpenRead(file))
{
int bytesRead;
var obuffer = new byte[2048];
while ((bytesRead = ostream.Read(obuffer, 0, 2048)) > 0)
zipFile.Write(obuffer, 0, bytesRead);
}
zipFile.Finish();
zipFile.Close();
}
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Console.WriteLine("------- Files Compressed ------------------");
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
public static bool PurgeLogFile(FileInfo fi, DateTime purgeBefore)
{
try
{
var filename = fi.Name;
if (filename.StartsWith("audittrace"))
{
filename = filename.Substring(10, 8);
var year = Convert.ToInt32(filename.Substring(0, 4));
var month = Convert.ToInt32(filename.Substring(4, 2));
var day = Convert.ToInt32(filename.Substring(6, 2));
var logDate = new DateTime(year, month, day);
return logDate.Date <= purgeBefore.Date;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
public static string GetCurrentAuditFilePath()
{
const string connStr = "Data Source=.\\SERVER;Persist Security Info=True;User ID=;Password=";
var dt = new DataTable();
var adapter =
new SqlDataAdapter(
"SELECT path FROM [master].[sys].[traces] WHERE path like '%audittrace%'", connStr);
try
{
adapter.Fill(dt);
if (dt.Rows.Count >= 1)
{
if (dt.Rows.Count > 1)
Console.WriteLine("More than one audit trace file defined! Count: {0}", dt.Rows.Count);
var path = dt.Rows[0]["path"].ToString();
return path.StartsWith("\\\\?\\") ? path.Substring(4) : path;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
throw new Exception("No Audit Trace File in sys.traces!");
}
You can also set up SQL Trace to log to a SQL table. Then you can set up a SQL Agent task to auto-truncate records.
sys.traces has a record for every trace started on the server. Since SQL Express does not have Agent and cannot set up jobs, you'll need an external process or service to monitor these. You'll have to roll your own everything (monitoring, archiving, trace retention policy etc). If you have C2 audit in place, I assume you have policies in place that determine the duration audit has to be retained.