Java Code Examples for org.apache.commons.fileupload.FileItem#getInputStream()

The following examples show how to use org.apache.commons.fileupload.FileItem#getInputStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParseUploadUtil.java    From S-mall-servlet with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @param request Servlet请求
 * @param params 一个预备的键值表储存非文件流的参数Map
 * @return 上传的文件流
 */
public static InputStream parseUpload(HttpServletRequest request, Map<String,String> params){
    InputStream is = null;
    try{
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        factory.setSizeThreshold(10*1024*1024);
        List<FileItem> items= upload.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                is = item.getInputStream();
            } else {
                String paramName = item.getFieldName();
                String paramValue = item.getString();
                paramValue = new String(paramValue.getBytes("ISO-8859-1"), "UTF-8");
                params.put(paramName, paramValue);
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return is;
}
 
Example 2
Source File: FrameServletHandler.java    From urule with Apache License 2.0 6 votes vote down vote up
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	boolean overwriteProject=true;
	List<FileItem> items = upload.parseRequest(req);
	if(items.size()==0){
		throw new ServletException("Upload file is invalid.");
	}
	for(FileItem item:items){
		String name=item.getFieldName();
		if(name.equals("overwriteProject")){
			String overwriteProjectStr=new String(item.get());
			overwriteProject=Boolean.valueOf(overwriteProjectStr);
		}else if(name.equals("file")){
			inputStream=item.getInputStream();
		}
	}
	repositoryService.importXml(inputStream,overwriteProject);
	IOUtils.closeQuietly(inputStream);
	resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
 
Example 3
Source File: PackageServletHandler.java    From urule with Apache License 2.0 6 votes vote down vote up
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory=new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	List<FileItem> items = upload.parseRequest(req);
	Iterator<FileItem> itr = items.iterator();
	List<Map<String,Object>> mapData=null;
	while (itr.hasNext()) {
		FileItem item = (FileItem) itr.next();
		String name=item.getFieldName();
		if(!name.equals("file")){
			continue;
		}
		InputStream stream=item.getInputStream();
		mapData=parseExcel(stream);
		httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
		stream.close();
		break;
	}
	httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
	writeObjectToJson(resp, mapData);
}
 
Example 4
Source File: VirtualHostManagerController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private static void validateKubeconfig(String context,
                                       FileItem kubeconfig) throws IOException {
    Map<String, Object> map;
    try (InputStream fi = kubeconfig.getInputStream()) {
        map = new Yaml().loadAs(fi, Map.class);
    }
    List<Map<String, Object>> contexts = (List<Map<String, Object>>)map.get("contexts");
    String currentUser = contexts.stream()
            .filter(ctx -> context.equals(ctx.get("name")))
            .map(ctx -> (Map<String, String>)ctx.get("context"))
            .map(attrs -> attrs.get("user"))
            .findFirst()
            .orElseThrow(() ->
                    new IllegalArgumentException("user missing for context " +
                            context));
    ((List<Map<String, Object>>)map.get("users"))
            .stream()
            .filter(usr -> currentUser.equals(usr.get("name")))
            .map(usr -> (Map<String, Object>)usr.get("user"))
            .filter(data -> data.get("client-certificate") != null ||
                    data.get("client-key") != null)
            .findAny()
            .ifPresent(data -> {
                throw new IllegalStateException(
                        "client certificate and key must be embedded for user '" +
                        currentUser + "'");
            });
}
 
Example 5
Source File: Oper.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param request
 * @param response 
 */
private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
if (PDLog.isDebug())
    PDLog.Debug("InsFile");
FileItem ItemFile=null;    
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileData=item.getInputStream();
        ItemFile=item;
        }
    }
DriverGeneric PDSession=getSessOPD(Req);
String Id=(String) ListFields.get("Id");
String Ver=(String) ListFields.get("Ver");
PDSession.InsertFile(Id, Ver, FileData);
if (FileData!=null)
    FileData.close();
if (ItemFile!=null)
    ItemFile.delete();
items.clear(); // to help and speed gc
PrintWriter out = response.getWriter(); 
Answer(Req, out, true, null, null);
out.close();
}
 
Example 6
Source File: WebServlet.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Handle file upload requests.
 * 
 * @param req
 * @param res
 */
