当前位置: 首页>>代码示例>>Java>>正文


Java RestletFileUpload类代码示例

本文整理汇总了Java中org.restlet.ext.fileupload.RestletFileUpload的典型用法代码示例。如果您正苦于以下问题:Java RestletFileUpload类的具体用法?Java RestletFileUpload怎么用?Java RestletFileUpload使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


RestletFileUpload类属于org.restlet.ext.fileupload包,在下文中一共展示了RestletFileUpload类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: processUpload

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
private void processUpload(Exchange exchange) throws Exception {
	logger.debug("Begin import:"+ exchange.getIn().getHeaders());
	if(exchange.getIn().getBody()!=null){
		logger.debug("Body class:"+ exchange.getIn().getBody().getClass());
	}else{
		logger.debug("Body class is null");
	}
	//logger.debug("Begin import:"+ exchange.getIn().getBody());
	MediaType mediaType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, MediaType.class);
	InputRepresentation representation = new InputRepresentation((InputStream) exchange.getIn().getBody(), mediaType);
	logger.debug("Found MIME:"+ mediaType+", length:"+exchange.getIn().getHeader(Exchange.CONTENT_LENGTH, Integer.class));
	//make a reply
	Json reply = Json.read("{\"files\": []}");
	Json files = reply.at("files");
	
	try {
		List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory()).parseRepresentation(representation);
		logger.debug("Begin import files:"+items);
		for (FileItem item : items) {
			if (!item.isFormField()) {
				InputStream inputStream = item.getInputStream();
				
				Path destination = Paths.get(Util.getConfigProperty(STATIC_DIR)+Util.getConfigProperty(MAP_DIR)+item.getName());
				logger.debug("Save import file:"+destination);
				long len = Files.copy(inputStream, destination, StandardCopyOption.REPLACE_EXISTING);
				Json f = Json.object();
				f.set("name",item.getName());
				f.set("size",len);
				files.add(f);
				install(destination);
			}
		}
	} catch (FileUploadException | IOException e) {
		logger.error(e.getMessage(),e);
	}
	exchange.getIn().setBody(reply);
}
 
开发者ID:SignalK,项目名称:signalk-server-java,代码行数:38,代码来源:UploadProcessor.java

示例2: addAttachment

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Put
public AttachmentResponse addAttachment(Representation entity) {
  if(authenticate() == false) return null;
  
  String taskId = (String) getRequest().getAttributes().get("taskId");
  
  try {
    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRepresentation(entity);
    
    FileItem uploadItem = null;
    for (FileItem fileItem : items) {
      if(fileItem.getName() != null) {
        uploadItem = fileItem;
      }
    }
    
    String fileName = uploadItem.getName();
    
    Attachment attachment = ActivitiUtil.getTaskService().createAttachment(
        uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream());
    
    return new AttachmentResponse(attachment);
    
  } catch(Exception e) {
    throw new ActivitiException("Unable to add new attachment to task " + taskId);
  }
}
 
开发者ID:iotsap,项目名称:FiWare-Template-Handler,代码行数:29,代码来源:TaskAttachmentAddResource.java

示例3: LazyInitializationFile

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
/**
 * Constructor.
 * 
 * @param request
 *        The request
 */
public LazyInitializationFile( Request request, FileItemFactory fileItemFactory )
{
	super( new HashMap<String, Map<String, Object>>() );
	this.request = request;
	fileUpload = new RestletFileUpload( fileItemFactory );
}
 
开发者ID:tliron,项目名称:prudence,代码行数:13,代码来源:LazyInitializationFile.java

示例4: parse

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
public Collection<FormDataItem> parse(Request request)
throws IOException  {
    FileItemFactory factory = new DiskFileItemFactory();
    //ServletFileUpload upload = new ServletFileUpload(factory);
    RestletFileUpload upload = new RestletFileUpload(factory);
    try {
        List<FileItem> fileItems = upload.parseRequest(request);
        return convertToFormData(fileItems);
    } catch (FileUploadException e) {
        UnknownServiceException use = new UnknownServiceException("File upload error.");
        use.initCause(e);
        throw use;
    }
}
 
开发者ID:devacfr,项目名称:spring-restlet,代码行数:15,代码来源:DefaultMultipartFormParser.java

