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


Java Streams类代码示例

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


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

示例1: processFileItemStreamAsFormField

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
/**
 * Processes the FileItemStream as a Form Field.
 *
 * @param itemStream file item stream
 */
private void processFileItemStreamAsFormField(FileItemStream itemStream) {
    String fieldName = itemStream.getFieldName();
    try {
        List<String> values;
        String fieldValue = Streams.asString(itemStream.openStream());
        if (!parameters.containsKey(fieldName)) {
            values = new ArrayList<>();
            parameters.put(fieldName, values);
        } else {
            values = parameters.get(fieldName);
        }
        values.add(fieldValue);
    } catch (IOException e) {
        LOG.warn("Failed to handle form field '{}'.", fieldName, e);
    }
}
 
开发者ID:txazo,项目名称:struts2,代码行数:22,代码来源:JakartaStreamMultiPartRequest.java

示例2: getRequestData

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
private Map<String, String> getRequestData(HttpServletRequest request) {
  Map<String, String> requestData = new HashMap<>();

  ServletFileUpload upload = new ServletFileUpload();
  try {
    FileItemIterator itemIterator = upload.getItemIterator(request);
    while (itemIterator.hasNext()) {
      FileItemStream item = itemIterator.next();
      InputStream itemStream = item.openStream();
      String value = Streams.asString(itemStream, CharEncoding.UTF_8);
      requestData.put(item.getFieldName(), value);
    }
  } catch (FileUploadException | IOException e) {
    LOGGER.error("Failed to process request", e);
  }

  return requestData;
}
 
开发者ID:Cognifide,项目名称:aet,代码行数:19,代码来源:SuiteServlet.java

示例3: asString

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
/**
    * @param stream
    *            The ServletFileUpload input stream
    * @param commonsConfigurator
    *            Used to get the password for encryption
    */
   public static String asString(InputStream stream,
    CommonsConfigurator commonsConfigurator)
    throws IOException {
String value = Streams.asString(stream);

if (isEncrypted(value, commonsConfigurator)) {
    try {
	value = StringUtils.substringAfter(value, Pbe.KAWANFW_ENCRYPTED);		
	
	value = new Pbe().decryptFromHexa(value,
		CommonsConfiguratorCall.getEncryptionPassword(commonsConfigurator));		
	
	return value;
    } catch (Exception e) {
	String message = Tag.PRODUCT_USER_CONFIG_FAIL
		+ " Impossible to decrypt the value " + value;
	message += ". Check that password values are the same on client and server side.";

	throw new IOException(message, e);
    }
} else {
    return value;
}
   }
 
开发者ID:kawansoft,项目名称:awake-file,代码行数:31,代码来源:StreamsEncrypted.java

示例4: parse

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
public void parse(MultipartRequestCallback callback) throws IOException, FileUploadException, StatusServletException {
	if (!ServletFileUpload.isMultipartContent(request)) {
		LOGGER.error("Request content is not multipart.");
		throw new StatusServletException(Response.SC_PRECONDITION_FAILED);
	}
	
	final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
	while (iterator.hasNext()) {
		// Gets the first HTTP request element.
		final FileItemStream item = iterator.next();

		if (item.isFormField()) {
			final String value = Streams.asString(item.openStream(), "UTF-8");
			properties.put(item.getFieldName(), value);
			
		} else if(callback != null) {
			callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType());
		}
	}
}
 
开发者ID:sigmah-dev,项目名称:sigmah,代码行数:21,代码来源:MultipartRequest.java

示例5: handleMultipart

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
private String handleMultipart(RecordedRequest request) {
    RecordedUpload upload = new RecordedUpload(request);
    Exception exception;
    try {
        Map<String,String> params = new HashMap<>();
        FileItemIterator iter = upload.getItemIterator();
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                System.out.println("Form field " + name + " with value "
                        + value + " detected.");
                params.put(name,value);
            } else {
                System.out.println("File field " + name + " with file name "
                        + item.getName() + " detected.");
                params.put(name, "file->"+item.getName());
            }
        }
        return "Multipart:"+JSON.toJSONString(params);
    } catch (Exception e) {
        exception = e;
    }
    return "Multipart:error->"+exception;
}
 