protected void postUpload(HttpServletRequest req, HttpServletResponse res)
{
	String path = req.getPathInfo();
	log.debug("path {}", path);
	if (path == null) path = "";
	// assume caller has verified that it is a request for content and that it's multipart
	// loop over attributes in request, picking out the ones
	// that are file uploads and doing them
	for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();)
	{
		String iname = (String) e.nextElement();
		log.debug("Item {}", iname);
		Object o = req.getAttribute(iname);
		// NOTE: Fileitem is from
		// org.apache.commons.fileupload.FileItem, not
		// sakai's parameterparser version
		if (o != null && o instanceof FileItem)
		{
			FileItem fi = (FileItem) o;
			try (InputStream inputStream = fi.getInputStream())
			{
				if (!writeFile(fi.getName(), fi.getContentType(), inputStream, path, req, res, true)) return;
			} catch (IOException ioe) {
				log.warn("Problem getting InputStream", ioe);
			}
		}
	}
}
 
Example 7
Source File: CommonsImageMultipartFile.java    From validator-web with Apache License 2.0 5 votes vote down vote up
protected BufferedImage readImage(FileItem file) throws IOException {
    InputStream in = file.getInputStream();
    if (in == null) {
        return null;
    }
    return ImageIO.read(in);
}
 
Example 8
Source File: ImportDocRIS.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);      
    String ParentId=ListFields.get("CurrFold");    
    String RISType=ListFields.get("RISType");    
    PDDocsRIS D=new PDDocsRIS(SParent.getSessOPD(Req), RISType);
    D.ImportFileRIS(ParentId, FileData);    
    out.println(UpFileStatus.SetResultOk(Req, ""));
    FileData.close();
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 9
Source File: ContribRes.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
static synchronized private String GenHtml(HttpServletRequest Req, DriverGeneric LocalSess, ContribConf ConfContrib, PDFolders FoldUser) throws Exception
{
String HtmlFinal;   
String Agent=Req.getHeader("User-Agent");
String DimHtml=ConfContrib.SolveHtmlRes(Agent);
if (DimHtml!=null) 
    {
    HtmlFinal=getHtml(LocalSess, DimHtml);
    }
else
    HtmlFinal=HtmlBase;
if (ConfContrib.getFormContribCSS()!=null)
    {
    if (ConfContrib.getFormContribCSS().startsWith("http"))    
       HtmlFinal=HtmlFinal.replace("@CSS@", "<link rel=\"STYLESHEET\" type=\"text/css\" href=\""+ConfContrib.getFormContribCSS()+"\"/>");
    else
       HtmlFinal=HtmlFinal.replace("@CSS@", GenCSS(LocalSess, ConfContrib.getFormContribCSS()));
    }
else
    HtmlFinal=HtmlFinal.replace("@CSS@", "");
if (!ServletFileUpload.isMultipartContent(Req))
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:NO File<div>");    
    return(HtmlFinal);
    }
String NameDocT=null;
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(ConfContrib.getMaxSize());
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        {
        if (item.getFieldName().equals("CONTRIB_DT"))    
            NameDocT=item.getString("UTF-8");
        else
            {
            ListFields.put(item.getFieldName(), item.getString("UTF-8"));
            }
        }
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!ConfContrib.IsAllowedExt(FileName.substring(FileName.lastIndexOf(".")+1)))
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:Not Allowed extension<div>");    
    return(HtmlFinal);
    }
PDDocs DocTmp=new PDDocs(LocalSess, NameDocT);
DocTmp.setName(FileName);
DocTmp.setStream(FileData);
Record AttrDef = DocTmp.getRecSum();
for (Map.Entry<String, String> entry : ListFields.entrySet())
    {
    if (AttrDef.getAttr(entry.getKey())!=null);
        AttrDef.getAttr(entry.getKey()).Import(entry.getValue());
    }
DocTmp.assignValues(AttrDef);
DocTmp.setParentId(FoldUser.getPDId());
DocTmp.setACL(FoldUser.getACL());
try {
DocTmp.insert();
HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESOK\">"+ConfContrib.getOKMsg()+"</div>");
HtmlFinal=HtmlFinal.replace("CONTRIBRETRYKO", "CONTRIBRETRYOK");
} catch (Exception Ex)
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:"+Ex.getLocalizedMessage()+"<div>");    
    }