示例5: upload

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
public void upload(Representation representation) throws ResourceException {
    Object result = null;

    List<FileItem> files = null;

    try {
        RestletFileUpload uploadRequest = new RestletFileUpload(getFileItemFactory());

        files = uploadRequest.parseRepresentation(representation);

        result = delegate.upload(this, files);
    } catch (FileUploadException e) {
        // try to take simply the body as stream
        String name = getRequest().getResourceRef().getPath();

        if (name.contains("/")) {
            name = name.substring(name.lastIndexOf("/") + 1, name.length());
        }

        FileItem file = new FakeFileItem(name, representation);

        files = new ArrayList<FileItem>();

        files.add(file);

        result = delegate.upload(this, files);
    }

    // only if the status was not changed to be something else, like a 202
    if (getResponse().getStatus() == Status.SUCCESS_OK) {
        getResponse().setStatus(Status.SUCCESS_CREATED);
    }

    if (result != null) {
        // TODO: representation cannot be returned as multipart!
        // (representation above is possibly multipart)
        getResponse().setEntity(doRepresent(result, getPreferredVariant()));
    }

}
 
开发者ID:devacfr,项目名称:spring-restlet,代码行数:41,代码来源:RestletResource.java

示例6: newModelFromForm

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Post("multi")
   public Representation newModelFromForm(Representation formRep) {
//TODO: rework to use FileUpload Streaming API...
DiskFileItemFactory factory = new DiskFileItemFactory() ;
RestletFileUpload upload = new RestletFileUpload(factory) ;
List<FileItem> items ;
try {
    items = upload.parseRepresentation(formRep) ;
} catch (FileUploadException e) {
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Exception parsing multipart form: " + e.getMessage(), e) ;
}
ComputationalModel model = parseModel(items) ;

model = addModel(model) ;

FileItem iframeItem = items.get(items.size() - 1) ;
if (iframeItem.getString().equals("true")) {
    return new StringRepresentation(buildIframeResponse(model), MediaType.TEXT_HTML) ;
} else {
    Reference modelRef = getNamespace().modelRef(entryName, getResolver().getModelName(model.getId()), true) ;
    redirectSeeOther(modelRef) ;
    return new StringRepresentation("Model created, URL: " + modelRef.toString() + ".") ;
}
   }
 
开发者ID:NCIP,项目名称:digital-model-repository,代码行数:25,代码来源:NewModelResource.java

示例7: extractXmlMultipart

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
private String extractXmlMultipart() {

		RestletFileUpload upload = new RestletFileUpload(
				new DiskFileItemFactory());

		List<FileItem> items;

		Request request = getRequest();
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
					e.getMessage());
		}

		String module = null;
		for (FileItem fi : items) {
			if (fi.getName() != null) {
				module = getContent(fi);
			}
		}
		if (module == null) {
			throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
					"the file is empty");
		}

		return module;
	}
 
开发者ID:slipstream,项目名称:SlipStreamServer,代码行数:29,代码来源:ModuleResource.java

示例8: uploadDeployment

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Post
public void uploadDeployment(Representation entity) {
  try {
    if(authenticate(SecuredResource.ADMIN) == false) return;
    
    RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRepresentation(entity);
    
    FileItem uploadItem = null;
    String successMethod = null;
    for (FileItem fileItem : items) {
      if(fileItem.getName() != null) {
        uploadItem = fileItem;
      } else if(fileItem.getFieldName().equals("success")){
        successMethod = fileItem.getString();
      }
    }
    
    DeploymentBuilder deploymentBuilder = ActivitiUtil.getRepositoryService().createDeployment();
    String fileName = uploadItem.getName();
    if (fileName.endsWith(".bpmn20.xml")) {
      deploymentBuilder.addInputStream(fileName, uploadItem.getInputStream());
    } else if (fileName.endsWith(".bar") || fileName.endsWith(".zip")) {
      deploymentBuilder.addZipInputStream(new ZipInputStream(uploadItem.getInputStream()));
    } else {
      throw new ActivitiException("File must be of type .bpmn20.xml, .bar or .zip");
    }
    deploymentBuilder.name(fileName);
    deploymentBuilder.deploy();
    StringBuilder html = new StringBuilder();
    html.append("<html>\n");
    html.append("  <script type=\"text/javascript\">\n");
    html.append("    " + successMethod + "()\n");
    html.append("   </script>\n");
    html.append("</html>\n");
    getResponse().setEntity(html.toString(), MediaType.TEXT_HTML);
    
  } catch (Exception e) {
    throw new ActivitiException(e.getMessage(), e);
  }
}
 