开发者ID:alexclin0188,项目名称:httplite,代码行数:28,代码来源:MiscHandle.java

示例6: readFormData

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
/**
 * Reads form values from the multipart request until a file is encountered. Field values are stored as strings for
 * retrieval using {@link #getFormFieldValue}.
 * @return  True if there is an upload file available to read via {@link #getUploadFileItem()}.
 */
public boolean readFormData() {
  mUploadFileItem = null;
  try {
    while (mItemIterator.hasNext()) {

      FileItemStream lCurrentItem = mItemIterator.next();
      /**
       * NOTE: the InputStream here is read here in a blocking way. Long upload hangs have been observed on live
       * environments at this point due to network issues. It should be possible to convert the stream to a
       * non-blocking stream at this point if required.
       */
      InputStream lItemInputStream = lCurrentItem.openStream();

      if (lCurrentItem.isFormField()) {
        //Read form values into the map
        String lParamName = lCurrentItem.getFieldName();
        String lFieldValue = Streams.asString(lItemInputStream);

        mFieldParamMap.put(lParamName, lFieldValue);
      }
      else {
        //We've hit the file field, so stop the read for now
        mUploadFileItem = lCurrentItem;
        break;
      }

      lItemInputStream.close();
    }

  }
  catch (IOException | FileUploadException e) {
    throw new ExInternal("Failed to read form data for the multipart request", e);
  }

  return mUploadFileItem != null;
}
 
开发者ID:Fivium,项目名称:FOXopen,代码行数:42,代码来源:MultipartUploadReader.java

示例7: getFileItem

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
private void getFileItem(HttpServletRequest request) throws FileUploadException, IOException {
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	
	if (!isMultipart) {
		throw new IllegalArgumentException("Not multipart...");
	}
	
	
		ServletFileUpload upload = new ServletFileUpload();
		
		List<String> mdrEntries = new ArrayList<String>();
		
		// Parse the request
		FileItemIterator iter = upload.getItemIterator(request);
		while (iter.hasNext()) {
			FileItemStream item = iter.next();
			
			String name = item.getFieldName();
			InputStream stream = item.openStream();
			if (item.isFormField()) {
				System.out.println("Form field " + name + " with value "
						+ Streams.asString(stream) + " detected.");
			} else {
				System.out.println("File field " + name + " with file name "
						+ item.getName() + " detected.");
				// Process the input stream
			}
			String mdrEntry = handleInput(name, stream);
			mdrEntries.add(mdrEntry);
		}
		commitContent(mdrEntries);
}
 
开发者ID:luox12,项目名称:onecmdb,代码行数:33,代码来源:ChangeUploadCommand.java

示例8: doPost

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
protected void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
	long gameId = 0l;
	String auth = null;
	try {
		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iter = upload.getItemIterator(req);

		String json = "";
		while (iter.hasNext()) {
			FileItemStream item = iter.next();
			String name = item.getFieldName();
			InputStream stream = item.openStream();
			if (item.isFormField()) {
				String value = Streams.asString(stream);
				if ("gameId".equals(name)) gameId = Long.parseLong(value);
				if ("auth".equals(name)) auth = value;
				
			} else {
				json = Streams.asString(stream);

			}
		}

		res.setContentType("text/plain");
		JSONObject jObject = new JSONObject(json);
		Object deserialized = JsonBeanDeserializer.deserialize(json);
		
		if (deserialized instanceof GamePackage && ((GamePackage) deserialized).getGame() != null)
			unpackGame((GamePackage) deserialized, req, auth);
		if (deserialized instanceof RunPackage && ((RunPackage) deserialized ).getRun() != null)
			unpackRun((RunPackage) deserialized, req, gameId, auth);

	} catch (Exception ex) {
		throw new ServletException(ex);
	}
}
 
开发者ID:WELTEN,项目名称:dojo-ibl,代码行数:38,代码来源:UploadGameServlet.java

