Unable to upload files greater than 7KB via ajax call to servlet over https - ajax

I am running JBoss 6.3 portal and have deployed a war file containing following two files
1) DocUpload.jsp
Containing following code snippet making an ajax call to send the mentioned fields in data2 along with file object fd.
fd.append('file', document.getElementById('file1').files[0]);
data2 = encodeURIComponent(document.getElementById("lob").value)+'#'+encodeURIComponent(document.getElementById("loantype").value)+
'#'+encodeURIComponent(document.getElementById('docType').value)+'#'+encodeURIComponent(document.getElementById('docName').value)+
'#'+encodeURIComponent(document.getElementById('entity').value)+'#'+encodeURIComponent(document.getElementById('userName').value)+
'#'+encodeURIComponent(document.getElementById('PartyName').value)+'#'+encodeURIComponent(document.getElementById('loanAccount').value)+
'#'+encodeURIComponent(document.getElementById('LoanAmount').value)+'#'+encodeURIComponent(e4)+'#'+encodeURIComponent(document.getElementById('hiddenWIName').value)+'#'+encodeURIComponent(e3);
alert("data2 "+data2);
var ret = doPostAjax("${pageContext.request.contextPath}/AddDocumentsServlet?data="+data2,fd);
2) AddDocumentsServlet.java
Containing code for handling the request
File path = new File(RootFolderPath + File.separator + "Portal_TmpDoc" + File.separator + todayAsString + File.separator + lMilliSecondsCurrent);
UploadPath = path.getAbsolutePath();
if (!path.isDirectory()) {
path.mkdirs();
}
if (isMultipart) {
System.out.println("Inside if isMultipart");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
//List multiparts = upload.parseRequest(request);
System.out.println("Before parsing request");
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("multiparts :::"+multiparts);
for (Iterator iterator = multiparts.iterator(); iterator.hasNext();) {
FileItem item = (FileItem) iterator.next();
logger.info(item);
if (!item.isFormField()) {
String fileobject = item.getFieldName();
System.out.println(request.getParameter("data"));
String[] fileArray = request.getParameter("data").split("#");
name = new File(item.getName()).getName();
name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
ext = name.substring(name.lastIndexOf(".") + 1);
logger.info(name);
File directory = new File(UploadPath);
File[] afile;
int j = (afile = directory.listFiles()).length;
for (int i = 0; i < j; i++) {
File f = afile[i];
if (f.getName().startsWith(filename))
f.delete();
}
item.write(new File(UploadPath + File.separator + filename + "." + ext));
System.out.println("File Uploaded");
}
}
My problem is when I use http connection for the above requests and getting session the program runs just fine. But while using https and uploading file greater than 7 KB the page becomes unresponsive.
On further analysis I found that the program flow gets stuck on this line
List<FileItem> multiparts = upload.parseRequest(request);
and despite having this line in a try block no exception is caught.

Related

Spring Boot - REST API to Post file and return Zipped file in response

Im trying to receive a file from an HTTP POST which I split into individual files wand then need to return that in a zip file. I am trying to return the file and I have tried everything to return the file, but I am unable to recieve the file... any thoughts?
#RequestMapping(value = "/splitFile", headers = ("content-type=multipart/*"), produces ="application/zip", method = RequestMethod.POST)
public void SplitFile(#RequestParam(value = "file", required = true) MultipartFile[] file, HttpServletResponse response ) throws IOException {
for (int i = 0; i < file.length; i++) {
File uplFile = new File(file[i].getOriginalFilename());
uplFile.createNewFile();
FileOutputStream fos = new FileOutputStream(uplFile);
fos.write(file[i].getBytes());
fos.close();
System.out.println("Splitting File: " + uplFile.getName());
uploadHelper Help = new uploadHelper();
ArrayList<String> filestrings = new ArrayList<String>();
filestrings = uplHelp.GetSplitFiles(uplFile);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
StringBuilder sb = new StringBuilder();
int filenumber = 0;
for (String filedata : filestrings) {
filenumber = filenumber + 1;
sb.append(filedata);
ZipEntry e = new ZipEntry("file_" + filenumber + ".data");
zipOutputStream.putNextEntry(e);
byte[] data = sb.toString().getBytes();
zipOutputStream.write(data, 0, data.length);
zipOutputStream.closeEntry();
}
System.out.println("Splitting File - Split " + filestrings.size() + " files");
if (zipOutputStream != null) {
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
}
IOUtils.closeQuietly(bufferedOutputStream);
IOUtils.closeQuietly(out);
InputStream is = new ByteArrayInputStream(out.toByteArray());
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Content-Disposition", "attachment; filename=test.zip");
response.setCharacterEncoding("gzip");
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
}
response.setStatus(HttpServletResponse.SC_ACCEPTED);
response.flushBuffer();
}

How to set Encoding in MQ headers using Beanshell in Jmeter

I am developing a test script to put a message onto a queue using IBM MQ API 8.0. I am using JMeter 3.1 and Beanshell Sampler for this (see code below).
The problem I am having is setting the "Encoding" field in the MQ headers. I've tried different methods as per API documentation, but nothing worked for me.
Has anyone faced this issue?
Thanks in advance!
Code below:
try {
MQEnvironment.hostname = _hostname;
MQEnvironment.channel = _channel;
MQEnvironment.port = _port;
MQEnvironment.userID = "";
MQEnvironment.password = "";
log.info("Using queue manager: " + _qMgr);
MQQueueManager _queueManager = new MQQueueManager(_qMgr);
int openOptions = CMQC.MQOO_OUTPUT + CMQC.MQOO_FAIL_IF_QUIESCING + CMQC.MQOO_INQUIRE + CMQC.MQOO_BROWSE
+ CMQC.MQOO_SET_IDENTITY_CONTEXT;
log.info("Using queue: " + _queueName + ", openOptions: " + openOptions);
MQQueue queue = _queueManager.accessQueue(_queueName, openOptions);
log.info("Building message...");
MQMessage sendmsg = new MQMessage();
sendmsg.clearMessage();
// Set MQ MD Headers
sendmsg.messageType = CMQC.MQMT_DATAGRAM;
sendmsg.replyToQueueName = _queueName;
sendmsg.replyToQueueManagerName = _qMgr;
sendmsg.userId = MQuserId;
sendmsg.setStringProperty("BAH_FR", fromBIC); // from /AppHdr/Fr/FIId/FinInstnId/BICFI
sendmsg.setStringProperty("BAH_TO", toBIC); // from /AppHdr/To/FIId/FinInstnId/BICFI
sendmsg.setStringProperty("BAH_MSGDEFIDR", "pacs.008.001.05"); // from /AppHdr/MsgDefIdr
sendmsg.setStringProperty("BAH_BIZSVC", "cus.clear.01-" + bizSvc); // from /AppHdr/BizSvcr
sendmsg.setStringProperty("BAH_PRTY", "NORM"); // priority
sendmsg.setStringProperty("userId", MQuserId); // user Id
sendmsg.setStringProperty("ConnectorId", connectorId);
sendmsg.setStringProperty("Roles", roleId);
MQPutMessageOptions pmo = new MQPutMessageOptions(); // accept the defaults, same as MQPMO_DEFAULT constant
pmo.options = CMQC.MQOO_SET_IDENTITY_CONTEXT; // set identity context by userId
// Build message
String msg = "<NS1> .... </NS1>";
// MQRFH2 Headers
sendmsg.format = CMQC.MQFMT_STRING;
//sendmsg.encoding = CMQC.MQENC_INTEGER_NORMAL | CMQC.MQENC_DECIMAL_NORMAL | CMQC.MQENC_FLOAT_IEEE_NORMAL;
sendmsg.encoding = 546; // encoding - 546 Windows/Linux
sendmsg.messageId = msgID.getBytes();
sendmsg.correlationId = CMQC.MQCI_NONE;
sendmsg.writeString(msg);
String messageIdBefore = new String(sendmsg.messageId, "UTF-8");
log.info("Before put, messageId=[" + messageIdBefore + "]");
int depthBefore = queue.getCurrentDepth();
log.info("Queue Depth=" + depthBefore);
log.info("Putting message on " + _queueName + ".... ");
queue.put(sendmsg, pmo);
int depthAfter = queue.getCurrentDepth();
log.info("Queue Depth=" + depthAfter);
log.info("**** Done");
String messageIdAfter = new String(sendmsg.messageId, "UTF-8");
log.info("After put, messageId=[" + messageIdAfter + "]");
log.info("Closing connection...");
} catch (Exception e) {
log.info("\\nFAILURE - Exception\\n");
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
log.error(errors.toString());
}
I think you are over thinking the problem. If you are not doing some sort of weird manual character/data conversion then you should be using:
sendmsg.encoding = MQC.MQENC_NATIVE;

Xamarin UILabel not updating

I've a basic for loop that's basically download files. It's supposed to update the label as long as it progress.
By searching here at Stack Overflow, I found an orientation to use SetNeedsDisplay(). But it's still refuses to update. Any idea ?
for (int i = 0; i < files.Length; i++)
{
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay();
string remoteFile = assetServer + files[i];
var webClient2 = new WebClient();
string localFile = files[i];
string localPath3 = Path.Combine(documentsPath, localFile);
webClient2.DownloadFile(remoteFile, localPath3);
}
As previously suggested try to avoid blocking the UI when doing heavy transactions in it. WebClient already has a async method which you can use.
webClient2.DownloadFileasync(new System.Uri(remoteFile), localPath3);
and to prevent you from accessing the UI from a different thread use the built-in method InvokeOnMainThread when accessing UI elements.
InvokeOnMainThread (() => {
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay ();
});
and finally use the using statement to help you with the resources disposal.
using (var webClient2 = new WebClient ())
{
webClient2.DownloadFileAsync (new System.Uri (remoteFile), localPath3);
}
You could also have the iteration inside the using statement this way you don't have to create a WebClient object for each file instead you will use the same object to download all files available in your files array.

how to add a folder in the apk

I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}

To Extract .7zip file using SharpCompress library in windows phone but getting exception

IArchive archive = null;
IReader reader = null;
archive = SevenZipArchive.Open(fileStream, Options.LookForHeader);
reader = archive.ExtractAllEntries();
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Stream _redaer = new MemoryStream();
reader.WriteEntryTo(_redaer);
fileName = reader.Entry.FilePath;
int index = fileName.LastIndexOf("/");
string file = fileName.Substring(index + 1, (fileName.Length - (index + 1)));
using (binaryReader = new BinaryReader(_redaer, encoding))
{
long fileLength = _redaer.Length;
MemoryStream ms = new MemoryStream();
_redaer.Position = 0;
_redaer.CopyTo(ms);
byte[] buteArray = ms.ToArray();
SaveToIsoStore(fileName, buteArray);
}
}
}
This code gives exception of type SharpCompress.Common.InvalidFormatException,Please provide the solution in wp7.

Resources