开发者ID:logicalhacking,项目名称:SecureBPMN,代码行数:42,代码来源:DeploymentUploadResource.java

示例9: update

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Put
@Post
public void update(Representation multipartForm) throws Exception {
	String path = getPath();
	LOG.debug("开始处理上传资源...");
	// 获取参数
	String userId = getAttribute("userId");
	Representation a = getRequest().getEntity();
	System.out.println((multipartForm == a));
	getRequest();
	// 创建上传文件的解析工厂
	DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
	RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);
	if (null != multipartForm) {
		// 获取引擎
		ProcessEngine processEngine = FoxBpmUtil.getProcessEngine();
		// 获取身份服务
		IdentityService identityService = processEngine.getIdentityService();
		UserEntity userEntity = Authentication.selectUserByUserId(userId);
		List<FileItem> fileItems = fileUpload.parseRepresentation(multipartForm);
		String fileName = null;
		String imgName = null;
		for (FileItem fileItem : fileItems) {
			fileName = fileItem.getName();
			if (StringUtil.isEmpty(fileName)) {
				continue;
			}
			LOG.debug("Save image ... " + fileName);
			/* 新建一个图片文件 */
			String extName = fileName.substring(fileName.lastIndexOf("."));
			createDir(path);
			imgName = userId + extName;
			deleteFile(new File(path + userEntity.getImage()));
			File file = new File(path + imgName);
			createFile(file);
			fileItem.write(file);
		}
		userEntity = new UserEntity(userId);
		userEntity.setImage(imgName);
		identityService.updateUser(userEntity);
		CacheUtil.getIdentityCache().remove("user_" + userEntity.getUserId());
	}
}
 
开发者ID:FoxBPM,项目名称:FoxBPM,代码行数:44,代码来源:UserPictureResource.java

示例10: accept

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
/**
 * processes uploaded file, storing in a temporary directory
 *
 * @param entity
 * @return the directory storing the uploaded file
 * @throws Exception
 */
@Post
public UploadedFile accept(
		final Representation entity )
		throws Exception {
	UploadedFile result;
	if ((entity != null) && MediaType.MULTIPART_FORM_DATA.equals(
			entity.getMediaType(),
			true)) {
		// 1/ Create a factory for disk-based file items
		final DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1000240);

		// 2/ Create a new file upload handler based on the Restlet
		// FileUpload extension that will parse Restlet requests and
		// generates FileItems.
		final RestletFileUpload upload = new RestletFileUpload(
				factory);

		final List<FileItem> fileList = upload.parseRepresentation(entity);
		if (fileList.size() != 1) {
			throw new ResourceException(
					Status.CLIENT_ERROR_BAD_REQUEST);
		}
		FileItem item = fileList.get(0);
		// 3/ Request is parsed by the handler which generates a
		// list of FileItems
		final String tempDir = System.getProperty("java.io.tmpdir");
		// HP Fortify "Path Traversal" false positive
		// A user would need to have OS-level access anyway
		// to change the system properties
		final File dir = new File(
				tempDir);
		final File filename = File.createTempFile(
				"uploadedfile-",
				"-" + item.getName(),
				dir);
		result = new UploadedFile(
				filename.getAbsolutePath());
		FileUtils.copyInputStreamToFile(
				item.getInputStream(),
				filename);
	}
	else {
		throw new ResourceException(
				Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
	}

	return result;
}
 
开发者ID:locationtech,项目名称:geowave,代码行数:57,代码来源:FileUploadResource.java