示例9: uploadMultipart

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp,
    OutputStream repoItemOutputStrem) throws IOException {

  log.debug("Multipart detected");

  ServletFileUpload upload = new ServletFileUpload();

  try {

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
      FileItemStream item = iter.next();
      String name = item.getFieldName();
      try (InputStream stream = item.openStream()) {
        if (item.isFormField()) {
          // TODO What to do with this?
          log.debug("Form field {} with value {} detected.", name, Streams.asString(stream));
        } else {

          // TODO Must we support multiple files uploading?
          log.debug("File field {} with file name detected.", name, item.getName());

          log.debug("Start to receive bytes (estimated bytes)",
              Integer.toString(req.getContentLength()));
          int bytes = IOUtils.copy(stream, repoItemOutputStrem);
          resp.setStatus(SC_OK);
          log.debug("Bytes received: {}", Integer.toString(bytes));
        }
      }
    }

  } catch (FileUploadException e) {
    throw new IOException(e);
  }
}
 
开发者ID:Kurento,项目名称:kurento-java,代码行数:37,代码来源:RepositoryHttpServlet.java

示例10: asMultipartRequest

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
private static MultipartRequest asMultipartRequest(HttpServletRequest request) throws Exception {
    String encoding = request.getCharacterEncoding();

    MultipartRequest req = new MultipartRequest(request);
    ServletFileUpload upload = new ServletFileUpload();
    upload.setHeaderEncoding(encoding);
    FileItemIterator it = upload.getItemIterator(request);

    while (it.hasNext()) {
        FileItemStream item = it.next();
        String fieldName = item.getFieldName();
        InputStream stream = item.openStream();
        try {
            if (item.isFormField()) {
                req.setParameter(fieldName, Streams.asString(stream, encoding));
            } else {
                String originalFilename = item.getName();
                File diskFile = getTempFile(originalFilename);
                OutputStream fos = new FileOutputStream(diskFile);

                try {
                    IoUtils.copy(stream, fos);
                } finally {
                    IoUtils.closeQuietly(fos);
                }

                FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
                req.addFile(filePart);
            }
        } finally {
            IoUtils.closeQuietly(stream);
        }
    }

    return req;
}
 
开发者ID:subchen,项目名称:jetbrick-all-1x,代码行数:37,代码来源:FileUploaderUtils.java

示例11: doPost

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();

    try{
        FileItemIterator iterator = upload.getItemIterator(request);
        if (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            String name = item.getFieldName();

            logger.debug("Uploading file '{}' with item name '{}'", item.getName(), name);

            InputStream stream = item.openStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Streams.copy(stream, out, true);

            byte[] data = out.toByteArray();

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(new String(data));
            response.flushBuffer();
        }
        else {
            logger.error("No file found in post request!");
            throw new RuntimeException("No file found in post request!");
        }
    }
    catch(Exception e){
        logger.error("Unexpected error in FileUploadServlet.doPost: ", e);
        throw new RuntimeException(e);
    }
}
 
开发者ID:kaaproject,项目名称:avro-ui,代码行数:36,代码来源:FileUploadServlet.java

示例12: doPost

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  //CHECKSTYLE:ON
  ServletFileUpload upload = new ServletFileUpload();

  try {
    FileItemIterator iter = upload.getItemIterator(request);
    if (iter.hasNext()) {
      FileItemStream item = iter.next();
      String name = item.getFieldName();

      LOG.debug("Uploading file '{}' with item name '{}'", item.getName(), name);

      InputStream stream = item.openStream();

      // Process the input stream
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      Streams.copy(stream, out, true);

      byte[] data = out.toByteArray();

      cacheService.uploadedFile(name, data);
    } else {
      LOG.error("No file found in post request!");
      throw new RuntimeException("No file found in post request!");
    }
  } catch (Exception ex) {
    LOG.error("Unexpected error in FileUpload.doPost: ", ex);
    throw new RuntimeException(ex);
  }

}
 
开发者ID:kaaproject,项目名称:kaa,代码行数:33,代码来源:FileUpload.java

示例13: internalImport

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
protected void internalImport(
    HttpServletRequest    request,
    Properties            options,
    long                  projectID
) throws Exception {

    String url = null;

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName().toLowerCase();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            if (name.equals("url")) {
                url = Streams.asString(stream);
            } else {
                options.put(name, Streams.asString(stream));
            }
        } else {
            String fileName = item.getName().toLowerCase();
            try {
                ProjectManager.getSingleton().importProject(projectID, stream, !fileName.endsWith(".tar"));
            } finally {
                stream.close();
            }
        }
    }

    if (url != null && url.length() > 0) {
        internalImportURL(request, options, projectID, url);
    }
}
 