return(HtmlFinal);
}
 
Example 10
Source File: AddDocAdv.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean AddDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException
{
String FileName=null;
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }
String Acept=(String) ListFields.get("BOk");
if (Acept==null || Acept.length()==0)
    return(false);
DriverGeneric PDSession=SParent.getSessOPD(Req);
String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
PDDocs Doc;
if (DType==null)
    Doc = new PDDocs(PDSession);
else
    Doc = new PDDocs(PDSession, DType);
Record Rec=Doc.getRecSum();
Rec.initList();
Attribute Attr=Rec.nextAttr();
while (Attr!=null)
    {
    if (!List.contains(Attr.getName()))
        {
        String Val=(String) ListFields.get(Attr.getName());
        if (Attr.getType()==Attribute.tBOOLEAN)
            {
            if(Val == null)
                Attr.setValue(false);
            else
                Attr.setValue(true);
            }
        else if(Val != null)
            {
            SParent.FillAttr(Req, Attr, Val, false);
            }
        }
    Attr=Rec.nextAttr();
    }
Doc.assignValues(Rec);
Doc.setParentId(getActFolderId(Req));
String RefFile=(String) ListFields.get(PDDocs.fNAME+"_");
if (RefFile!=null && RefFile.length()!=0)
    {
    Doc.setFile(RefFile);
    }
else
    {
    Doc.setName(FileName);
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    }
Doc.insert();
return(true);
}
 
Example 11
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 4 votes vote down vote up
/**
 * 创建 multipart 请求参数列表
 */
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
    // 定义参数列表
    List<Object> paramList = new ArrayList<Object>();
    // 创建两个对象,分别对应 普通字段 与 文件字段
    Map<String, Object> fieldMap = new HashMap<String, Object>();
    List<Multipart> multipartList = new ArrayList<Multipart>();
    // 获取并遍历表单项
    List<FileItem> fileItemList;
    try {
        fileItemList = fileUpload.parseRequest(request);
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // 异常转换(抛出自定义异常)
        throw new UploadException(e);
    }
    for (FileItem fileItem : fileItemList) {
        // 分两种情况处理表单项
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // 处理普通字段
            String fieldValue = fileItem.getString(FrameworkConstant.UTF_8);
            fieldMap.put(fieldName, fieldValue);
        } else {
            // 处理文件字段
            String fileName = FileUtil.getRealFileName(fileItem.getName());
            if (StringUtil.isNotEmpty(fileName)) {
                long fileSize = fileItem.getSize();
                String contentType = fileItem.getContentType();
                InputStream inputSteam = fileItem.getInputStream();
                // 创建 Multipart 对象,并将其添加到 multipartList 中
                Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                multipartList.add(multipart);
            }
        }
    }
    // 初始化参数列表
    paramList.add(new Params(fieldMap));
    paramList.add(new Multiparts(multipartList));
    // 返回参数列表
    return paramList;
}
 
Example 12
Source File: ProgressUploadServlet.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 上传状态
    UploadStatus status = new UploadStatus();

    // 监听器
    UploadListener listener = new UploadListener(status);

    // 把 UploadStatus 放到 session 里
    request.getSession(true).setAttribute("uploadStatus", status);

    // Apache 上传工具
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    // 设置 listener
    upload.setProgressListener(listener);

    try {
        List itemList = upload.parseRequest(request);

        for (Iterator it = itemList.iterator(); it.hasNext(); ) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                System.out.println("FormField: " + item.getFieldName() + " = " + item.getString());
            } else {
                System.out.println("File: " + item.getName());

                // 统一 Linux 与 windows 的路径分隔符
                String fileName = item.getName().replace("/", "\\");
                fileName = fileName.substring(fileName.lastIndexOf("\\"));

                File saved = new File("C:\\upload_test", fileName);
                saved.getParentFile().mkdirs();

                InputStream ins = item.getInputStream();
                OutputStream ous = new FileOutputStream(saved);

                byte[] tmp = new byte[1024];
                int len = -1;

                while ((len = ins.read(tmp)) != -1) {
                    ous.write(tmp, 0, len);
                }

                ous.close();
                ins.close();

                response.getWriter().println("已保存文件:" + saved);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().println("上传发生错误:" + e.getMessage());
    }
}
 
