List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java
public int createDocument(HttpServletResponse response, String library, FileItem item) throws UnrecognizedValueTypeException, ShareServerException { // System.out.println("createDocument: uri='" + uri + "'"); //SharepointResource sharepointResource = new SharepointResource(uri); // String filename = resource.getSource(); // //from w w w .j a va2 s. c o m // OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10)) // .properties(OProperties.string("Name", filename)) // .properties(OProperties.string("ContentType","Document")) // .properties(OProperties.string("Title","Architecture")) // .properties(OProperties.string("ApprovalStatus","2")) // .properties(OProperties.string("Path","/Empire")) // .execute(); // no obvious API in odata4j to create a document, default apache http Create HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); BufferedReader br = null; int returnCode = 500; PostMethod method = null; try { client.setConnectionTimeout(8000); method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library); String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword(); String encoding = Base64.encodeBase64String(userPassword.getBytes()); encoding = encoding.replaceAll("\r\n?", ""); method.setRequestHeader("Authorization", "Basic " + encoding); method.addRequestHeader("Content-type", item.getContentType()); method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName()); //InputStream is = new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc"); RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword"); method.setRequestEntity(entity); method.setDoAuthentication(true); returnCode = client.executeMethod(method); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); // still consume the response body method.getResponseBodyAsString(); } else { //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); InputStream is = method.getResponseBodyAsStream(); //br = new BufferedReader(new InputStreamReader(is)); // String readLine; // while(((readLine = br.readLine()) != null)) { // System.out.println(readLine); // } response.setContentType("text/html"); //response.setContentType("application/atom+xml"); //response.setContentLength(is.getBytes().length); response.setStatus(IConstants.SC_OK); //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>"); //response.getWriter().write(method.getResponseBodyAsString()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(is); Element root = doc.getDocumentElement(); System.out.println("Root element of the doc is " + root.getNodeName()); // String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices"; // String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; String id = null; String name = null; NodeList nl = root.getElementsByTagName("d:Id"); if (nl.getLength() > 0) { id = nl.item(0).getFirstChild().getNodeValue(); } //nl = root.getElementsByTagName("d:ContentType"); //if (nl.getLength() > 0) { // type = nl.item(0).getFirstChild().getNodeValue(); //} nl = root.getElementsByTagName("d:Name"); if (nl.getLength() > 0) { name = nl.item(0).getFirstChild().getNodeValue(); } response.getWriter().write("<html>"); response.getWriter().write("<head>"); response.getWriter().write("</head>"); response.getWriter().write("<body>"); response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>"); response.getWriter().write("</body>"); response.getWriter().write("</html>"); //response.getWriter().write(is.content); //String readLine; //while(((readLine = br.readLine()) != null)) { // response.getWriter().write(readLine); //} //response.setContentType(IConstants.CT_XML); //response.getWriter().write(is.toString()); //response.setStatus(IConstants.SC_OK); //test // String readLine; // while(((readLine = br.readLine()) != null)) { // System.out.println(readLine); // } } } catch (Exception e) { System.err.println(e); e.printStackTrace(); } finally { if (method != null) method.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { } } return returnCode; }
From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServiceHandler.java
/** * Treats the request as a post request which contains the file to be * uploaded. Uses the apache commons fileupload library to * extract the file from the request, attaches a {@link FileUploadListener} to * get notified about the progress and writes the file content * to the given {@link FileUploadStorageItem} * @param request Request object, must not be null * @param fileUploadStorageitem Object where the file content is set to. * If null, nothing happens.//from w ww . j a v a 2s . c om * @param uploadProcessId Each upload action has a unique process identifier to * match subsequent polling calls to get the progress correctly to the uploaded file. * */ private void handleFileUpload(final HttpServletRequest request, final FileUploadStorageItem fileUploadStorageitem, final String uploadProcessId) { // Ignore upload requests which have no valid widgetId if (fileUploadStorageitem != null && uploadProcessId != null && !"".equals(uploadProcessId)) { // Create file upload factory and upload servlet // You could use new DiskFileItemFactory(threshold, location) // to configure a custom in-memory threshold and storage location. // By default the upload files are stored in the java.io.tmpdir FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Create a file upload progress listener final ProgressListener listener = new ProgressListener() { public void update(final long aBytesRead, final long aContentLength, final int anItem) { fileUploadStorageitem.updateProgress(aBytesRead, aContentLength); } }; // Upload servlet allows to set upload listener upload.setProgressListener(listener); fileUploadStorageitem.setUploadProcessId(uploadProcessId); FileItem fileItem = null; try { final List uploadedItems = upload.parseRequest(request); // Only one file upload at once is supported. If there are multiple files, take // the first one and ignore other if (uploadedItems.size() > 0) { fileItem = (FileItem) uploadedItems.get(0); // Don't check for file size 0 because this prevents uploading new empty office xp documents // which have a file size of 0. if (!fileItem.isFormField()) { fileUploadStorageitem.setFileInputStream(fileItem.getInputStream()); fileUploadStorageitem.setContentType(fileItem.getContentType()); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } } }
From source file:org.ecocean.servlet.AdoptionAction.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String adopterName = ""; String adopterAddress = ""; String adopterEmail = ""; String adopterImage;/*from www . j ava 2 s.c om*/ String adoptionStartDate = ""; String adoptionEndDate = ""; String adopterQuote = ""; String adoptionManager = ""; String shark = ""; String encounter = ""; String notes = ""; String adoptionType = ""; String number = ""; String text = ""; // Saved to the selected shark, not the adoption. String newNickName = ""; // Storing the customer ID here makes the subscription cancellation process easier to do in less moves. String stripeCustomerID = ""; // Stores some wack response string from google recaptcha. String gresp = ""; boolean adoptionSuccess = true; String failureMessage = ""; //set UTF-8 request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(true); String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("AdoptionAction.class"); System.out.println("in context " + context); //request.getSession()getServlet().getServletContext().getRealPath("/")); String rootDir = getServletContext().getRealPath("/"); System.out.println("rootDir=" + rootDir); // This value is only stored in the email specific edit form. Boolean emailEdit = false; if ((Boolean) session.getAttribute("emailEdit") != false) { emailEdit = (Boolean) session.getAttribute("emailEdit"); number = (String) session.getAttribute("sessionAdoptionID"); } //setup data dir String rootWebappPath = getServletContext().getRealPath("/"); File webappsDir = new File(rootWebappPath).getParentFile(); File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context)); //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();} File adoptionsDir = new File(shepherdDataDir.getAbsolutePath() + "/adoptions"); if (!adoptionsDir.exists()) { adoptionsDir.mkdirs(); } //get the form to read data from // AdoptionForm theForm = (AdoptionForm) form; //set up for response response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean locked = false; String fileName = "None"; String username = "None"; String fullPathFilename = ""; String id = ""; boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end) String doneMessage = ""; List<String> filesOK = new ArrayList<String>(); HashMap<String, String> filesBad = new HashMap<String, String>(); List<FileItem> formFiles = new ArrayList<FileItem>(); Calendar date = Calendar.getInstance(); long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context); long maxSizeBytes = maxSizeMB * 1048576; //set form value hashmap HashMap fv = new HashMap(); //else { id = "adpt" + (new Integer(date.get(Calendar.DAY_OF_MONTH))).toString() + (new Integer(date.get(Calendar.MONTH) + 1)).toString() + (new Integer(date.get(Calendar.YEAR))).toString() + (new Integer(date.get(Calendar.HOUR_OF_DAY))).toString() + (new Integer(date.get(Calendar.MINUTE))).toString() + (new Integer(date.get(Calendar.SECOND))).toString(); //} System.out.println("Starting an adoption submission..."); Calendar todayDate = Calendar.getInstance(); if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); List<FileItem> multiparts = upload.parseRequest(request); //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (item.isFormField()) { //plain field fv.put(item.getFieldName(), ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")"); } else { //file //System.out.println("content type???? " + item.getContentType()); TODO note, the helpers only check extension if (item.getSize() > maxSizeBytes) { filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB"); } else if (myShepherd.isAcceptableImageFile(item.getName()) || myShepherd.isAcceptableVideoFile(item.getName())) { formFiles.add(item); filesOK.add(item.getName()); } else { filesBad.put(item.getName(), "invalid type of file"); } } } doneMessage = "File Uploaded Successfully"; fileSuccess = true; } catch (Exception ex) { doneMessage = "File Upload Failed due to " + ex; } } else { doneMessage = "Sorry this Servlet only handles file upload request"; } session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray()))); String badmsg = ""; for (String key : filesBad.keySet()) { badmsg += key + " (" + getVal(filesBad, key) + ") "; } if (badmsg.equals("")) { badmsg = "none"; } session.setAttribute("filesBadMessage", badmsg); boolean isEdit = false; if (fileSuccess) { if ((fv.get("number") != null) && !fv.get("number").toString().equals("")) { //handle adoption number processing number = fv.get("number").toString(); if ((number != null) && (!number.equals(""))) { isEdit = true; System.out.println("Ping! Hit adoption number recieved by action servlet."); //myShepherd.beginDBTransaction(); } //end adoption number/id processing } if ((fv.get("adopterName") != null) && !fv.get("adopterName").toString().equals("")) { adopterName = fv.get("adopterName").toString().trim(); } if ((fv.get("adopterAddress") != null) && !fv.get("adopterAddress").toString().equals("")) { adopterAddress = fv.get("adopterAddress").toString().trim(); } if ((fv.get("adopterEmail") != null) && !fv.get("adopterEmail").toString().equals("")) { adopterEmail = fv.get("adopterEmail").toString().trim(); } if ((fv.get("adoptionStartDate") != null) && !fv.get("adoptionStartDate").toString().equals("")) { adoptionStartDate = fv.get("adoptionStartDate").toString().trim(); } if ((fv.get("adoptionEndDate") != null) && !fv.get("adoptionEndDate").toString().equals("")) { adoptionEndDate = fv.get("adoptionEndDate").toString().trim(); } if ((fv.get("adopterQuote") != null) && !fv.get("adopterQuote").toString().equals("")) { adopterQuote = fv.get("adopterQuote").toString().trim(); } if ((fv.get("adoptionManager") != null) && !fv.get("adoptionManager").toString().equals("")) { adoptionManager = fv.get("adoptionManager").toString().trim(); } if ((fv.get("shark") != null) && !fv.get("shark").toString().equals("")) { shark = fv.get("shark").toString().trim(); } if ((fv.get("encounter") != null) && !fv.get("encounter").toString().equals("")) { encounter = fv.get("encounter").toString().trim(); } if ((fv.get("notes") != null) && !fv.get("notes").toString().equals("")) { notes = fv.get("notes").toString().trim(); } if ((fv.get("adoptionType") != null) && !fv.get("adoptionType").toString().equals("")) { adoptionType = fv.get("adoptionType").toString().trim(); } if ((fv.get("text") != null) && !fv.get("text").toString().equals("")) { text = fv.get("text").toString().trim(); } // New nickname to save to marked individual object. if ((fv.get("newNickName") != null) && !fv.get("newNickName").toString().equals("")) { newNickName = fv.get("newNickName").toString().trim(); } if ((fv.get("g-recaptcha-response") != null) && !fv.get("g-recaptcha-response").toString().equals("")) { gresp = fv.get("g-recaptcha-response").toString().trim(); } if (isEdit) { id = number; } // Grab the stripe customer out of session. stripeCustomerID = (String) session.getAttribute("stripeID"); File thisAdoptionDir = new File(adoptionsDir.getAbsolutePath() + "/" + id); if (!thisAdoptionDir.exists()) { thisAdoptionDir.mkdirs(); } String baseDir = ServletUtilities.dataDir(context, rootDir); ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>(); for (FileItem item : formFiles) { /* this will actually write file to filesystem (or [FUTURE] wherever) TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc. */ //try { //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir); //SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir); try { //retrieve the file data ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stream = item.getInputStream(); //System.out.println(writeFile); //if ((!(file[iter].getFileName().equals(""))) && (file[iter].getFileSize() > 0)) { //write the file to the file specified //String writeName=file[iter].getFileName().replace('#', '_').replace('-', '_').replace('+', '_').replaceAll(" ", "_"); //String writeName=forHTMLTag(file[iter].getFileName()); String writeName = "adopter.jpg"; //String writeName=URLEncoder.encode(file[iter].getFileName(), "UTF-8"); //while (writeName.indexOf(".") != writeName.lastIndexOf(".")) { // writeName = writeName.replaceFirst("\\.", "_"); // } //System.out.println(writeName); OutputStream bos = new FileOutputStream(new File(thisAdoptionDir, writeName)); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); //data = "The file has been written to \"" + id + "\\" + writeName + "\""; adopterImage = writeName; // } //close the stream stream.close(); baos.close(); } catch (FileNotFoundException fnfe) { System.out.println("File not found exception.\n"); fnfe.printStackTrace(); //return null; } catch (IOException ioe) { System.out.println("IO Exception.\n"); ioe.printStackTrace(); //return null; } } // This verifies the user being logged in or passing the recapture. boolean loggedIn = false; try { if (request.getUserPrincipal() != null) { loggedIn = true; } } catch (NullPointerException ne) { System.out.println("Got a null pointer checking for logged in user."); } boolean validCaptcha = false; if (loggedIn != true) { String remoteIP = request.getRemoteAddr(); validCaptcha = ServletUtilities.captchaIsValid(context, gresp, remoteIP); System.out.println("Results from captchaIsValid(): " + validCaptcha); } if ((validCaptcha == true) || (loggedIn == true)) { System.out.println("Ping! Hit the Adoption creation section."); try { Adoption ad = new Adoption(id, adopterName, adopterEmail, adoptionStartDate, adoptionEndDate); if (isEdit || emailEdit) { ad = myShepherd.getAdoption(number); ad.setAdopterName(adopterName); ad.setAdopterEmail(adopterEmail); ad.setAdoptionEndDate(adoptionEndDate); ad.setAdoptionStartDate(adoptionStartDate); } ad.setAdopterQuote(adopterQuote); ad.setAdoptionManager(adoptionManager); ad.setIndividual(shark); ad.setEncounter(encounter); ad.setNotes(notes); ad.setAdoptionType(adoptionType); ad.setAdopterAddress(adopterAddress); ad.setStripeCustomerId(stripeCustomerID); if ((filesOK != null) && (filesOK.size() > 0)) { ad.setAdopterImage(filesOK.get(0)); } myShepherd.beginDBTransaction(); if (adoptionSuccess && !isEdit) { try { myShepherd.storeNewAdoption(ad, id); } catch (Exception e) { adoptionSuccess = false; failureMessage += "Failed to presist the new adoption.<br>"; } } // New logic to change marked individual nickname if necessary in adoption. MarkedIndividual mi = myShepherd.getMarkedIndividual(shark); if (!newNickName.equals("")) { if (adoptionSuccess && !isEdit) { try { mi.setNickName(newNickName); mi.setNickNamer(adopterName); } catch (Exception e) { failureMessage += "Retrieving shark to set nickname failed.<br>"; } } } // Sends a confirmation email to a a new adopter with cancellation and update information. if (emailEdit == false) { try { String emailContext = "context0"; String langCode = "en"; String to = ad.getAdopterEmail(); String type = "adoptionConfirmation"; System.out.println("About to email new adopter."); // Retrieve background service for processing emails ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService(); Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, mi, ad); NotificationMailer mailer = new NotificationMailer(emailContext, langCode, to, type, tagMap); NotificationMailer adminMailer = new NotificationMailer(emailContext, langCode, CommonConfiguration.getNewSubmissionEmail(emailContext), type, tagMap); es.execute(mailer); es.execute(adminMailer); } catch (Exception e) { System.out.println("Error in sending email confirmation of adoption."); e.printStackTrace(); } } if ((adoptionSuccess && isEdit) || (emailEdit == true)) { myShepherd.commitDBTransaction(); } } catch (Exception e) { System.out.println("The recaptcha passed but something went wrong saving the adoption."); e.printStackTrace(); } } } // Sets adoption paid to false to allow multiple adoptions session.setAttribute("paid", false); //return a forward to display.jsp System.out.println("Ending adoption data submission."); //if((submitterID!=null)&&(submitterID.equals("deepblue"))) { if ((adoptionSuccess) && (emailEdit == false)) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/adoptionSuccess.jsp?id=" + id); } else if ((adoptionSuccess) && (emailEdit == true)) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/editSuccess.jsp"); } else { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/adoptionFailure.jsp?message=" + failureMessage); } //} myShepherd.closeDBTransaction(); }
From source file:org.ejbca.ui.web.admin.cainterface.CAInterfaceBean.java
public byte[] parseRequestParameters(HttpServletRequest request, Map<String, String> requestMap) throws IOException { byte[] fileBuffer = null; try {/* w w w . java 2 s . co m*/ if (ServletFileUpload.isMultipartContent(request)) { final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(59999); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setSizeMax(60000); final List<FileItem> items = upload.parseRequest(request); for (final FileItem item : items) { if (item.isFormField()) { final String fieldName = item.getFieldName(); final String currentValue = requestMap.get(fieldName); if (currentValue != null) { requestMap.put(fieldName, currentValue + ";" + item.getString("UTF8")); } else { requestMap.put(fieldName, item.getString("UTF8")); } } else { //final String itemName = item.getName(); final InputStream file = item.getInputStream(); byte[] fileBufferTmp = FileTools.readInputStreamtoBuffer(file); if (fileBuffer == null && fileBufferTmp.length > 0) { fileBuffer = fileBufferTmp; } } } } else { final Set<String> keySet = request.getParameterMap().keySet(); for (final String key : keySet) { requestMap.put(key, request.getParameter(key)); } } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (FileUploadException e) { throw new IOException(e); } return fileBuffer; }
From source file:org.ejbca.ui.web.admin.hardtokeninterface.EditHardTokenProfileJSPHelper.java
public String parseRequest(HttpServletRequest request) throws AuthorizationDeniedException { String includefile = PAGE_HARDTOKENPROFILES; String profile = null;// w w w. ja v a2 s. c om HardTokenProfileDataHandler handler = hardtokenbean.getHardTokenProfileDataHandler(); String action = null; InputStream file = null; boolean buttonupload = false; String filename = null; try { RequestHelper.setDefaultCharacterEncoding(request); } catch (UnsupportedEncodingException e1) { // ignore } if (ServletFileUpload.isMultipartContent(request)) { try { final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(1999999); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setSizeMax(2000000); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { if (item.getFieldName().equals(ACTION)) { action = item.getString(); } if (item.getFieldName().equals(HIDDEN_HARDTOKENPROFILENAME)) { profilename = item.getString(); } if (item.getFieldName().equals(BUTTON_CANCEL)) { // do nothing } if (item.getFieldName().equals(BUTTON_UPLOADFILE)) { buttonupload = true; } } else { file = item.getInputStream(); filename = item.getName(); } } } catch (IOException e) { fileuploadfailed = true; includefile = PAGE_HARDTOKENPROFILE; } catch (FileUploadException e) { fileuploadfailed = true; includefile = PAGE_HARDTOKENPROFILE; } } else { action = request.getParameter(ACTION); } if (action != null) { if (action.equals(ACTION_EDIT_HARDTOKENPROFILES)) { if (request.getParameter(BUTTON_EDIT_HARDTOKENPROFILES) != null) { // Display profilepage.jsp profile = request.getParameter(SELECT_HARDTOKENPROFILES); if (profile != null) { if (!profile.trim().equals("")) { includefile = PAGE_HARDTOKENPROFILE; this.profilename = profile; this.profiledata = handler.getHardTokenProfile(profilename); } else { profile = null; } } if (profile == null) { includefile = PAGE_HARDTOKENPROFILES; } } if (request.getParameter(BUTTON_DELETE_HARDTOKENPROFILES) != null) { // Delete profile and display profilespage. profile = request.getParameter(SELECT_HARDTOKENPROFILES); if (profile != null) { if (!profile.trim().equals("")) { hardtokenprofiledeletefailed = handler.removeHardTokenProfile(profile); } } includefile = PAGE_HARDTOKENPROFILES; } if (request.getParameter(BUTTON_RENAME_HARDTOKENPROFILES) != null) { // Rename selected profile and display profilespage. String newhardtokenprofilename = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME); String oldhardtokenprofilename = request.getParameter(SELECT_HARDTOKENPROFILES); if (oldhardtokenprofilename != null && newhardtokenprofilename != null) { if (!newhardtokenprofilename.trim().equals("") && !oldhardtokenprofilename.trim().equals("")) { try { handler.renameHardTokenProfile(oldhardtokenprofilename.trim(), newhardtokenprofilename.trim()); } catch (HardTokenProfileExistsException e) { hardtokenprofileexists = true; } } } includefile = PAGE_HARDTOKENPROFILES; } if (request.getParameter(BUTTON_ADD_HARDTOKENPROFILES) != null) { // Add profile and display profilespage. profile = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME); if (profile != null) { if (!profile.trim().equals("")) { try { if (!handler.addHardTokenProfile(profile.trim(), new SwedishEIDProfile())) { profilemalformed = true; } } catch (HardTokenProfileExistsException e) { hardtokenprofileexists = true; } } } includefile = PAGE_HARDTOKENPROFILES; } if (request.getParameter(BUTTON_CLONE_HARDTOKENPROFILES) != null) { // clone profile and display profilespage. String newhardtokenprofilename = request.getParameter(TEXTFIELD_HARDTOKENPROFILESNAME); String oldhardtokenprofilename = request.getParameter(SELECT_HARDTOKENPROFILES); if (oldhardtokenprofilename != null && newhardtokenprofilename != null) { if (!newhardtokenprofilename.trim().equals("") && !oldhardtokenprofilename.trim().equals("")) { try { handler.cloneHardTokenProfile(oldhardtokenprofilename.trim(), newhardtokenprofilename.trim()); } catch (HardTokenProfileExistsException e) { hardtokenprofileexists = true; } } } includefile = PAGE_HARDTOKENPROFILES; } } if (action.equals(ACTION_EDIT_HARDTOKENPROFILE)) { // Display edit access rules page. profile = request.getParameter(HIDDEN_HARDTOKENPROFILENAME); if (profile != null) { if (!profile.trim().equals("")) { if (request.getParameter(BUTTON_SAVE) != null || request.getParameter(BUTTON_UPLOADENVELOPETEMP) != null || request.getParameter(BUTTON_UPLOADVISUALTEMP) != null || request.getParameter(BUTTON_UPLOADRECEIPTTEMP) != null || request.getParameter(BUTTON_UPLOADADRESSLABELTEMP) != null) { if (profiledata == null) { String tokentype = request.getParameter(HIDDEN_HARDTOKENTYPE); if (tokentype.equals(TYPE_SWEDISHEID)) { profiledata = new SwedishEIDProfile(); } if (tokentype.equals(TYPE_ENCHANCEDEID)) { profiledata = new EnhancedEIDProfile(); } if (tokentype.equals(TYPE_TURKISHEID)) { profiledata = new TurkishEIDProfile(); } } // Save changes. // General settings String value = request.getParameter(TEXTFIELD_SNPREFIX); if (value != null) { value = value.trim(); profiledata.setHardTokenSNPrefix(value); } value = request.getParameter(CHECKBOX_EREASBLE); if (value != null) { profiledata.setEreasableToken(value.equals(CHECKBOX_VALUE)); } else { profiledata.setEreasableToken(false); } value = request.getParameter(SELECT_NUMOFTOKENCOPIES); if (value != null) { profiledata.setNumberOfCopies(Integer.parseInt(value)); } value = request.getParameter(CHECKBOX_USEIDENTICALPINS); if (value != null) { profiledata.setGenerateIdenticalPINForCopies(value.equals(CHECKBOX_VALUE)); } else { profiledata.setGenerateIdenticalPINForCopies(false); } if (profiledata instanceof HardTokenProfileWithPINEnvelope) { value = request.getParameter(SELECT_ENVELOPETYPE); if (value != null) { ((HardTokenProfileWithPINEnvelope) profiledata) .setPINEnvelopeType(Integer.parseInt(value)); } value = request.getParameter(SELECT_NUMOFENVELOPECOPIES); if (value != null) { ((HardTokenProfileWithPINEnvelope) profiledata) .setNumberOfPINEnvelopeCopies(Integer.parseInt(value)); } value = request.getParameter(TEXTFIELD_VISUALVALIDITY); if (value != null) { ((HardTokenProfileWithPINEnvelope) profiledata) .setVisualValidity(Integer.parseInt(value)); } } if (profiledata instanceof HardTokenProfileWithVisualLayout) { HardTokenProfileWithVisualLayout visprof = (HardTokenProfileWithVisualLayout) profiledata; value = request.getParameter(SELECT_VISUALLAYOUTTYPE); if (value != null) { visprof.setVisualLayoutType(Integer.parseInt(value)); } } if (profiledata instanceof HardTokenProfileWithReceipt) { value = request.getParameter(SELECT_RECEIPTTYPE); if (value != null) { ((HardTokenProfileWithReceipt) profiledata) .setReceiptType(Integer.parseInt(value)); } value = request.getParameter(SELECT_NUMOFRECEIPTCOPIES); if (value != null) { ((HardTokenProfileWithReceipt) profiledata) .setNumberOfReceiptCopies(Integer.parseInt(value)); } } if (profiledata instanceof HardTokenProfileWithAdressLabel) { value = request.getParameter(SELECT_ADRESSLABELTYPE); if (value != null) { ((HardTokenProfileWithAdressLabel) profiledata) .setAdressLabelType(Integer.parseInt(value)); } value = request.getParameter(SELECT_NUMOFADRESSLABELCOPIES); if (value != null) { ((HardTokenProfileWithAdressLabel) profiledata) .setNumberOfAdressLabelCopies(Integer.parseInt(value)); } } if (profiledata instanceof SwedishEIDProfile) { SwedishEIDProfile sweprof = (SwedishEIDProfile) profiledata; value = request.getParameter(SELECT_MINKEYLENGTH); if (value != null) { int val = Integer.parseInt(value); sweprof.setMinimumKeyLength(SwedishEIDProfile.CERTUSAGE_SIGN, val); sweprof.setMinimumKeyLength(SwedishEIDProfile.CERTUSAGE_AUTHENC, val); sweprof.setKeyType(SwedishEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA); sweprof.setKeyType(SwedishEIDProfile.CERTUSAGE_AUTHENC, EIDProfile.KEYTYPE_RSA); } value = request.getParameter(CHECKBOX_CERTWRITABLE); if (value != null) { sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_SIGN, value.equals(CHECKBOX_VALUE)); sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_AUTHENC, value.equals(CHECKBOX_VALUE)); } else { sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_SIGN, false); sweprof.setCertWritable(SwedishEIDProfile.CERTUSAGE_AUTHENC, false); } value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0"); if (value != null) { sweprof.setCertificateProfileId(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "0"); if (value != null) { sweprof.setCAId(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "0"); if (value != null) { sweprof.setPINType(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "0"); if (value != null) { sweprof.setMinimumPINLength(SwedishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1"); if (value != null) { sweprof.setCertificateProfileId(SwedishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "1"); if (value != null) { sweprof.setCAId(SwedishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "1"); if (value != null) { sweprof.setPINType(SwedishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "1"); if (value != null) { sweprof.setMinimumPINLength(SwedishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } } if (profiledata instanceof TurkishEIDProfile) { TurkishEIDProfile turkprof = (TurkishEIDProfile) profiledata; value = request.getParameter(SELECT_MINKEYLENGTH); if (value != null) { int val = Integer.parseInt(value); turkprof.setMinimumKeyLength(TurkishEIDProfile.CERTUSAGE_SIGN, val); turkprof.setMinimumKeyLength(TurkishEIDProfile.CERTUSAGE_AUTHENC, val); turkprof.setKeyType(TurkishEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA); turkprof.setKeyType(TurkishEIDProfile.CERTUSAGE_AUTHENC, EIDProfile.KEYTYPE_RSA); } value = request.getParameter(CHECKBOX_CERTWRITABLE); if (value != null) { turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_SIGN, value.equals(CHECKBOX_VALUE)); turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_AUTHENC, value.equals(CHECKBOX_VALUE)); } else { turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_SIGN, false); turkprof.setCertWritable(TurkishEIDProfile.CERTUSAGE_AUTHENC, false); } value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0"); if (value != null) { turkprof.setCertificateProfileId(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "0"); if (value != null) { turkprof.setCAId(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "0"); if (value != null) { turkprof.setPINType(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "0"); if (value != null) { turkprof.setMinimumPINLength(TurkishEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1"); if (value != null) { turkprof.setCertificateProfileId(TurkishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "1"); if (value != null) { turkprof.setCAId(TurkishEIDProfile.CERTUSAGE_AUTHENC, Integer.parseInt(value)); } } if (profiledata instanceof EnhancedEIDProfile) { EnhancedEIDProfile enhprof = (EnhancedEIDProfile) profiledata; value = request.getParameter(SELECT_MINKEYLENGTH); if (value != null) { int val = Integer.parseInt(value); enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_SIGN, val); enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_AUTH, val); enhprof.setMinimumKeyLength(EnhancedEIDProfile.CERTUSAGE_ENC, val); enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_SIGN, EIDProfile.KEYTYPE_RSA); enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_ENC, EIDProfile.KEYTYPE_RSA); enhprof.setKeyType(EnhancedEIDProfile.CERTUSAGE_ENC, EIDProfile.KEYTYPE_RSA); } value = request.getParameter(CHECKBOX_CERTWRITABLE); if (value != null) { enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_SIGN, value.equals(CHECKBOX_VALUE)); enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_AUTH, value.equals(CHECKBOX_VALUE)); enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_ENC, value.equals(CHECKBOX_VALUE)); } else { enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_SIGN, false); enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_AUTH, false); enhprof.setCertWritable(EnhancedEIDProfile.CERTUSAGE_ENC, false); } value = request.getParameter(SELECT_CERTIFICATEPROFILE + "0"); if (value != null) { enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "0"); if (value != null) { enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "0"); if (value != null) { enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "0"); if (value != null) { enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_SIGN, Integer.parseInt(value)); } enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_SIGN, false); value = request.getParameter(SELECT_CERTIFICATEPROFILE + "1"); if (value != null) { enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "1"); if (value != null) { enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "1"); if (value != null) { enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "1"); if (value != null) { enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_AUTH, Integer.parseInt(value)); } enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_AUTH, false); value = request.getParameter(SELECT_CERTIFICATEPROFILE + "2"); if (value != null) { enhprof.setCertificateProfileId(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_CA + "2"); if (value != null) { enhprof.setCAId(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_PINTYPE + "2"); if (value != null) { enhprof.setPINType(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value)); } value = request.getParameter(SELECT_MINPINLENGTH + "2"); if (value != null) { enhprof.setMinimumPINLength(EnhancedEIDProfile.CERTUSAGE_ENC, Integer.parseInt(value)); } value = request.getParameter(CHECKBOX_KEYRECOVERABLE + "2"); if (value != null) { enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_ENC, value.equals(CHECKBOX_VALUE)); } else { enhprof.setIsKeyRecoverable(EnhancedEIDProfile.CERTUSAGE_ENC, false); } value = request.getParameter(CHECKBOX_REUSEOLDCERT + "2"); if (value != null) { enhprof.setReuseOldCertificate(EnhancedEIDProfile.CERTUSAGE_ENC, value.equals(CHECKBOX_VALUE)); } else { enhprof.setReuseOldCertificate(EnhancedEIDProfile.CERTUSAGE_ENC, false); } } if (request.getParameter(BUTTON_SAVE) != null) { if (!handler.changeHardTokenProfile(profile, profiledata)) { profilemalformed = true; } includefile = PAGE_HARDTOKENPROFILES; } if (request.getParameter(BUTTON_UPLOADENVELOPETEMP) != null) { uploadmode = UPLOADMODE_ENVELOPE; includefile = PAGE_UPLOADTEMPLATE; } if (request.getParameter(BUTTON_UPLOADVISUALTEMP) != null) { uploadmode = UPLOADMODE_VISUAL; includefile = PAGE_UPLOADTEMPLATE; } if (request.getParameter(BUTTON_UPLOADRECEIPTTEMP) != null) { uploadmode = UPLOADMODE_RECEIPT; includefile = PAGE_UPLOADTEMPLATE; } if (request.getParameter(BUTTON_UPLOADADRESSLABELTEMP) != null) { uploadmode = UPLOADMODE_ADRESSLABEL; includefile = PAGE_UPLOADTEMPLATE; } } if (request.getParameter(BUTTON_CANCEL) != null) { // Don't save changes. includefile = PAGE_HARDTOKENPROFILES; } } } } if (action.equals(ACTION_CHANGE_PROFILETYPE)) { this.profilename = request.getParameter(HIDDEN_HARDTOKENPROFILENAME); String value = request.getParameter(SELECT_HARDTOKENTYPE); if (value != null) { int profiletype = Integer.parseInt(value); EIDProfile newprofile = null; switch (profiletype) { case SwedishEIDProfile.TYPE_SWEDISHEID: newprofile = new SwedishEIDProfile(); break; case EnhancedEIDProfile.TYPE_ENHANCEDEID: newprofile = new EnhancedEIDProfile(); break; case TurkishEIDProfile.TYPE_TURKISHEID: newprofile = new TurkishEIDProfile(); break; } if (profiledata != null && profiledata instanceof EIDProfile) { ((EIDProfile) profiledata).clone(newprofile); newprofile.reInit(); profiledata = newprofile; } } includefile = PAGE_HARDTOKENPROFILE; } if (action.equals(ACTION_UPLOADENVELOPETEMP)) { if (buttonupload) { if (profiledata instanceof IPINEnvelopeSettings) { try { BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8")); String filecontent = ""; String nextline = ""; while (nextline != null) { nextline = br.readLine(); if (nextline != null) { filecontent += nextline + "\n"; } } ((IPINEnvelopeSettings) profiledata).setPINEnvelopeData(filecontent); ((IPINEnvelopeSettings) profiledata).setPINEnvelopeTemplateFilename(filename); fileuploadsuccess = true; } catch (IOException ioe) { fileuploadfailed = true; } } } includefile = PAGE_HARDTOKENPROFILE; } if (action.equals(ACTION_UPLOADVISUALTEMP)) { if (profiledata instanceof IVisualLayoutSettings) { try { BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8")); String filecontent = ""; String nextline = ""; while (nextline != null) { nextline = br.readLine(); if (nextline != null) { filecontent += nextline + "\n"; } } ((IVisualLayoutSettings) profiledata).setVisualLayoutData(filecontent); ((IVisualLayoutSettings) profiledata).setVisualLayoutTemplateFilename(filename); fileuploadsuccess = true; } catch (IOException ioe) { fileuploadfailed = true; } } includefile = PAGE_HARDTOKENPROFILE; } if (action.equals(ACTION_UPLOADRECEIPTTEMP)) { if (profiledata instanceof IReceiptSettings) { try { BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8")); String filecontent = ""; String nextline = ""; while (nextline != null) { nextline = br.readLine(); if (nextline != null) { filecontent += nextline + "\n"; } } ((IReceiptSettings) profiledata).setReceiptData(filecontent); ((IReceiptSettings) profiledata).setReceiptTemplateFilename(filename); fileuploadsuccess = true; } catch (IOException ioe) { fileuploadfailed = true; } } includefile = PAGE_HARDTOKENPROFILE; } if (action.equals(ACTION_UPLOADADRESSLABELTEMP)) { if (profiledata instanceof IAdressLabelSettings) { try { BufferedReader br = new BufferedReader(new InputStreamReader(file, "UTF8")); String filecontent = ""; String nextline = ""; while (nextline != null) { nextline = br.readLine(); if (nextline != null) { filecontent += nextline + "\n"; } } ((IAdressLabelSettings) profiledata).setAdressLabelData(filecontent); ((IAdressLabelSettings) profiledata).setAdressLabelTemplateFilename(filename); fileuploadsuccess = true; } catch (IOException ioe) { fileuploadfailed = true; } } includefile = PAGE_HARDTOKENPROFILE; } } return includefile; }
From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java
public byte[] getfileBuffer(HttpServletRequest request, Map<String, String> requestMap) throws IOException, FileUploadException { byte[] fileBuffer = null; if (ServletFileUpload.isMultipartContent(request)) { final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(59999); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setSizeMax(60000);// w w w . j a v a 2 s . c om final List<FileItem> items = upload.parseRequest(request); for (final FileItem item : items) { if (item.isFormField()) { final String fieldName = item.getFieldName(); final String currentValue = requestMap.get(fieldName); if (currentValue != null) { requestMap.put(fieldName, currentValue + ";" + item.getString("UTF8")); } else { requestMap.put(fieldName, item.getString("UTF8")); } } else { importedProfileName = item.getName(); final InputStream file = item.getInputStream(); byte[] fileBufferTmp = FileTools.readInputStreamtoBuffer(file); if (fileBuffer == null && fileBufferTmp.length > 0) { fileBuffer = fileBufferTmp; } } } } else { final Set<String> keySet = request.getParameterMap().keySet(); for (final String key : keySet) { requestMap.put(key, request.getParameter(key)); } } return fileBuffer; }
From source file:org.elissa.server.EPCUpload.java
/** * The POST request./*from w w w.j ava 2 s . com*/ */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { // No isMultipartContent => Error final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req); if (!isMultipartContent) { printError(res, "No Multipart Content transmitted."); return; } // Get the uploaded file final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(-1); final List<?> items; try { items = servletFileUpload.parseRequest(req); if (items.size() != 1) { printError(res, "Not exactly one File."); return; } } catch (FileUploadException e) { handleException(res, e); return; } final FileItem fileItem = (FileItem) items.get(0); // Get filename and content (needed to distinguish between EPML and AML) final String fileName = fileItem.getName(); String content = fileItem.getString(); // Get the input stream final InputStream inputStream; try { inputStream = fileItem.getInputStream(); } catch (IOException e) { handleException(res, e); return; } // epml2eRDF XSLT source final String xsltFilename = getServletContext().getRealPath("/xslt/EPML2eRDF.xslt"); // final String xsltFilename = System.getProperty("catalina.home") + "/webapps/oryx/xslt/EPML2eRDF.xslt"; final File epml2eRDFxsltFile = new File(xsltFilename); final Source epml2eRDFxsltSource = new StreamSource(epml2eRDFxsltFile); // Transformer Factory final TransformerFactory transformerFactory = TransformerFactory.newInstance(); // Get the epml source final Source epmlSource; if (fileName.endsWith(".epml") || content.contains("http://www.epml.de")) { epmlSource = new StreamSource(inputStream); } else { printError(res, "No EPML or AML file uploaded."); return; } // Get the result string String resultString = null; try { Transformer transformer = transformerFactory.newTransformer(epml2eRDFxsltSource); StringWriter writer = new StringWriter(); transformer.transform(epmlSource, new StreamResult(writer)); resultString = writer.toString(); } catch (Exception e) { handleException(res, e); return; } if (resultString != null) { try { printResponse(res, resultString); } catch (Exception e) { handleException(res, e); return; } } }
From source file:org.etudes.mneme.tool.UploadXml.java
/** * Accept a file upload from the user./* w ww . ja va 2 s.c o m*/ * * @param file * The file. */ public void setUpload(FileItem file) { try { String fileName = file.getName(); String extension = (fileName != null && fileName.lastIndexOf('.') != -1) ? fileName.substring(fileName.lastIndexOf('.') + 1) : null; // parse into a doc if ("xml".equals(extension)) { this.upload = Xml.readDocumentFromStream(file.getInputStream()); this.unzipLocation = ""; } else if ("zip".equals(extension)) { this.unzipLocation = unpackageZipFile(fileName, file); this.upload = Xml.readDocument(unzipLocation + File.separator + "imsmanifest.xml"); } } catch (IOException e) { } catch (Exception e) { } }
From source file:org.etudes.tool.melete.AddResourcesPage.java
public String addItems() { byte[] secContentData; String secResourceName;/*from w w w . j a va2 s . com*/ String secContentMimeType; FacesContext context = FacesContext.getCurrentInstance(); ResourceLoader bundle = new ResourceLoader("org.etudes.tool.melete.bundle.Messages"); String addCollId = getMeleteCHService().getUploadCollectionId(); //Code that validates required fields int emptyCounter = 0; String linkValue, titleValue; boolean emptyLinkFlag = false; boolean emptyTitleFlag = false; err_fields = null; if (this.fileType.equals("upload")) { for (int i = 1; i <= 10; i++) { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi == null || fi.getName() == null || fi.getName().length() == 0) { emptyCounter = emptyCounter + 1; } } if (emptyCounter == 10) { FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; } /* try { if (emptyCounter == 10) throw new MeleteException("all_uploads_empty"); } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage (null, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); return "failure"; } */ for (int i = 1; i <= 10; i++) { try { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { //validate fileName Util.validateUploadFileName(fi.getName()); validateFileSize(fi.getSize()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(secContentData); secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); if (logger.isDebugEnabled()) logger.debug( "new names for upload content is" + secContentMimeType + "," + secResourceName); addItem(secResourceName, secContentMimeType, addCollId, secContentData); if (success_fields == null) success_fields = new ArrayList<String>(); success_fields.add(new Integer(i).toString()); success_fields.add(bundle.getString("add_item_success") + secResourceName); } else { logger.debug("File being uploaded is NULL"); continue; } } catch (MeleteException mex) { String mexMsg = mex.getMessage(); if (mex.getMessage().equals("embed_img_bad_filename")) mexMsg = "img_bad_filename"; String errMsg = bundle.getString(mexMsg); // context.addMessage ("FileUploadForm:chooseFile"+i, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); // logger.error("error in uploading multiple files" + errMsg); if (err_fields == null) err_fields = new ArrayList<String>(); err_fields.add(new Integer(i).toString()); err_fields.add(errMsg); //return "failure"; } catch (Exception e) { logger.debug("file upload FAILED" + e.toString()); } } if (err_fields != null) { logger.debug("err found in fields" + err_fields.toString()); return "file_upload_view"; } } if (this.fileType.equals("link")) { Iterator utIterator = utList.iterator(); //Finish validating here int count = -1; while (utIterator.hasNext()) { count++; try { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); if (utObj.title != null) utObj.title = utObj.title.trim(); String linkUrl = utObj.getUrl(); if (linkUrl != null) linkUrl = linkUrl.trim(); String checkUrl = linkUrl; if (checkUrl != null) { checkUrl = checkUrl.replace("http://", ""); checkUrl = checkUrl.replace("https://", ""); } if ((utObj.title == null || utObj.title.length() == 0) && (checkUrl == null || checkUrl.length() == 0)) { utIterator.remove(); continue; } if (utObj.title == null || utObj.title.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":title", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_title_reqd", bundle.getString("URL_title_reqd"))); return "#"; } if (checkUrl == null || checkUrl.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":url", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_reqd", bundle.getString("URL_reqd"))); return "#"; } Util.validateLink(linkUrl); } catch (UserErrorException uex) { String errMsg = bundle.getString(uex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "add_section_bad_url_formats", bundle.getString("add_section_bad_url_formats"))); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } utIterator = utList.iterator(); while (utIterator.hasNext()) { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); try { secContentMimeType = getMeleteCHService().MIME_TYPE_LINK; String linkUrl = utObj.getUrl(); secResourceName = utObj.getTitle(); if ((linkUrl != null) && (linkUrl.trim().length() > 0) && (secResourceName != null) && (secResourceName.trim().length() > 0)) { secContentData = new byte[linkUrl.length()]; secContentData = linkUrl.getBytes(); addItem(secResourceName, secContentMimeType, addCollId, secContentData); } } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, mex.getMessage(), errMsg)); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } } FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; }
From source file:org.etudes.tool.melete.ExportMeleteModules.java
/** * writes the file to disk/*from w ww. j av a2 s.c om*/ * * @param fileItem * Fileitem * @param outputFile * out put file * @throws FileNotFoundException * @throws IOException */ private void writeFileToDisk(FileItem fileItem, File outputFile) throws FileNotFoundException, IOException { FileInputStream in = null; FileOutputStream out = null; try { in = (FileInputStream) fileItem.getInputStream(); out = new FileOutputStream(outputFile); int len; byte buf[] = new byte[102400]; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { throw e; } catch (IOException e) { throw e; } finally { try { if (in != null) in.close(); } catch (IOException e1) { } try { if (out != null) out.close(); } catch (IOException e2) { } } }