开发者ID:dfci-cccb,项目名称:mev,代码行数:36,代码来源:ImportProjectCommand.java

示例14: doFilter

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
@Override
public void doFilter(HttpExchange exchange, Chain chain) throws IOException
{
	final Map<String, List<String>> params = parseGetParameters(exchange);
	Map<String, Pair<String, File>> streams = null;

	if( HttpExchangeUtils.isPost(exchange) )
	{
		if( HttpExchangeUtils.isMultipartContent(exchange) )
		{
			streams = new HashMap<String, Pair<String, File>>();

			try
			{
				FileItemIterator ii = new FileUpload().getItemIterator(new ExchangeRequestContext(exchange));
				while( ii.hasNext() )
				{
					final FileItemStream is = ii.next();
					final String name = is.getFieldName();
					try( InputStream stream = is.openStream() )
					{
						if( !is.isFormField() )
						{
							// IE passes through the full path of the file,
							// where as Firefox only passes through the
							// filename. We only need the filename, so
							// ensure that we string off anything that looks
							// like a path.
							final String filename = STRIP_PATH_FROM_FILENAME.matcher(is.getName()).replaceFirst(
								"$1");
							final File tempfile = File.createTempFile("equella-manager-upload", "tmp");
							tempfile.getParentFile().mkdirs();
							streams.put(name, new Pair<String, File>(filename, tempfile));

							try( OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile)) )
							{
								ByteStreams.copy(stream, out);
							}
						}
						else
						{
							addParam(params, name, Streams.asString(stream));
						}
					}
				}
			}
			catch( Exception t )
			{
				throw new RuntimeException(t);
			}
		}
		else
		{
			try( InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "UTF-8") )
			{
				BufferedReader br = new BufferedReader(isr);
				String query = br.readLine();

				parseQuery(query, params);
			}
		}
	}

	exchange.setAttribute(PARAMS_KEY, params);
	exchange.setAttribute(MULTIPART_STREAMS_KEY, streams);
	// attributes seem to last the life of a session... I don't know why...
	exchange.setAttribute("error", null);

	chain.doFilter(exchange);
}
 
开发者ID:equella,项目名称:Equella,代码行数:71,代码来源:SuperDuperFilter.java

示例15: service

import org.apache.commons.fileupload.util.Streams; //导入依赖的package包/类
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        List<String> files = new ArrayList<>();
        ServletFileUpload upload = new ServletFileUpload();
        // Parse the request
        FileItemIterator iter = null;
        try {
            iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                try (InputStream stream = item.openStream()) {

                    if (item.isFormField()) {
                        LOGGER.debug("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                        incrementStringsProcessed();
                    } else {
                        LOGGER.debug("File field " + name + " with file name " + item.getName() + " detected.");
                        // Process the input stream
                        File tmpFile = File.createTempFile(UUID.randomUUID().toString() + "_MockUploadServlet", ".tmp");
                        tmpFile.deleteOnExit();
                        try (OutputStream os = new FileOutputStream(tmpFile)) {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = stream.read(buffer)) != -1) {
                                os.write(buffer, 0, bytesRead);
                            }
                            incrementFilesProcessed();
                            files.add(tmpFile.getAbsolutePath());
                        }
                    }
                }
            }
        } catch (FileUploadException e) {

        }
        try (Writer w = response.getWriter()) {
            w.write(Integer.toString(getFilesProcessed()));
            resetFilesProcessed();
            resetStringsProcessed();
            w.write("||");
            w.write(files.toString());
        }
    } else {
        try (Writer w = response.getWriter()) {
            w.write(Integer.toString(getFilesProcessed()));
            resetFilesProcessed();
            resetStringsProcessed();
            w.write("||");
        }
    }
}
 
开发者ID:amaralDaniel,项目名称:megaphone,代码行数:56,代码来源:MultipartUploadTest.java


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