Upload File Callable Object (GP)
Hello,
I want to create a process where a user:
1 - Fills in a form
2 - Uploads a file using the "Upload file" callable object
3 - Another user receives a workitem with the data from the form, and the file.
I know I can use attachments, but I want to have an explicit "Upload FIle" step. If I don't, people will forget to upload the file....
Problem is I can't seem to map the file, into the "Display Form" of step 3. Is it possible?
Hi,
For creating WD callable object you need to add following three DC in your WD DC project.
In the Web Dynpro Explorer of the Web Dynpro Perspective, expand the node DC MetaData -> DC Definition, and select Used DCs.
a. To create a DC dependency, open the context menu and choose Add Used DC.
b. Select Local Development -> SAP-EU -> caf/eu/gp/api/wd -> DC MetaData -> Public Parts -> GPWebDynproCO. For Dependency Type, select Build Time, Design Time, and Run Time. Choose weak from the dropdown list.
c. Repeat the previous step to define a dependency to DCs SAP-EU-> caf/eu/gp/api (public part external) and SAP-JEE -> com.sap.security.api.sda (public part default).
You need to do one more thing like bellow.
Select your Web Dynpro project and open its context menu. Choose Properties.
1. Choose Web Dynpro References -> Library References.
2. Add a reference for library caf/eu/gp/api.
I think this will help you.
Thanks
Chandan
Similar Messages
-
Upload file in Web Dynpro and add to Workflow container as SOFM object
Hi!
I have a Web Dynpro for ABAP application that should send attachments of uploaded files to a workflow container. I have already managed to do this, and it works fine for TXT files, but when I try to attach a WORD (.DOC) file the file looks corrput when I open it from the SAP inbox.
When uploading files in Web Dynpro it is as an XSTRING. I have tried out the following alternatives regarding convertion of the XSTRING before it is inserted in the SOFM object:
1) Convert from XSTRING to STRING using codepage 4110.
Then it is split into a string table of 255 chars
2) Convert from XSTRING to STRING using codepage 4102
Then it is split into a string table of 255 chars
3) Convert from XSTRING to BINARY format
I use function module 'SWL_SOFM_CREATE_WITH_TABLE'
and then swf_create_object lr_sofm 'SOFM' ls_sofm_key.
before I call some macros to fill the container.
Anyone else who have tried to do this with success? I'm greatful for any help.
Regards, TineHi,
I had the same problem in the last days and finally I got a quite simple solution:
I had a look at the FM SWL_SOFM_CREATE_WITH_TABLE an noticed that it calls another FM (SO_DOCUMENT_INSERT_API1) which has a tables parameter for HEX data and is actually able to create a SOFM object from HEX data.
I simply copied SWL_SOFM_CREATE_WITH_TABLE as a customer FM and applied a few changes to make it accept HEX data:
First I added a new table parameter in the interface which gets the HEX data from the calling application (uploaded data using BIN format):
OBJECT_CONTENT_HEX LIKE SOLIX
Here is the code of the FM (I marked all additional and changed lines with a comment):
function z_test_sofm_create_with_table .
*"*"Lokale Schnittstelle:
*" IMPORTING
*" VALUE(NOTE_TITLE) LIKE SODOCCHGI1-OBJ_DESCR OPTIONAL
*" VALUE(DOCUMENT_TYPE) LIKE SOODK-OBJTP DEFAULT SPACE
*" EXPORTING
*" VALUE(SOFM_KEY) LIKE SWOTOBJID-OBJKEY
*" TABLES
*" NOTE_TEXT STRUCTURE SOLISTI1 OPTIONAL
*" OBJECT_CONTENT_HEX STRUCTURE SOLIX OPTIONAL
*" EXCEPTIONS
*" ERROR_SOFM_CREATION
data: region like sofd-folrg.
data: folder_id like soodk.
data: l_folder_id like soobjinfi1-object_id.
data: document_data like sodocchgi1.
data: document_info like sofolenti1.
data: object_content like solisti1 occurs 0 with header line.
data: lines like sy-tabix.
*- set default
if document_type is initial.
document_type = 'RAW'.
endif.
*- create office object
*-- get dark folder
region = 'B'.
call function 'SO_FOLDER_ROOT_ID_GET'
exporting
region = region
importing
folder_id = folder_id
exceptions
communication_failure = 1
owner_not_exist = 2
system_failure = 3
x_error = 4
others = 5.
if sy-subrc ne 0.
message e696(wl) "<== Add message class
raising error_sofm_creation.
endif.
*- get description
if note_title is initial.
read table note_text index 1.
note_title = note_text.
endif.
*-- create office document
document_data-obj_name = 'ATTACHMENT'.
document_data-obj_descr = note_title.
document_data-obj_langu = sy-langu.
object_content[] = note_text[].
describe table object_content lines lines.
document_data-doc_size = ( lines - 1 ) * 255 + strlen( object_content ).
if object_content[] is initial. "<== insert
describe table object_content_hex lines lines. "<== insert
document_data-doc_size = lines * 255. "<== insert
endif. "<== insert
l_folder_id = folder_id.
call function 'SO_DOCUMENT_INSERT_API1'
exporting
folder_id = l_folder_id
document_data = document_data
document_type = document_type
importing
document_info = document_info
tables
object_content = object_content
contents_hex = object_content_hex " <== Insert line
exceptions
folder_not_exist = 1
document_type_not_exist = 2
operation_no_authorization = 3
parameter_error = 4
x_error = 5
enqueue_error = 6
others = 7.
if sy-subrc ne 0.
message e696(wl) "<== Add message class
raising error_sofm_creation.
endif.
*- set export parameter
sofm_key = document_info-doc_id.
endfunction.
The returned SOFM key I added to a container element. The element refers to event parameter of type OBJ_RECORD in my ABAP OO Class
Using this function I was able to raise an event by using Method cl_swf_evt_event=>raise
that invoked a workitem containing an Excel-File i had uploaded as binary file and passed to the FM z_test_sofm_create_with_table as document type 'XLS'.
In the woritem preview when clicking on the attachment the file was opened directly in Excel.
Actually the new lines for calculation the file size is not yet quite correct. At first glance it does not seem to cause any trouble, but I will stll check that. In FM SO_OBJECT_INSERT the size is again checked and calculated if initial, so leaving size initial might also be an option.
I hope this helps anyone having a similar issue.
Greetings,
Michael Gulitz -
Unable to see the uploaded file using gos object
Hi Experts,
I uploaded the file to server by using the below code. But I am unable to see the uploaded file. Please help me out hot to view the uploaded files (list the file name and view the content) (i want to upload the file by getting the url as input and by clicking the button)
Code to upload the file.
DATA: wa_zqtc_gos_request TYPE zqtc_gos_request.
DATA: l_attachment TYPE swo_typeid.
DATA: lo_gos_service TYPE REF TO cl_gos_document_service.
obj-objkey = req_num.
obj-objtype = objtype.
CREATE OBJECT lo_gos_service.
CALL METHOD lo_gos_service->create_attachment
EXPORTING
is_object = obj
IMPORTING
ep_attachment = l_attachment.
I tyied with this to view the files but the attachement link is disabled. (i want to view the files by clicking the icon-GOS icon in tool bar)
DATA: wa_zqtc_gos_request TYPE zqtc_gos_request.
DATA: l_attachment TYPE swo_typeid.
DATA: lo_gos_service TYPE REF TO cl_gos_document_service.
obj-objtype = objtype.
obj-objkey = req_num.
CREATE OBJECT manager
EXPORTING
is_object = obj
EXCEPTIONS
OTHERS = 1.
Please help me out how to view the file and list.
thanks & regards
T.Tamodarane
Edited by: T.Tamodarane on Oct 23, 2009 9:55 AM
Edited by: T.Tamodarane on Oct 23, 2009 9:56 AMHi,
Please post ur thred below:
PL/SQL
Regards
Meher Irk -
Interactive Form/File Approval Callable Object - %PDF- error
I have a GP which send out an Adobe Form via E-mail and waits for a response.
When the form is returned, I want to render the Adobe form from the UWL as part of the task.
I understand that the Process Control - Interactive Form/File Approval Callable object can be used for this.
However, when I try to open the task I get an error message saying the File does not start with %PDF-
Looking at the process context in the NWA, I do see the PDF binary content at that step.
Any ideas?
I have followed an example setup as shown on:
http://help.sap.com/saphelp_nw04s/helpdata/en/0a/964dfc764b4a428f4321f1ba33dbdd/frameset.htm
Thanks
Hennie PietersThanks a lot Greg for the response.
If the output of an interactive form includes a structure called 'Interactive Form' with the attributes you mentioned, that will serve my purpose.
However, I am not seeing these fields any where in the default output of MY interactivev forms. Do I have to do something explicitly to see it in the output.
I would appreciate your prompt response.
Thanks
Ram -
GP: Creation of process for uploading file with approval or a rejection
Problem: It is necessary to organise process of uploading files in KM repository with approval or a rejection.
I have created process with two callable objects.
1. File Input
2. Interactive Form/File Approval
Has grouped structure "File"
In Runtime, during object performance "Interactive Form/File Approval" there is an error:
com.sap.tc.webdynpro.services.exceptions.WDRuntimeException: pdfSource of InteractiveForm UI element should be populated with pdf binary content in USE_PDF mode
It is one problem, the second problem consists in that how to organise a folder choice where the file will be loaded.Hi Pustovoytov Stanislav ,
Check whether if the context attribute pdfsource is of binary type or any other type. It sbould be of binary type.
And about the second one you can organize the folder structure in the KM administration.
Thanks
Satya -
Type in "Callable Object" gallery in CAF?
Hello,
I'm trying to follow the doc "Building the Job Application Process - SAP Composite Application Framework v1.1" to build a test process.
My environment is the NetWeaver Sneakpreview 2004s SPS4 on Windows 2003 Server.
sap.com/SAP-JEECOR 7.00 SP7 (1000.7.00.7.0.20060324070000) 20060703235737
sap.com/SAP-JEE 7.00 SP7 (1000.7.00.7.0.20060319012200) 20060703235756
I logged in ad Administrator, and verified that it also has the roles "GP Basic User" and "GP Business Expert".
After I clicked on "Create Callable Object", the next screen only shows 3 lines in the "Type" pane, which are 'Web Dynpro Form', 'Web Pages', and an expandable 'Data forms'.
I'm looking for "content package" and "Web dynpro component" types.
Am I missing something here? The install of the preview went without any errors (at least not on the installer console). I am able to create a Folder, create a new "content package", upload an HTML file into the package, and activate it.
Also, any references to such self guided study guides will be appreciated.
Yethat was the easiest 10 points I ever received. thank you. so funny, sometimes you work your butts out and get no appreciation. in your case the question and answer was simple but I still get the maximum reward points. what a great return on investment.
Anyway, if your company is a SAP customer or partner, you should have or somebody in your organization should have the login id to service.sap.com. Otherwise go to SDN under the CAF Tutorial Center SAP Composite Application Framework - CAF Tutorial Center [original link is broken] where you should also get enough how-to guides. Enjoy you learning experience with GP! -
Problem in use xmlgen.insertXML to insert XML file to Object Viewse
I am trying to update XML file to Object View but it failed. Refer to the steps that I was doing.
1) Use utl_file.get_line to read XML file which I generated (It is no problem)
2)The xml data is
<?xml version="1.0" ?>
- <ROWSET>
- <ROW num="1">
<PK_NO>305</PK_NO>
<ACC_NAME>PAPERS AND CLIPS</ACC_NAME>
<FROM_NAME>MB METAL PTE LTD</FROM_NAME>
<MAS_NO>990015</MAS_NO>
<MAS_DATE>2000-04-07 15:47:52.0</MAS_DATE>
<CURR_CODE>SGD</CURR_CODE>
<MAS_CODE>WRFQ</MAS_CODE>
<REMARK>SADKJAS</REMARK>
- <LINEITEMLIST_NTAB>
- <LINEITEMLIST_NTAB_ITEM>
<ITEM_NO>1</ITEM_NO>
<STK_C>2506401</STK_C>
<SP_STK_C>H282828</SP_STK_C>
<STK_NAME>STICK-ON-NOTES - 11110 1.5, 12 100 SHEET PADS</STK_NAME>
<UOM>SET</UOM>
<QTY>10</QTY>
<SALES_PRICE>95.50</SALES_PRICE>
<REMARK>SADKJAS</REMARK>
</LINEITEMLIST_NTAB_ITEM>
- <LINEITEMLIST_NTAB_ITEM>
<ITEM_NO>2</ITEM_NO>
<STK_C>7706001</STK_C>
<SP_STK_C>H282828</SP_STK_C>
<STK_NAME>FACESHIELD/EYE PROT CLEAR GLASS WTR PLATE, STANDARD DREW</STK_NAME>
<UOM>PCS</UOM>
<QTY>1</QTY>
<SALES_PRICE>100</SALES_PRICE>
<REMARK>SADKJAS</REMARK>
</LINEITEMLIST_NTAB_ITEM>
</LINEITEMLIST_NTAB>
</ROW>
</ROWSET>
3) From Object View, I generated xml file is
- <ROWSET>
- <ROW num="1">
<PK_NO>2</PK_NO>
<ACC_NAME>PAPERS AND CLIPS</ACC_NAME>
<FROM_NAME>MB METAL PTE LTD</FROM_NAME>
<MAS_NO>990015</MAS_NO>
<MAS_DATE>2000-06-07 00:00:00.0</MAS_DATE>
<CURR_CODE>SGD</CURR_CODE>
<MAS_CODE>WRFQ</MAS_CODE>
- <LINEITEMLIST_NTAB>
- <LINEITEMLIST_NTAB_ITEM>
<ITEM_NO>1</ITEM_NO>
<STK_C>2506401</STK_C>
<STK_NAME>STICK-ON-NOTES - 11110 1.5,X2 12 100 SHEET PADS</STK_NAME>
<UOM>SET</UOM>
<QTY>1</QTY>
<SALES_PRICE>10</SALES_PRICE>
</LINEITEMLIST_NTAB_ITEM>
</LINEITEMLIST_NTAB>
</ROW>
- <ROW num="2">
<PK_NO>4</PK_NO>
<ACC_NAME>ABC</ACC_NAME>
<FROM_NAME>VBF</FROM_NAME>
<MAS_NO>99200</MAS_NO>
<MAS_DATE>2000-01-04 00:00:00.0</MAS_DATE>
<CURR_CODE>SGD</CURR_CODE>
<MAS_CODE>DSDS</MAS_CODE>
<REMARK>WRFQ</REMARK>
<LINEITEMLIST_NTAB />
</ROW>
</ROWSET>
3) I use INSTEAD OF trigger for Object View to insert the data to database.
I got the message is:
ORA-29532: Java call terminated by uncaught Java exception: oracle.xml.sql.OracleXMLSQLException:5.
Anybody can give me the advise for that.
nullIf you have the ftp server at 8080 running (9iR2 only) the simples way is to upload it to the database through that server. You can then do whatever you want using the xdburitype() procedure.
Below is an excerpt of a script I use to register XML schema's (I've got some very long ones, about 150K). It should work with "any" file..
begin
dbms_xmlschema.registerSchema (
schemaURL => 'http://www.agralin.nl/WebQuery/ns/&1',
schemaDoc => xdburitype('/age/&1..xsd'),
local => TRUE,
genTables => FALSE,
genbean => FALSE,
genTypes => TRUE,
force => FALSE,
owner => 'AGE'
end; -
Is there a way to silently upload files?
Ok, so I've taken the plunge. I've started working on an AIR
app using Flash CS3. I'm putting together a little app that will
keep my online store updated with all the product updates from our
wholesaler. This includes parsing a csv file, downloading product
images from the wholesaler, updating the database, and then
uploading the images to our server.
The problem is that AIR does not seem to have the
functionality to silently upload files! Sure, I can use the
file.reference object to fire off the browse method, which then
opens the OS file browser window BUT I would really like the whole
thing to be hands off. In the past, I've written these types of
apps using Visual Studio but I haven't touched VS in two years.
Has anyone run across a way to silently upload or ftp files
in AIR?Hey Oliver,
Thanks for your answer--the fact that it CAN be done has
gotten me a lot further on finding a solution. Here's what I have
so far. As it runs, I can see the progress and completion of the
upload but I'm still not getting it saved. I'm uploading it to a
ColdFusion processing page.
AS3 Code:
import flash.filesystem.*;
import flash.net.URLRequest;
//Silent File Upload (no browse window)
function imageUpload(imageName,uploadPage):void
trace('Starting Upload of ' + imageName + '\n');
var myFile:File =
File.applicationDirectory.resolvePath(imageName);
var request:URLRequest = new URLRequest(uploadPage);
request.method = URLRequestMethod.POST;
myFile.addEventListener(ProgressEvent.PROGRESS,progressHandler);
myFile.addEventListener(Event.COMPLETE,completeHandler);
myFile.upload(request,"theFile");
function progressHandler(event:ProgressEvent):void {
var file:FileReference = FileReference(event.target);
var pLoaded =
Math.ceil(event.bytesLoaded/event.bytesTotal*100);
trace(pLoaded + '% uploaded');
function completeHandler(event:Event):void
trace ('Upload complete.');
var uploadPage = "
http://www.aaronbday.com/upload_file.cfm";
imageUpload("angelic_cat.jpg",uploadPage);
Here's the CFM page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=utf-8" />
<title>Upload File</title>
</head>
<body>
<cfif isDefined("form.theFile")>
<!---we only want images--->
<cffile
action="upload"
destination="#ExpandPath("test/")#"
filefield="theFile"
nameconflict="overwrite"
accept="image/jpg,image/jpeg,image/gif,image/pjpeg"
>
<cfoutput><img src="test/#cffile.serverFile#"
/></cfoutput>
<cfelse>
<form method="post" action="upload_file.cfm"
enctype="multipart/form-data">
<input type="file" name="theFile" />
<input type="submit" name="Submit" />
</form>
</cfif>
</body>
</html>
Any ideas? Thanks! -
We can use JSR-168 JPS portlet upload file,
We can use JSR-168 JPS portlet upload file,
here is the source for you referrence:
upload file can use JSR168 portlet,
1,CustomizablePortlet.java File
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.portlet.*;
import oracle.webdb.utils.SimpleStringBuffer;
public class CustomizablePortlet extends GenericPortlet {
private static final String TITLE_KEY = "title";
protected static final String OK_ACTION = "ok_action";
protected static final String APPLY_ACTION = "apply_action";
protected static final PortletMode PREVIEW_MODE = new PortletMode("preview");
protected static final PortletMode EDIT_DEFAULTS_MODE = new PortletMode("EDIT_DEFAULTS");
protected static final PortletMode ABOUT_MODE = new PortletMode("ABOUT");
public CustomizablePortlet() {
public String getTitle(RenderRequest request) {
return request.getPreferences().getValue("title", getPortletConfig().getResourceBundle(request.getLocale()).getString("javax.portlet.title"));
public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<FORM ACTION=\"");
out.print(getEditFormSubmitURL(request, response));
out.println("\" METHOD=\"POST\">");
out.println("<TABLE BORDER=\"0\">");
out.println("<TR>");
out.println("<TD WIDTH=\"20%\">");
out.println("<P CLASS=\"portlet-form-field\" ALIGN=\"RIGHT\">Title:");
out.println("</TD>");
out.println("<TD WIDTH=\"80%\">");
out.print("<INPUT CLASS=\"portlet-form-input-field\" TYPE=\"TEXT\" NAME=\"");
out.print("title");
out.print("\" VALUE=\"");
out.print(getTitle(request));
out.println("\" SIZE=\"20\">");
out.println("</TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD COLSPAN=\"2\" ALIGN=\"CENTER\">");
out.print("<INPUT CLASS=\"portlet-form-button\" TYPE=\"SUBMIT\" NAME=\"");
out.print("ok_action");
out.print("\" VALUE=\"OK\">");
out.print("<INPUT CLASS=\"portlet-form-button\" TYPE=\"SUBMIT\" NAME=\"");
out.print("apply_action");
out.print("\" VALUE=\"Apply\">");
out.println("</TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("</FORM>");
protected String getEditFormSubmitURL(RenderRequest request, RenderResponse response) {
return response.createActionURL().toString();
public void doHelp(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("Help for <i><b>");
out.print(getTitle(request));
out.println("</b></i>.");
public void doAbout(RenderRequest request, RenderResponse response) throws PortletException, IOException {
String aboutHTML = (new SimpleStringBuffer(30)).append("/about_").append(getPortletName()).append(".html").toString();
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(aboutHTML);
response.setContentType("text/html");
if(rd != null) {
rd.include(request, response);
} else {
PrintWriter out = response.getWriter();
out.print("<p class=\"portlet-font\">This is the about page for ");
out.print(getTitle(request));
out.print(".</p><p class=\"portlet-font\">");
out.print("To customize the contents of this page, create a file named '");
out.print(aboutHTML.substring(1));
out.print("' in the Portlet web application's root directory containing HTML ");
out.print("to appear here. ");
out.print("Alternatively, override the <code>CustomizablePortlet</code> ");
out.println("class's <code>doAbout()</code> method.</p>");
public void doDispatch(RenderRequest request, RenderResponse response) throws PortletException, IOException {
WindowState state = request.getWindowState();
if(!state.equals(WindowState.MINIMIZED)) {
PortletMode mode = request.getPortletMode();
if(mode.equals(PREVIEW_MODE))
doView(request, response);
else
if(mode.equals(EDIT_DEFAULTS_MODE))
doEdit(request, response);
else
if(mode.equals(ABOUT_MODE))
doAbout(request, response);
else
super.doDispatch(request, response);
} else {
super.doDispatch(request, response);
public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException {
String newTitle = request.getParameter("title");
PortletPreferences prefs = request.getPreferences();
prefs.setValue("title", newTitle);
prefs.store();
if(request.getParameter("ok_action") != null) {
actionResponse.setPortletMode(PortletMode.VIEW);
actionResponse.setWindowState(WindowState.NORMAL);
2,FileUploadPortlet.java file
import java.io.*;
import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.portlet.*;
import oracle.portal.portlet.sample.CustomizablePortlet;
public class FileUploadPortlet extends CustomizablePortlet
private static final String FILE_PARAM = "file";
private static final String SUBMIT_PARAM = "submit";
private static final String DEFAULT_CHARSET = "ISO-8859-1";
private static final String uploadRoot = "";
public FileUploadPortlet()
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<form action=\"");
out.print(response.createActionURL().toString());
out.println("\" enctype=\"multipart/form-data\" method=\"post\">");
out.println("<center><table border=\"0\">");
out.println("<tr>");
out.print("<td class=\"portlet-form-field\" align=\"right\">");
out.print("Please browse to an HTML file:");
out.println("</td>");
out.print("<td>");
out.print("<input class=\"portlet-form-input-field\" type=\"file\" name=\"");
out.print("file");
out.print("\">");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td colspan=\"2\" align=\"center\">");
out.print("<input type=\"submit\" class=\"portlet-form-button\" name=\"");
out.print("submit");
out.print("\" value=\"Display\">");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
String lastFile = request.getPreferences().getValue("file", null);
if(lastFile != null) {
out.println("<hr width=\"100%\"><br>");
out.print(lastFile);
public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, IOException {
FormDataParser parsedRequest = new FormDataParser(request);
MimeBodyPart mbp = parsedRequest.getMimeBodyPart("file");
if(mbp == null)
super.processAction(request, actionResponse);
else
try {
String fileName= mbp.getFileName();
int splash = fileName.lastIndexOf("\\");
if(splash != -1)
fileName = fileName.substring(splash +1, fileName.length()).trim();
String contentType = mbp.getContentType();
String charSet = getCharsetFromContentType(contentType);
int sepIndex = contentType.indexOf(';');
if(sepIndex != -1)
contentType = contentType.substring(0, sepIndex).trim();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mbp.getDataHandler().writeTo(bos);
bos.close();
String content = new String(bos.toByteArray(), charSet);
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(bos.toByteArray());
fos.close();
PortletPreferences prefs = request.getPreferences();
prefs.setValue("file", fileName + "upload ok");
prefs.store();
catch(MessagingException me) {
throw new PortletException(me);
public static String getCharsetFromContentType(String contentType) {
int lastPos;
if((lastPos = contentType.indexOf(';')) == -1)
return "ISO-8859-1";
lastPos++;
String lowerContentType = contentType.toLowerCase();
int nextPos;
do {
nextPos = lowerContentType.indexOf(';', lastPos);
String param;
if(nextPos == -1)
param = lowerContentType.substring(lastPos).trim();
else
param = lowerContentType.substring(lastPos, nextPos).trim();
if(param.startsWith("charset=") && param.length() > 8)
return param.substring(8);
lastPos = nextPos + 1;
} while(nextPos != -1);
return "ISO-8859-1";
3,FormDataParser.java file
import java.io.*;
import java.util.*;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.portlet.ActionRequest;
import javax.portlet.PortletException;
public class FormDataParser {
private static final String MULTIPART_PREFIX = "multipart/";
private static final String MULTIPART_FORM_DATA = "multipart/form-data";
private static final String PLAIN_TEXT = "text/plain";
private ActionRequest mWrappedRequest;
private Map mParams;
private Map mBodyParts;
private boolean mIsInitialized;
private boolean mHasMultipart;
public FormDataParser(ActionRequest request) {
mWrappedRequest = request;
public String getParameter(String name) throws PortletException {
String value = mWrappedRequest.getParameter(name);
if(value != null)
return value;
initParameters();
if(!mHasMultipart)
return null;
List paramList = (List)mParams.get(name);
if(paramList != null)
return (String)paramList.get(0);
else
return null;
public String[] getParameterValues(String name) throws PortletException {
String values[] = mWrappedRequest.getParameterValues(name);
if(!mHasMultipart)
return values;
initParameters();
List valueList = (List)mParams.get(name);
if(valueList == null)
return values;
int size = valueList.size();
if(values != null) {
List newValueList = new ArrayList(values.length + size);
newValueList.addAll(Arrays.asList(values));
newValueList.addAll(valueList);
valueList = newValueList;
values = new String[size];
valueList.toArray(values);
return values;
public MimeBodyPart getMimeBodyPart(String name) throws PortletException {
initParameters();
if(!mHasMultipart) {
return null;
} else {
List parts = (List)mBodyParts.get(name);
return parts != null ? (MimeBodyPart)parts.get(0) : null;
public MimeBodyPart[] getMimeBodyParts(String name) throws PortletException {
initParameters();
if(!mHasMultipart)
return null;
List parts = (List)mBodyParts.get(name);
if(parts == null) {
return null;
} else {
MimeBodyPart mimeBodyParts[] = new MimeBodyPart[parts.size()];
parts.toArray(mimeBodyParts);
return mimeBodyParts;
private void initParameters() throws PortletException {
if(mIsInitialized)
return;
String contentType = mWrappedRequest.getContentType();
if(contentType == null) {
mIsInitialized = true;
return;
int sepIndex = contentType.indexOf(';');
if(sepIndex != -1)
contentType = contentType.substring(0, sepIndex).trim();
if(contentType.equalsIgnoreCase("multipart/form-data")) {
mParams = new HashMap(20);
mBodyParts = new HashMap(20);
DataSource ds = new DataSource() {
public InputStream getInputStream() throws IOException {
return mWrappedRequest.getPortletInputStream();
public OutputStream getOutputStream() throws IOException {
throw new IOException("OutputStream not available");
public String getContentType() {
return mWrappedRequest.getContentType();
public String getName() {
return getClass().getName();
try {
MimeMultipart multipartMessage = new MimeMultipart(ds);
parseMultiPart(multipartMessage, null);
catch(MessagingException me) {
throw new PortletException(me);
catch(IOException ioe) {
throw new PortletException(ioe);
mHasMultipart = true;
mIsInitialized = true;
private void parseMultiPart(MimeMultipart multipartMessage, String parentFieldName) throws MessagingException, IOException {
int partCount = multipartMessage.getCount();
for(int i = 0; i < partCount; i++) {
javax.mail.BodyPart part = multipartMessage.getBodyPart(i);
if(part instanceof MimeBodyPart) {
MimeBodyPart mimePart = (MimeBodyPart)part;
String disps[] = mimePart.getHeader("Content-Disposition");
if(disps != null && disps.length != 0) {
String disp = disps[0];
String lcDisp = disp.toLowerCase();
int nameStart;
int nameEnd;
if((nameStart = lcDisp.indexOf("name=\"")) != -1 && (nameEnd = lcDisp.indexOf("\"", nameStart + 6)) != -1)
parentFieldName = disp.substring(nameStart + 6, nameEnd);
if(parentFieldName != null)
if(mimePart.getContentType().toLowerCase().startsWith("multipart/")) {
Object content = mimePart.getContent();
if(content instanceof MimeMultipart)
parseMultiPart((MimeMultipart)content, parentFieldName);
} else
if((nameStart = lcDisp.indexOf("filename=\"")) != -1 && (nameEnd = lcDisp.indexOf("\"", nameStart + 10)) != -1) {
List values = (List)mBodyParts.get(parentFieldName);
if(values == null) {
values = new ArrayList(1);
mBodyParts.put(parentFieldName, values);
values.add(mimePart);
} else
if(mimePart.getContentType().toLowerCase().startsWith("text/plain")) {
Object content = mimePart.getContent();
if(content instanceof String) {
List values = (List)mParams.get(parentFieldName);
if(values == null) {
values = new ArrayList(1);
mParams.put(parentFieldName, values);
values.add((String)content);
4.web.xml file
<?xml version = '1.0' encoding = 'ISO-8859-1'?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>hanhuiwen OracleSamplePortlets</display-name>
<description>hanhuiwen Oracle Sample Portlet Application</description>
<servlet>
<servlet-name>portletdeploy</servlet-name>
<servlet-class>oracle.webdb.wsrp.server.deploy.PortletDeployServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>portletjaxrpc</servlet-name>
<servlet-class>com.sun.xml.rpc.server.http.JAXRPCServlet</servlet-class>
<init-param>
<param-name>configuration.file</param-name>
<param-value>/WEB-INF/WSRPService_Config.properties</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>portletresource</servlet-name>
<servlet-class>oracle.webdb.wsrp.server.ResourceServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChartServlet</servlet-name>
<display-name>Chart Servlet</display-name>
<description>Demo image-generating servlet</description>
<servlet-class>oracle.portal.portlet.sample.chart.ChartServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>uix</servlet-name>
<servlet-class>oracle.cabo.servlet.UIXServlet</servlet-class>
<init-param>
<param-name>oracle.cabo.servlet.pageBroker</param-name>
<param-value>oracle.cabo.servlet.xml.UIXPageBroker</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ChartServlet</servlet-name>
<url-pattern>/chart*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>portletjaxrpc</servlet-name>
<url-pattern>/portlets*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>portletresource</servlet-name>
<url-pattern>/portletresource*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>uix</servlet-name>
<url-pattern>*.uix</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>uix</servlet-name>
<url-pattern>/uix/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.uix</welcome-file>
</welcome-file-list>
<!--
LogLevel controls the amount of information logged. There are 7 log levels:
0 - logging disabled
1 - configuration
2 - severe error
3 - warning
4 - throwing exception
5 - performance
6 - information
7 - debug
The oracle.portal.log.Logger interface defines methods that map to these 7
log levels. However, there are also 2 methods that do not map to log
levels. These methods are included for backwards compatibility and data
logged using these methods will always be logged regardless of the log level.
-->
<env-entry>
<env-entry-name>oracle/portal/log/logLevel</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>7</env-entry-value>
</env-entry>
</web-app>
5.portlet.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd" version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd">
<portlet>
<description xml:lang="en">A portlet that demonstrates the file upload features of the Java Portlet Specification.</description>
<portlet-name>FileUpload</portlet-name>
<portlet-class>FileUploadPortlet</portlet-class>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>help</portlet-mode>
<portlet-mode>about</portlet-mode>
<portlet-mode>edit_defaults</portlet-mode>
</supports>
<supported-locale>en</supported-locale>
<portlet-info>
<title>File Upload Portlet</title>
<short-title>File Upload</short-title>
<keywords>File,Upload, Portlet</keywords>
</portlet-info>
</portlet>
<custom-portlet-mode>
<description xml:lang="en">This mode should be used by the portlet to display information on the portlet's purpose, origin, version, etc.</description>
<portlet-mode>about</portlet-mode>
</custom-portlet-mode>
<custom-portlet-mode>
<description xml:lang="en">This mode signifies that the portlet should render a screen to set the default values for the modifiable preferences that are typically changed in the EDIT screen. Calling this mode requires that the user must have administrator rights.</description>
<portlet-mode>edit_defaults</portlet-mode>
</custom-portlet-mode>
<custom-portlet-mode>
<description xml:lang="en">This mode should be used by the portlet to render output without the need of having back-end connections or user specific data available.</description>
<portlet-mode>preview</portlet-mode>
</custom-portlet-mode>
<user-attribute>
<name>user.name.given</name>
</user-attribute>
<user-attribute>
<name>user.name.family</name>
</user-attribute>
<user-attribute>
<name>user.name.middle</name>
</user-attribute>
<user-attribute>
<name>user.name.nickname</name>
</user-attribute>
<user-attribute>
<name>user.bdate</name>
</user-attribute>
<user-attribute>
<name>user.business-info.online.email</name>
</user-attribute>
</portlet-app>Hello i had exactly the same error, but not with file upload.
I'm sure you have in your application lib directory to jars which aren't compatible to each other.
And the problem occured between my myfaces and tomahawk jars .
See this page:
http://wiki.apache.org/myfaces/CompatibilityMatrix
It tells you which myfaces and tomahawk jars you can use together.
Hope it can help.
bye -
How to SCAN uploaded files for VIRUS in APEX
part 1:
Goal:
Do a virus scan of the uploaded file from APEX application prior to storing the file in custom tables.
The process:
Followed the document from www.developer.com:
Implementing an Anti-Virus File Scan in JEE Applications
By Vlad Kofman
Go to page: 1 2 3 Next
This article will discuss one of the ways to implement antivirus file scanning in Java, particular in the JEE applications. Viruses, Trojan Horses, and different malware and spyware are a real problem for current computer environments, and especially for the Windows operating system. If you are designing any application in Java that has a requirement to be able to upload external files, you have a potential security risk. By uploading, I mean any way to get the external file inside of the corporate firewall be it via HTTP protocol or any other means. It is quite common to have this type of requirement in an enterprise application and with Java being one of the most popular web development platforms, it is unfortunate that this type of gaping security risk is quite often overlooked.
Java's Development Kit (JDK) does not have any means to do the antivirus scan right out of the box. This is primarily because Java is a programming language, and does not have any virus scanning packages. Furthermore, anti-virus software is not Sun's area of expertise or business model. Developing this type of software (or Java package), and more importantly maintaining it, would be a huge task for Sun. Mainly because viruses are constantly evolving and keeping virus definitions up-to-date is a daunting task. Large companies such as McAffee, Symantec, or Zone Labs develop virus detecting and combating products and spend a lot of resources to maintain them.
Application Environment
To implement a virus file scan in Java, a third-party package needs to be used. For the purposes of this article, I will use Symantec Scan Engine (SSE) package, which comes with Java APIs. This package is an application that serves as a TCP/IP server and has a programming interface and enables Java applications to incorporate support for content scanning technologies. For this article, I used Symantec Scan Engine 5.1, which is available as a Unix or Windows install.
If you are using an anti-virus package from the different vendor, you will need to investigate what kind of APIs are available; however, the general approach should be similar. Also, note that my implementation can be used with JEE technology and any modern MVC framework such as Struts or Spring.
The architecture is as follows: A server machine needs to have SSE running at all times. This can be the same machine that hosts your Application Server, but in an enterprise environment this should be a different machine. The Default Port needs to be open through the firewall to allow communication with the scan engine. All JEE applications that need to do file scanning can talk to the SSE server machine through a default port. Also, multiple applications running on different application servers can re-use the same scanning server. For more information, you should refer to the Symantec Scan Engine (SSE) Installation Guide, available on the Symantec web site.
When an external file that needs to be scanned is sent to the SSE via its programming interface (Java APIs using the default port), before any other operation on the file is performed, the SSE returns a result code. For instance, a file is uploaded by an external user into the web email type application as an attachment; then, the SSE API is invoked by the application and the return code of pass or fail determines the outcome of the upload and whether that email can actually be sent. If you have an account on Yahoo mail, you probably have seen that Yahoo is using Norton Antivirus to scan all attachments, although no Java.
Click here for a larger image.
Figure 1: Screen shot from Yahoo
For details on the Scan Engine Server Installationm please see the Symantec Scan Engine (SSE) Implementation Guide from Symantec.
Here are some key things to remember about SSE:
• Java 2 SE Runtime (JRE) 5.0 Update 6.0 or later must be installed on the server before the SSE installation is done.
• After installation, verify that the Symantec Scan Engine daemon is running. At the Unix command prompt (if it's a Unix install), type the following command:
ps –ea | grep sym.
A list of processes similar to the following should appear:
o 5358 ? 0:00 symscan
o 5359 ? 0:00 symscan
If nothing is displayed the SSE process did not start.
If the SSE process did not start, type the following command to restart SSE:
/etc/init.d/symscan restart
• Keeping the virus definition up to date is the most important task and if new updates are not installed, the whole scan becomes ineffective. Symantec automatically downloads the most current file definitions through LiveUpdate. Please make sure that firewall rules are in place to allow the host server to connect to the Symantec update service.
Project Setup
For the purposes of this article, I included a wrapper for the Symantec SSE APIs, av.jar, which has Symantec Java APIs and serves as a client to the SSE server and takes care of all communications with the server. Please refer to the download source section. The av.jar should be included in the Java CLASSPATH to work with the SSE. This jar contains a class called AVClient that takes care of actually sending the files to SSE as byte arrays and returning the result.
In my project setting, I added three variables to be accessed via the System.getProperty mechanism. For example:
AV_SERVER_HOST=192.168.1.150
AV_SERVER_PORT=1344
AV_SERVER_MODE=SCAN
The AV_SERVER_HOST is the host name or IP of the machine where Scan Engine is installed.
The AV_SERVER_PORT is the port where Scan Engine listens for incoming files.
The AV_SERVER_MODE is the scan mode which can be:
• NOSCAN: No scanning will be done (any keyword that does not start with "SCAN" will result in ignoring the call to the Scan Engine and no files will be transferred for scanning).
• SCAN: Files or the byte stream will be scanned, but the scan engine will not try to repair infections.
• SCANREPAIR: Files will be scanned, the scan engine will try to repair infections, but nothing else will be done.
• SCANREPAIRDELETE: Files will be scanned, the scan engine will try to repair infections, and irreparable files will be deleted.
Note: For the file stream (byte array) scanning, the only meaning full values are "SCAN" and "NOSCAN".
Using the SSE Scanning Java APIs
In any class where scan is required, call the scanning API provided in the AVClient object located in the av.jar. The AVClient object will establish connection to the Scan Engine server and has the following APIs:
Figure 2: The significant APIs for the communication with to the Scan Engine Server.
If scanning a file on the file system, in SCAN only mode, use the call that accepts filename only.
If scanning a file on the file system, with SCANREPAIR or SCANREPAIRDELETE, use the call that accepts input and output file names.
If scanning an in-memory file (byte array), use the call accepting byte array.
For example:
import com.av.*;
Initialize setup parameters:
static String avMode =
(System.getProperty("AV_SERVER_MODE") != null)
? (String) System.getProperty("AV_SERVER_MODE") : "NOSCAN";
static boolean scan = avMode.startsWith("SCAN");
static String avServer =
(String) System.getProperty("AV_SERVER_HOST");
static int avPort =
Integer.parseInt( (String) System.getProperty("AV_SERVER_PORT"));
Scan check example for an in-memory file byte array:
public void scanFile(byte[] fileBytes, String fileName)
throws IOException, Exception {
if (scan) {
AVClient avc = new AVClient(avServer, avPort, avMode);
if (avc.scanfile(fileName, fileBytes) == -1) {
throw new VirusException("WARNING: A virus was detected in
your attachment: " + fileName + "<br>Please scan
your system with the latest antivirus software with
updated virus definitions and try again.");
Note that if you are using this code inside of the MVC handler, you can throw a custom VirusException and check for it in the calling method and perform any necessary cleanup. I have included the class in the AV Jar as well.
For example:
catch (Exception ex) {
logger.error(ex);
if (ex instanceof VirusException) {
// do something here
else {
// there was some other error – handle it
For more details on the Scan Engine Client API, please see Symantec Scan Engine Software Developers Guide.
Continuation in part2part 4:
c) Clienttester.java – This is the gui app set to test if the configuration is working or not. This gui uses the method scanfile(inputfile, outputfile) as you can see the result in the outputpane of the jframe.
* clienttester.java
* Created on April 12, 2005, 2:37 PM
* @author george_maculley
package com.av;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class clienttester
implements ActionListener {
// private String ipaddress = "127.0.0.1";
private String ipaddress = "199.209.150.58";
//private String ipaddress = "192.168.0.55";
static JFrame frame;
JFileChooser chooser = new JFileChooser();
TextField pathtofile = new TextField(System.getProperty("user.home"), 30);
// TextField pathtooutfile= new TextField(System.getProperty("user.home"),30);
private int port = 1344;
JButton filechooser = new JButton("Browse to file"); ;
private String originalfilename;
private String outputfilename;
JButton scanbutton = new JButton("Scan");
TextArea outputarea = new TextArea(20, 40);
TextField iptext = new TextField("127.0.0.1", 16);
TextField porttext = new TextField("1344", 5);
AVClient mine;
JRadioButton choosescan = new JRadioButton("SCAN");
// JRadioButton choosedelete= new JRadioButton("SCANREPAIRDELETE");
/** Creates a new instance of gui */
public clienttester() {
public clienttester(java.lang.String ip, java.lang.String infile, java.lang.String outfile, int port) {
this.ipaddress = ip;
this.port = port;
this.originalfilename = infile;
this.outputfilename = outfile;
boolean setValues(java.lang.String ip, java.lang.String infile, java.lang.String outfile, int port) {
this.ipaddress = ip;
this.port = port;
this.originalfilename = infile;
this.outputfilename = outfile;
return (true);
public void actionPerformed(java.awt.event.ActionEvent actionEvent) {
JComponent c = (JComponent) actionEvent.getSource();
if (c == filechooser) {
int retval = chooser.showDialog(frame, null);
if (retval == JFileChooser.APPROVE_OPTION) {
File theFile = chooser.getSelectedFile();
if (theFile != null) {
pathtofile.setText(theFile.getPath());
// pathtooutfile.setText(theFile.getPath());
JOptionPane.showMessageDialog(frame, "You chose this file: " + theFile.getPath());
if (c == scanbutton) {
//return object that can be passed to AVClient
String policy;
int thisport;
int scanresult;
String thisip;
String inputfile;
String outputfile;
outputarea.append("Server: " + iptext.getText() + "\r\n");
if (choosescan.isSelected()) {
policy = "SCAN";
else {
policy = "SCANREPAIRDELETE";
thisport = new Integer(porttext.getText()).intValue();
thisip = iptext.getText();
//mine= new AVClient(iptext.getText(),porttext.getText(),policy);
mine = new AVClient(iptext.getText(), thisport, policy);
if (mine.test() == 1) {
outputarea.append("Sorry. Incorrect parameters specified.\r\n");
System.exit(1);
else {
outputarea.append("Connection to SAVSE initialized.\r\n");
inputfile = pathtofile.getText();
// outputfile=pathtooutfile.getText();
outputfile = "/tmp";
outputarea.append("Scanning file " + inputfile + " \r\n");
if (policy == "SCAN") {
scanresult = mine.scanfile(inputfile);
else {
scanresult = mine.scanfile(inputfile, outputfile);
if (scanresult == 0) {
outputarea.append("File is clean.\r\n");
else if (scanresult == -1) {
outputarea.append("File is infected. \r\n");
else {
outputarea.append("Scan error.\r\n");
void display() {
Frame f = new Frame("SAVSE JAVA ICAP Client");
f.setLayout(new GridLayout(1, 2));
JPanel lpanel = new JPanel(new GridLayout(7, 1));
JPanel ippanel = new JPanel();
JPanel portpanel = new JPanel();
JPanel rpanel = new JPanel();
JPanel outputpanel = new JPanel();
JPanel buttonpanel = new JPanel();
JPanel pathpanel = new JPanel();
// JPanel outpathpanel= new JPanel();
JPanel policypanel = new JPanel();
ButtonGroup policygroup = new ButtonGroup();
filechooser.addActionListener(this);
scanbutton.addActionListener(this);
choosescan.setSelected(true);
policygroup.add(choosescan);
// policygroup.add(choosedelete);
buttonpanel.setBorder(BorderFactory.createTitledBorder("Scan Policy"));
buttonpanel.add(choosescan);
// buttonpanel.add(choosedelete);
pathpanel.setBorder(BorderFactory.createTitledBorder("Path to File"));
pathpanel.add(pathtofile);
f.setSize(new Dimension(650, 400));
f.setBackground(Color.white);
f.setResizable(true);
ippanel.setBorder(BorderFactory.createTitledBorder("SAVSE IP Address"));
ippanel.add(iptext);
outputpanel.setBorder(BorderFactory.createTitledBorder("OUTPUT"));
outputpanel.add(outputarea);
portpanel.setBorder(BorderFactory.createTitledBorder("ICAP Port"));
portpanel.add(porttext);
// outpathpanel.setBorder(BorderFactory.createTitledBorder("Path to Repair File"));
// outpathpanel.add(pathtooutfile);
lpanel.add(ippanel);
rpanel.add(outputpanel);
lpanel.add(portpanel);
lpanel.add(buttonpanel);
lpanel.add(pathpanel);
// lpanel.add(outpathpanel);
lpanel.add(filechooser);
lpanel.add(scanbutton);
f.add(lpanel);
f.add(rpanel);
f.setVisible(true);
public static void main(String[] args) {
clienttester g = new clienttester();
g.display();
d) my2.java – This is the class file I wrote to test that I am able to send a file and scan it and see the output in the JDEVELOPER. In this case the file is stored on the filesystem of the client machine. JDEVELOPER should be able to see the file.
NOTE:
“EICAR.com” is the test file downloaded from Symantec site to test a non malicious virus file. I n order to be able to test it like this, the Antivirus program running on your machine should be disabled, or else Antivirus will kick in and delete the file. In the first place you will not be able to download the test virus file either with anti virus running on the machine you are downloading to.
package com.av;
import java.io.*;
public class my2 {
static int my_return = 0;
* @param fileBytes
* @param fileName
* @return
public static int scanfile(String fileName){
String avMode = "SCAN";
boolean scan = avMode.startsWith("SCAN");
String avServer = "xx";--avserver ip address
int avPort = 1344;
int the_return = 0;
if (scan) {
AVClient avc = new AVClient(avServer,avPort,avMode);
the_return = avc.scanfile(fileName);
if (the_return == -1) {
return (the_return);
} else
return (the_return);
//my_return = the_return;
return (the_return);
public static void main(String[] args) throws Exception {
System.out.println("Hi there in Main");
byte[] b1 = new byte[4];
b1[1] = 68;
my_return = scanfile("c:\\eicar.com");
System.out.println(my_return);
e) Then finally we have my1.JAVA, which takes the filename, and it’s contents in the bytes form and scans the file. The reason for this method is we are not storing the file on the filesystem, it is read into the memory and only if it is clean, it is put into the database or else notify the user.
package com.av;
import java.io.*;
public class my1 {
static int my_return = 0;
static int a_length = 0;
* @param fileBytes
* @param fileName
* @return
public static int scanfile(String fileName,byte[] fileBytes) throws IOException {
String avMode = "SCAN";
boolean scan = avMode.startsWith("SCAN");
String avServer = "xxx";--avserver’s ip address
int avPort = 1344;
int the_return = 0;
if (scan) {
AVClient avc = new AVClient(avServer,avPort,avMode);
// File file = new File(fileName) ;
//byte[] fBytes = getBytesFromFile(file);
the_return = avc.scanfile(fileName, fileBytes);
if (the_return == -1) {
return (the_return);
} else
{return (the_return);}
my_return = the_return;
return (the_return);
// Returns the contents of the file in a byte array.
* @param file
* @return
* @throws IOException
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
// Close the input stream and return bytes
is.close();
return bytes;
// public static void main(String[] args) throws Exception {
//System.out.println("Hi there in Main");
// File file = new File() ;
// byte[] b1 = getBytesFromFile(file);
//System.out.println(b1);
// my_return = scanfile(,b1);
//System.out.println(my_return); }
Finally , you have the exceptions file,
e) package com.av;
public class VirusException
extends Exception {
public VirusException() {
super();
public VirusException(String text) {
super(text);
Once you have all these classes, you can use JDEVELOPER , to load these classes into the database: This is as follows:
Right click on the project, which has all these classes.
NEW -> deployment profiles -> load java and stored procedures.
When you are created deployment profile, you have to specify,
Loadjava options.
-f, -v (check the check boxes)
Under privileges:
-s – specify database schema these classes are loaded into
-s – create sysnonym check box
-g – grant to public or any specific users per your policy.
Under Resolver,
-r and –o (check the check boxes)
I accepted the default name storedproc1. Then you right click on the storedproc1.deploy, deploy to whichever database connection you created.
And then, In order to access this java class we need a pl/sql wrapper as follows:
create or replace package my1 is
function mycheck (pfilename in varchar2, psize in number)
return number;
end my1;
create or replace package body my1 is
function mycheck (pfilename in varchar2, psize in number)
return number is
language java
name 'com.av.my1.scanfile(java.lang.String, byte[]) return int';
end my1;
And the code is invoked from sql plus as follows:
Select my1.mycheck(“filename”, “filebytes”) from dual;
One important catch in the above method is to send the filename and filecontents in bytes form. In order to send the file contents as filebytes, you will need another java class and load into the data base as described above.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
* This program demonstrates how to read a file into a byte array. This method
* reads the entire contents of the file into a byte array.
* @version 1.0
* @author Jeffrey M. Hunter ([email protected])
* @author http://www.idevelopment.info
public class ReadFileIntoByteArray {
* method to convert a byte to a hex string.
* @param data the byte to convert
* @return String the converted byte
public static String byteToHex(byte data) {
StringBuffer buf = new StringBuffer();
buf.append(toHexChar((data >>> 4) & 0x0F));
buf.append(toHexChar(data & 0x0F));
return buf.toString();
* Convenience method to convert an int to a hex char.
* @param i the int to convert
* @return char the converted char
public static char toHexChar(int i) {
if ((0 <= i) && (i <= 9)) {
return (char) ('0' + i);
} else {
return (char) ('a' + (i - 10));
* Returns the contents of the file in a byte array
* @param file File this method should read
* @return byte[] Returns a byte[] array of the contents of the file
private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
System.out.println("\nDEBUG: FileInputStream is " + file);
// Get the size of the file
long length = file.length();
System.out.println("DEBUG: Length of " + file + " is " + length + "\n");
* You cannot create an array using a long type. It needs to be an int
* type. Before converting to an int type, check to ensure that file is
* not loarger than Integer.MAX_VALUE;
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large to process");
return null;
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while ( (offset < bytes.length)
( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
is.close();
return bytes;
* @param filename
public static byte[] chk_file(String filename) {
byte[] fileArray = null;
try {
fileArray = getBytesFromFile(new File( filename));
} catch (IOException e) {
e.printStackTrace();
if (fileArray != null) {
for (int i=0; i<fileArray.length; i++) {
System.out.println(
"fileArray[" + i + "] = " +
((int)fileArray[i] < 9 ? " " : "") +
( ((int)fileArray[i] > 9 && (int)fileArray[i] <= 99) ? " " : "") +
fileArray[i] + " : " +
" HEX=(0x" + byteToHex(fileArray) + ") : " +
" charValue=(" + (char)fileArray[i] + ")");
return fileArray;
* Sole entry point to the class and application.
* @param args Array of String arguments.
public static void main(String[] args) {
byte[] fileArray = null;
try {
fileArray = getBytesFromFile(new File("c:\\eicar.com"));
} catch (IOException e) {
e.printStackTrace();
if (fileArray != null) {
for (int i=0; i<fileArray.length; i++) {
System.out.println(
"fileArray[" + i + "] = " +
((int)fileArray[i] < 9 ? " " : "") +
( ((int)fileArray[i] > 9 && (int)fileArray[i] <= 99) ? " " : "") +
fileArray[i] + " : " +
" HEX=(0x" + byteToHex(fileArray[i]) + ") : " +
" charValue=(" + (char)fileArray[i] + ")");
Having main method helps you to run the file in JDEVELOPER or using JAVA.
DO not forget to load this class into the database.
And you create the pl/sql wrapper again as follows:
create or replace FUNCTION TOBY (pfilename in varchar2) RETURN VARCHAR2 iS
language java name
'ReadFileIntoByteArray.chk_file(java.lang.String) return byte[]';
And you call the function from sqlplus as follows:
Sql>Set serveroutput on size 20000;
Sql> call dbms_java.set_output(20000);
Sql> Select toby(“filename”) from dual; --
this file should be accessible, I mean you will not be able to send a file on your pc, from sql plus as sql/plus is running on your db server.
You will be able to see the output in sql plus:
If you are running it from the APEX:
When we use file browser widget from APEX, the file is stored in APEX_APPLICATION_FILES table. And we retrieve that into a variable and pass this variable to the function as follows:
DECLARE
scan_failed EXCEPTION;
x varchar2(400);
z number;
BEGIN
select filename into x from wwv_flow_files where name = :P1_FILE_NAME;
select my1.mycheck(x,toby(x)) into z from dual;
if z = 0 then
:P1_SUBJECT:= 'PASSED';
else
:P1_SUBJECT:= 'FAILED';
end if;
:P1_SCAN_RESULT := '** Scanning File **';
IF UPPER(:P1_SUBJECT) = 'PASSED' THEN
BEGIN
:P1_SCAN_FLAG := 'PASSED';
:P1_SCAN_RESULT := :P1_SCAN_RESULT || ' ** File passed scan **';
END;
ELSIF UPPER(:P1_SUBJECT) = 'FAILED' THEN
BEGIN
:P1_SCAN_FLAG := 'FAILED';
:P1_SCAN_RESULT := :P1_SCAN_RESULT || ' ** File failed scan **';
END;
ELSE
BEGIN
:P1_SCAN_FLAG := 'UNKNOWN';
:P1_SCAN_RESULT := :P1_SCAN_RESULT || ' ** Scan Is Not Conclussive **';
END;
END IF;
--IF :P1_SCAN_FLAG = 'FAILED'
-- THEN RAISE scan_failed;
--END IF;
EXCEPTION
WHEN OTHERS THEN
DELETE from APEX_APPLICATION_FILES WHERE name = :P1_FILE_NAME;
RAISE_APPLICATION_ERROR (-20000, 'seb OTHERS error encountered - file upload not allowed. Possible virus detected !');
raise;
END;
ACKNOWLEDMENTS:
1) JOHN SCOTT – who suggested this ICAP API in one of the threads which is my initial starting point in this direction.
2) VLAD KOFMAN who wrote the article on WWW.DEVELOPER.com
3) Mr. KIRAN –One of the engineers from Metalink, who helped me at every step of getting this java programs and pl/sql wrappers working. But for him, I would have not completed my project. -
Hello everyone. I am having trouble writing a utility that uses SharePoint web services to upload a file and metatag it. It keeps throwing the following error message:
"The request failed with the error message: -- <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="/_forms/default.aspx?ReturnUrl=%2fsites%2fgk%2f_vti_bin%2fcopy.asmx">here</a>.</h2>
</body></html> --."
Not sure why. I pass the file that I am going to upload to the subroutine and it is suppose to upload it to the appropriate library. I have burned several days on this problem and I am not sure what is going on. I would appreciate anyone that can point me in
the right direction. Below is the subroutine that I have that is causing the problem. Obviously, I have stripped the name from the example.
Thanks
Mike
******** <Begin snip of code> **********************
Public Shared Sub CreateNewDocumentWithCopyService(ByVal fileName As String)
Dim c As New copyservice.Copy
c.PreAuthenticate = True
c.Credentials = New System.Net.NetworkCredential("[email protected]", "mypassword")
c.Url = "https://x.sharepoint.com/sites/gk/_vti_bin/copy.asmx"
Dim myBinary As Byte() = System.IO.File.ReadAllBytes(fileName)
Dim destination As String = "https://x.sharepoint.com/sites/gk/Gatekeeper%20Reference/" & System.IO.Path.GetFileName(fileName)
Dim destinationUrl As String() = {destination}
Dim info1 As New copyservice.FieldInformation
info1.DisplayName = "Title"
info1.InternalName = "Title"
info1.Type = copyservice.FieldType.Text
info1.Value = "new title"
Dim info2 As New copyservice.FieldInformation
info2.DisplayName = "Modified By"
info2.InternalName = "Editor"
info2.Type = copyservice.FieldType.User
info2.Value = "-1;#servername\\testmoss"
Dim info As copyservice.FieldInformation() = {info1, info2}
Dim resultTest As New copyservice.CopyResult
Dim result As copyservice.CopyResult() = {resultTest}
Try
' When creating new content use the same URL in the SourceURI as in the Destination URL argument
c.CopyIntoItems(destination, destinationUrl, info, myBinary, result)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
******** <End snip of code> **********************Hi,
If you want to upload a file to a library in SharePoint 2013 online, I suggest you use Client Object Model or REST API.
The code snippets in the two threads below will be helpful:
http://social.technet.microsoft.com/Forums/sharepoint/en-US/deac7cb7-c677-47b0-acdc-c56b32dfaac8/uploading-bigger-files-using-csom
http://stackoverflow.com/questions/17057074/how-to-download-upload-files-from-to-sharepoint-2013-using-csom
Uploading Files Using the REST API
http://blogs.msdn.com/b/uksharepoint/archive/2013/04/20/uploading-files-using-the-rest-api-and-client-side-techniques.aspx
You can handle the authentication with
SharePointOnlineCredentials object:
http://www.vrdmn.com/2013/01/authenticating-net-client-object-model.html
Best regards
Patrick Liang
TechNet Community Support -
How can i Upload Files from my Flex 2.0 Application?
How can i do a Upload File funtionality with Flex 2.0? Do i
have to make the component? How is the code in Flex/ Action Script
to make this possible?. I'm new in this Flex world and it seems to
me very interesting to make RIA's Applications; in fact i'm making
a little Employees Application for my company and i'm trying this
technology and of course i need the functionality that i asking
for.
Regards.
Andres.I haven't tried this, but I believe what you could do is
append
requestHeaders to the urlrequest object that you pass into
the file.upload()
method. The requestHeaders is an array of name/value pairs
that would be
included with your post. At least in theory, I believe that
shoudl work.
Good luck.
Phil
"tantalo" <[email protected]> wrote in
message
news:e3q3mt$138$[email protected]..
> Hi. Phil, how i commented in the forum the examples
works ok, with a
> little
> changes to make a file Upload. Now i have another doubt,
i need to make a
> submit of a form with another fields and the file
selected.
>
> I made a HHTP Service for that purpose with the tags
Requests like:
>
> <mx:HTTPService id="empleadoRequest"
> url="
http://andresbarrios:8080/directorio/empleados/insertarEmpleado.jsp"
> useProxy="false" method="POST">
> <mx:request xmlns="">
>
<empresa>{empresa.selectedItem.data}</empresa>
>
<ubicacion>{ubicacion.selectedItem.data}</ubicacion>
>
<departamento>{departamento.selectedItem.data}</departamento>
> <cedula>{cedula.text}</cedula>
> <nombre>{nombre.text}</nombre>
> <apellido>{apellido.text}</apellido>
> <!--Falta Fecha de Nacimiento -->
> <sexo>{sexo.selectedItem.data}</sexo>
>
<estado_civil>{estado_civil.selectedItem.data}</estado_civil>
>
<telefono_celular>{telefono_celular.text}</telefono_celular>
> <extension>{extension.text}</extension>
>
<correo_electronico>{correo_electronico.text}</correo_electronico>
> </mx:request>
> </mx:HTTPService>
> I have the global variable called "file" that contains
the file selected.
> I
> want to send this file variable in the HHTPservice call
EmpleadoRequest,
> can i
> do that with a Request tag like another field? or the
only way is trougth:
> file.upload(upload.cfm) ?;
>
> I want only make a one call to the server to submit the
fields of the form
> and
> to upload the file at th e same time can you help me How
can i do that?
>
> Thanks.
>
> Regards.
>
> Andres.
>
>
> -
Problem in creating a callable object of type Business Logic
Hi SDN,
I am trying to create a callable object of type Business Logic in CE.
When I give all information and click Next, I get this error message.
Error while loading configuration dialog: Failed to create delegate for component com.sap.caf.eu.gp.ui.co.CExpConfig. (Hint: Is the corresponding DC deployed correctly? Does the DC contain the component?)
Can anybody help me out with this problem.
Regards,
SumangalaHi.
I'm having the same problem as Senthil in NW2004s SP15 with my application service and methods not showing up in the Callable Object wizard for Composite Application Services after I choose the Endpoint. The only application name that shows up in the wizard is caf.tc, and the only service names that show up for it are LDDataAccessor, Metadata, and PropPermissionService.
My IDE is on one machine and the application server I deploy to is located on a different machine. My endpoint to the remote application server looks to be correctly configured. The Composite Application Service seems to be deployed properly as I'm able to see it and test that it works in the Web Services Navigator <http://remotehost:50000/wsnavigator/>
My deployed application service is a remote enabled service and is also web services enabled as well.
I'm not sure if this is relevant, but I noticed that the generated Java code does not create any remote EJB interfaces (only home and local interfaces were generated).
Something else I noticed is that when I proceed to the External Service Configuration -> Business Entities screen <http://remotehost:50000/webdynpro/dispatcher/sap.com/cafUIconfiguration>, I only see three business entities displayed, and the following error message is displayed: "Corrupt metadata has been detected. This may prevent some objects from being displayed. Check the server log for more details." I was unable to find anything in the instance log files. Is the error message indicative of the problem?
I am developing locally without a NetWeaver Development Infrastructure (NWDI) in place.
I'm wondering if the credentials specified in the endpoint require any special roles or privileges.
Senthil, do any of these additional descriptions apply to you as well?
Edited by: Ric Leeds on Jun 20, 2008 4:37 PM -
Error building/creating WD Callable Object
Hello guys,
Pardon for reposting - I did post on the WD Java thread - and I think this is the more appropriate area to ask this question since its GP Callable Objects related.
While creating a WD Callable Object: I
I added Used DC: caf/eu/gp/api/wd to the WD DC. And added IGPWebdynproCO on the Implemented Interface. Afterwards, after building the DC, I got the following errors:
This compilation unit indirectly references the missing type com.sap.caf.eu.gp.co.api.IGPTechnicalDescription (typically some required class file is referencing a type outside the classpath)
The project was not built since its classpath is incomplete. Cannot find the class file for com.sap.caf.eu.gp.co.api.IGPTechnicalDescription. Fix the classpath then try rebuilding this project.
I tried repair and rebuild - and restared NWDS (and even restarted my PC).
Issue not resolved.
What else should I do?
Thanks!
Regards,
JanI solve this including DC from caf/eu/gp/api (external public part) as show
http://help.sap.com/saphelp_nw70/helpdata/en/43/e085d6421a4d9de10000000a155369/content.htm
Later the method getDescription throws error because not return anything, while I return null
Regards, -
Error testing Web Dynpro Callable Object (GP Interface)
With reference to thread:
Interactive form as Callable object error on testing the object.
FYI, I'm running NW04s, EP 7.0 SPS 13, JDK 1.4.2_14, Unix OS
Hi All,
I have created a Web Dynpro App with a Adobe Form as the frontend. I have included the caf/eu/gp/api as a DC and implemented the IGPWebDynproCO interface. Next I created a Web Dynpro Callable object in GP and ran a test and received the following error:
Result: Technical Exception
Details: Could not create web dynpro callable object component
Output Parameters
Callable object implementation did not return output parameters
Can anyone help me resolve this? Do I have to make a manual entry in the HOST file? If so, what is that entry? Are there alternatives?
Thanks
Kunal.Hi,
For creating WD callable object you need to add following three DC in your WD DC project.
In the Web Dynpro Explorer of the Web Dynpro Perspective, expand the node DC MetaData -> DC Definition, and select Used DCs.
a. To create a DC dependency, open the context menu and choose Add Used DC.
b. Select Local Development -> SAP-EU -> caf/eu/gp/api/wd -> DC MetaData -> Public Parts -> GPWebDynproCO. For Dependency Type, select Build Time, Design Time, and Run Time. Choose weak from the dropdown list.
c. Repeat the previous step to define a dependency to DCs SAP-EU-> caf/eu/gp/api (public part external) and SAP-JEE -> com.sap.security.api.sda (public part default).
You need to do one more thing like bellow.
Select your Web Dynpro project and open its context menu. Choose Properties.
1. Choose Web Dynpro References -> Library References.
2. Add a reference for library caf/eu/gp/api.
I think this will help you.
Thanks
Chandan
Maybe you are looking for
-
Photosmart 7520 - Non-HP Cartridge Message
As of today, I have received 4,874 "Non-HP Cartridge(s)" messages from HP. I consider this out and out harassment rather than reminders to use HP cartridges in the printer. I am using Office Depot cartridges because the local Office Depot was out o
-
Possibility to auto-storno consequent FI-document coming from MM (4.6C)?
Hi, it seems my question is not to be posted right here, but it is concerned to some abap-ing, so perhaps this is the place where to ask. Scenario is: We have Invoice Receipt (from MM) with consequent FI-document. For some reason we have to storno th
-
DG Setup Perfect, Running Ok, Yet One Unique Issue, Need Ur Intervention!
Hi Experts, Version : 11.2.03 Box : AIX 5l Active Passive RAC Node: Standby : StandAlone DR ================== I am stuck in some silly situation, where I setup my DG and everything went fine. My DG is in complete sync with Primary. The archives are
-
Hi All, I have encountered some code which takes a somewhat different approach to event handling that I have used previously. This is a basic example of the principles: private final static String = "CMD_ONE"; private final static String = "CMD_
-
Approach of using Bulk Collect
Hi Experts, how to use bulk collect for uncertain number of columns of select statement. Master table structure: Create table tabmst (id number, cls_input varchar2(2000), price number); insert into tabmst(1,'select product, price from product',500);