Example 13
Source File: podHomeBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * Creates a BufferedInputStream to get ready to upload file selected. Used
	 * by Add Podcast and Revise Podcast pages.
	 * 
	 * @param event
	 *            ValueChangeEvent object generated by selecting a file to
	 *            upload.
	 *            
	 * @throws AbortProcessingException
	 * 			Internal processing error attempting to set up BufferedInputStream
	 */
	public void processFileUpload(ValueChangeEvent event)
			throws AbortProcessingException {
		UIComponent component = event.getComponent();

		Object newValue = event.getNewValue();
		Object oldValue = event.getOldValue();
		PhaseId phaseId = event.getPhaseId();
		Object source = event.getSource();
//		log.info("processFileUpload() event: " + event
//				+ " component: " + component + " newValue: " + newValue
//				+ " oldValue: " + oldValue + " phaseId: " + phaseId
//				+ " source: " + source);

		if (newValue instanceof String)
			return;
		if (newValue == null)
			return;

		FileItem item = (FileItem) event.getNewValue();
		String fieldName = item.getFieldName();
		filename = FilenameUtils.getName(item.getName());
		fileSize = item.getSize();
		fileContentType = item.getContentType();
//		log.info("processFileUpload(): item: " + item
//				+ " fieldname: " + fieldName + " filename: " + filename
//				+ " length: " + fileSize);

		// Read the file as a stream (may be more memory-efficient)
		try {
			fileAsStream = new BufferedInputStream(item.getInputStream());
			
		} 
		catch (IOException e) {
			log.warn("IOException while attempting to set BufferedInputStream to upload "
							+ filename + " from site " + podcastService.getSiteId() + ". "
									 + e.getMessage(), e);
			setErrorMessage(INTERNAL_ERROR_ALERT);

		}

	}
 
Example 14
Source File: ImportController.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@PostMapping(value = "/importGroups", consumes = "multipart/form-data")
public String showImportGroups(@RequestParam(required=false) String groupUploadedText, Model model, HttpServletRequest req) {
    log.debug("showImportGroups called with value {}", groupUploadedText);

    // Variable definition
    Locale userLocale = sakaiService.getCurrentUserLocale();
    Map<String, List<String>> importedGroupMap = new HashMap<String, List<String>>();
    String uploadedText = StringUtils.EMPTY;
    String groupFileUploadedText = StringUtils.EMPTY;

    //Check the uploaded file and contents.
    FileItem uploadedFileItem = (FileItem) req.getAttribute("groupUploadFile");
    if (uploadedFileItem.getSize() > 0) {
        try (Scanner scanner = new Scanner(uploadedFileItem.getInputStream(), StandardCharsets.UTF_8.name())) {
            groupFileUploadedText = scanner.useDelimiter("\\A").next();
        } catch (Exception e) {
            log.error("The file {} provided is not valid.", uploadedFileItem.getName());
        }
    }

    // Check if both options are blank and return an error message
    if (StringUtils.isAllBlank(groupUploadedText, groupFileUploadedText)) {
        return returnImportError(model, "import.error.inputrequired", userLocale);
    }        

    // Process the submitted texts, combine the uploaded and the file into one String
    uploadedText = String.format("%s\r\n%s", groupUploadedText, groupFileUploadedText);

    String[] lineArray = uploadedText.split(BULK_LINE_DELIMITER);
    for (String line : lineArray) {

        if (StringUtils.isBlank(line)) {
            continue;
        }

        String[] lineContentArray = line.split(BULK_FIELD_DELIMITER);

        //Each line must contain a groupTitle and a userEid
        if (lineContentArray.length == 2) {
            String groupTitle = StringUtils.trimToNull(lineContentArray[0]);
            String userEid = StringUtils.trimToNull(lineContentArray[1]);

            if (StringUtils.isAnyBlank(groupTitle, userEid)) {
                // One of the items of the line is blank, redirect to the import form again displaying an error. 
                return returnImportError(model, "import.error.wrongformat", userLocale);
            }

            if (groupTitle.length() > 99) {
                // One of the items of the line has more than 99 characters, redirect to the import form again displaying an error. 
                return returnImportError(model, "import.error.titlelength", userLocale);
            }

            if (importedGroupMap.get(groupTitle) != null) {
                // If the map contains an entry for that group, add the user to the list
                importedGroupMap.get(groupTitle).add(userEid);
            } else {
                // If the map does not contain an entry for that group, create a list and add the member to the list
                List<String> newUserlist = new ArrayList<String>();
                newUserlist.add(userEid);
                importedGroupMap.put(groupTitle, newUserlist);
            }
        } else {
            // One line does not contain two items, redirect to the import form again displaying an error.
            return returnImportError(model, "import.error.wrongformat", userLocale);
        }
    }

    //Redirect to the confirmation page once the map are correct
    return showImportConfirmation(model, importedGroupMap);
}
 