示例11: addBitstream

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Post
public Representation addBitstream(InputRepresentation rep) {
    Context c = null;
    Bundle bundle = null;
    Bitstream bitstream = null;
    try {
        c = getAuthenticatedContext();
        bundle = Bundle.find(c, this.bundleId);
        if (bundle == null) { 
            return errorNotFound(c, "Could not find the bundle.");
        }
    
        Item[] items = bundle.getItems();

        RestletFileUpload rfu =
            new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        String description = null;
        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value =
                    IOUtils.toString(fileItemStream.openStream(), "UTF-8");
            
                if (key.equals("description")) {
                    description = value;
                } else {
                    return error(c, "Unexpected attribute: " + key,
                                 Status.CLIENT_ERROR_BAD_REQUEST);
                }
            } else {
                if (bitstream != null) {
                    return error(c,
                                 "Only one file can added in one request.",
                                 Status.CLIENT_ERROR_BAD_REQUEST);
                }
                String name = fileItemStream.getName();
                bitstream =
                    bundle.createBitstream(fileItemStream.openStream());
                bitstream.setName(name);
                bitstream.setSource(name);
                BitstreamFormat bf =
                    FormatIdentifier.guessFormat(c, bitstream);
                bitstream.setFormat(bf);
            }
        }

        if (bitstream == null) {
            return error(c, "Request does not contain file(?)",
                         Status.CLIENT_ERROR_BAD_REQUEST);
        }
        if (description != null) {
            bitstream.setDescription(description);
        }
        bitstream.update();
        items[0].update(); // This updates at least the
                           // sequence ID of the bitstream.

        c.complete();
    } catch (AuthorizeException ae) {
      return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    }
    catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successCreated("Bitstream created.",
                          baseUrl() +
                          BitstreamResource.relativeUrl(bitstream.getID()));
}
 
开发者ID:anis-moubarik,项目名称:SimpleREST,代码行数:73,代码来源:BundleResource.java

示例12: submitJob

import org.restlet.ext.fileupload.RestletFileUpload; //导入依赖的package包/类
@Post("multi")
   public Representation submitJob(Representation formRep) {
RestletFileUpload upload = new RestletFileUpload() ;
ComputationJob job = new ComputationJob() ;
boolean inIframe = false ;
try {
    FileItemIterator items = upload.getItemIterator(formRep) ;
    List<ParameterValue> values = new ArrayList<ParameterValue>() ;
    job.setParameterValues(values) ;
    State state = State.TITLE ;
    while (items.hasNext()) {
	FileItemStream item = items.next() ;
       	InputStream itemStream = item.openStream() ;
       	switch (state) {
       	    case TITLE:
       		job.setTitle(Streams.asString(itemStream)) ;
       		state = State.DESC ;
       		break ;
       	    case DESC:
       		job.setDescription(Streams.asString(itemStream)) ;
       		state = State.COMMENTS ;
       		break ;
       	    case COMMENTS:
       		job.setComment(Streams.asString(itemStream)) ;
       		state = State.PARAMS ;
       		break ;
       	    case PARAMS:
       		if (item.getFieldName().equals("iframe")) {
       		    inIframe = Boolean.parseBoolean(Streams.asString(itemStream)) ;
       		} else {
       		    Parameter param = new Parameter() ;
       		    param.setName(parseParamName(item.getFieldName())) ;
       		    ParameterValue value = new ParameterValue() ;
       		    if (item.isFormField()) {
       			value.setValue(Streams.asString(itemStream)) ;
       		    } else {
       			value.setValue(storeFile(item.getName(), itemStream).getSource()) ;
       		    }
       		    value.setJob(job) ;
       		    value.setParameter(param) ;
       		    param.setValue(value) ;
       		    values.add(value) ;
       		}
       		break ;
       	}
    }
} catch (Exception e) {
    throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Exception processing submit job form: " + e.getMessage(), e) ;
}

job = addNewJob(job) ;
ComputationJob startedJob = startJob(job) ;

if (inIframe) {
    return new StringRepresentation(buildIframeResponse(job), MediaType.TEXT_HTML) ;
} else {
    Reference jobRef = getNamespace().jobRef(entryName, modelName,getResolver().getJobName(startedJob.getId()), true) ;
    redirectSeeOther(jobRef) ;
    return new StringRepresentation("Job submitted, URL: " + jobRef.toString() + ".") ;
}
   }
 
开发者ID:NCIP,项目名称:digital-model-repository,代码行数:62,代码来源:SubmitJobResource.java


注:本文中的org.restlet.ext.fileupload.RestletFileUpload类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。