Example 15
Source File: SyllabusTool.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String processUpload(ValueChangeEvent event)
{
  if(attachCaneled == false)
  {
    Object newValue = event.getNewValue();

    if (newValue instanceof String) return "";
    if (newValue == null) return "";

    FileItem item = (FileItem) event.getNewValue();
    try (InputStream inputStream = item.getInputStream())
    {
      String fileName = item.getName();

      ResourcePropertiesEdit props = contentHostingService.newResourceProperties();

      if (fileName != null) {
          filename = FilenameUtils.getName(filename);
      }

      ContentResourceEdit thisAttach = contentHostingService.addAttachmentResource(fileName);
      thisAttach.setContent(inputStream);
      thisAttach.setContentType(item.getContentType());
      thisAttach.getPropertiesEdit().addAll(props);
      contentHostingService.commitResource(thisAttach);
      
      SyllabusAttachment attachObj = syllabusManager.createSyllabusAttachmentObject(thisAttach.getId(), fileName);
      attachments.add(attachObj);

      if(entry.justCreated != true)
      {
        allAttachments.add(attachObj);
      }
    }
    catch (Exception e)
    {
      log.error(this + ".processUpload() in SyllabusTool", e);
    }
    if(entry.justCreated == true)
    {
      return "edit";
    }
    else
    {
      return "read";
    }
  }
  return null;
}
 
Example 16
Source File: VariableEditorServletHandler.java    From urule with Apache License 2.0 4 votes vote down vote up
public void importXml(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	try {
		List<FileItem> items = upload.parseRequest(req);
		if(items.size()!=1){
			throw new ServletException("Upload xml file is invalid.");
		}
		FileItem item=items.get(0);
		inputStream=item.getInputStream();
		String xmlContent=IOUtils.toString(inputStream, "utf-8");
		List<Variable> variables=new ArrayList<Variable>();
		Document doc=DocumentHelper.parseText(xmlContent);
		Element root=doc.getRootElement();
		String clazz=root.attributeValue("clazz");
		for(Object obj:root.elements()){
			if(obj==null || !(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			Variable var=new Variable();
			var.setAct(Act.InOut);
			var.setDefaultValue(ele.attributeValue("defaultValue"));
			var.setLabel(ele.attributeValue("label"));
			var.setName(ele.attributeValue("name"));
			var.setType(Datatype.valueOf(ele.attributeValue("type")));
			variables.add(var);
		}
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("clazz", clazz);
		result.put("variables", variables);
		writeObjectToJson(resp, result);
	} catch (Exception e) {
		throw new ServletException(e);
	} finally {
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example 17
Source File: ArchiveServlet.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void processRequest(HttpServletRequest request,
		HttpServletResponse response)
				throws ServletException, IOException {

	// Prepare file upload

	// Create a factory for disk-based file items
	DiskFileItemFactory factory = new DiskFileItemFactory();

	// Configure a repository (to ensure a secure temp location is used)
	ServletContext servletContext = this.getServletConfig().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);

	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);
	List<FileItem> items = null;
	try {
		// Parse the request
		items = upload.parseRequest(request);
		FileItem item = null;
		ArchivePrinter printer = null;

		// Process the uploaded items
		Iterator<FileItem> iter = items.iterator();
		while (iter.hasNext()) {
			item = iter.next();

			// Print the entries of an uploaded ZIP
			if (!item.isFormField()) {
				printer = new ArchivePrinter(item.getInputStream());
				printer.printEntries(new PrintStream(response.getOutputStream()));
			}
			else {
				//ArchiveServlet.log.info("Parameter [" + item.getFieldName() + "], value [" + item.getString() + "]");
				if(item.getFieldName().equals("note"))
					this.saveNote(item.getString());
			}
		}
	} catch (FileUploadException e) {
		//ArchiveServlet.log.error("Error uploading file: " + e.getMessage(), e);
	}
}
 
Example 18
Source File: podHomeBean.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * Creates a BufferedInputStream to get ready to upload file selected. Used
	 * by Add Podcast and Revise Podcast pages.
	 * 
	 * @param event
	 *            ValueChangeEvent object generated by selecting a file to
	 *            upload.
	 *            
	 * @throws AbortProcessingException
	 * 			Internal processing error attempting to set up BufferedInputStream
	 */
	public void processFileUpload(ValueChangeEvent event)
			throws AbortProcessingException {
		UIComponent component = event.getComponent();

		Object newValue = event.getNewValue();
		Object oldValue = event.getOldValue();
		PhaseId phaseId = event.getPhaseId();
		Object source = event.getSource();
//		log.info("processFileUpload() event: " + event
//				+ " component: " + component + " newValue: " + newValue
//				+ " oldValue: " + oldValue + " phaseId: " + phaseId
//				+ " source: " + source);

		if (newValue instanceof String)
			return;
		if (newValue == null)
			return;

		FileItem item = (FileItem) event.getNewValue();
		String fieldName = item.getFieldName();
		filename = FilenameUtils.getName(item.getName());
		fileSize = item.getSize();
		fileContentType = item.getContentType();
//		log.info("processFileUpload(): item: " + item
//				+ " fieldname: " + fieldName + " filename: " + filename
//				+ " length: " + fileSize);

		// Read the file as a stream (may be more memory-efficient)
		try {
			fileAsStream = new BufferedInputStream(item.getInputStream());
			
		} 
		catch (IOException e) {
			log.warn("IOException while attempting to set BufferedInputStream to upload "
							+ filename + " from site " + podcastService.getSiteId() + ". "
									 + e.getMessage(), e);
			setErrorMessage(INTERNAL_ERROR_ALERT);

		}

	}
 
Example 19
Source File: UploadDatasetFileAction.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem unzipUploadedFile(FileItem uploaded) {

		logger.debug("Method unzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			ZipInputStream zippedInputStream = new ZipInputStream(uploaded.getInputStream());
			ZipEntry zipEntry = null;

			if ((zipEntry = zippedInputStream.getNextEntry()) != null) {

				String zipItemName = zipEntry.getName();

				logger.debug("Method unzipUploadedFile(): Zip entry [ " + zipItemName + " ]");

				if (zipEntry.isDirectory()) {
					throw new SpagoBIServiceException(getActionName(), "The uploaded file is a folder. Zip directly the file.");
				}

				DiskFileItemFactory factory = new DiskFileItemFactory();
				tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), zipItemName);
				OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

				IOUtils.copy(zippedInputStream, tempFileItemOutStream);

				tempFileItemOutStream.close();
			}

			zippedInputStream.close();

			logger.debug("Method unzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}
 
Example 20
Source File: UpdateServlet.java    From database with GNU General Public License v2.0 2 votes vote down vote up
private boolean validateItem(
		final HttpServletResponse resp, final FileItem item) 
			throws IOException {
	
	final String contentType = item.getContentType();
	
    if (contentType == null) {
    	
        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not specified");

        return false;
        
    }

       final RDFFormat format = RDFFormat
               .forMIMEType(new MiniMime(contentType).getMimeType());

    if (format == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not recognized as RDF: " + contentType);

        return false;

    }
    
       final RDFParserFactory rdfParserFactory = RDFParserRegistry
	        .getInstance().get(format);
	
	if (rdfParserFactory == null) {
	
	    buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN,
	            "Parser factory not found: Content-Type=" + contentType
	                    + ", format=" + format);
	
	    return false;
	
	}

    if (item.getInputStream() == null) {
    	
        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "No content");

        return false;
    	
    }
    
    return true;
	
}