List of usage examples for org.apache.commons.fileupload.util Streams asString
public static String asString(InputStream pStream) throws IOException
From source file:org.celstec.arlearn2.upload.BlobStoreServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {//from w ww .ja v a2 s.co m Long runId = null; String account = null; ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { if ("runId".equals(item.getFieldName())) { runId = Long.parseLong(Streams.asString(stream)); } if ("account".equals(item.getFieldName())) { account = Streams.asString(stream); } } else { BlobKey blobkey = storeBlob(item.getContentType(), item.getName(), stream); if (blobkey != null) { System.out.println(blobkey); // File exists BlobKey oldkey = FilePathManager.getBlobKey(account, runId, item.getName()); if (oldkey != null) { FilePathManager.delete(oldkey); blobstoreService.delete(oldkey); } FilePathManager.addFile(runId, account, item.getName(), blobkey); } else { blobkey.toString(); } } } } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.celstec.arlearn2.upload.BlobStoreServletIncremental.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {//ww w . jav a2 s . c o m Long runId = null; String account = null; String serverPath = null; boolean last = false; ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(req); System.out.println("before while"); while (iterator.hasNext()) { System.out.println("in while"); FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { if ("runId".equals(item.getFieldName())) { runId = Long.parseLong(Streams.asString(stream)); System.out.println("runid is " + runId); } if ("account".equals(item.getFieldName())) { account = Streams.asString(stream); System.out.println("account is " + account); } if ("last".equals(item.getFieldName())) { last = Boolean.parseBoolean(Streams.asString(stream)); System.out.println("last is " + last); } if ("serverPath".equals(item.getFieldName())) { serverPath = Streams.asString(stream); System.out.println("serverPath is " + serverPath); } } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); AppEngineFile file = storeBlob(item.getContentType(), item.getName(), stream, last, serverPath); BlobKey blobkey = fileService.getBlobKey(file); if (blobkey != null) { // File exists BlobKey oldkey = FilePathManager.getBlobKey(account, runId, item.getName()); if (oldkey != null) { FilePathManager.delete(oldkey); blobstoreService.delete(oldkey); } FilePathManager.addFile(runId, account, item.getName(), blobkey); System.out.println(blobkey.toString()); } res.getWriter().write(file.getFullPath()); // else { // blobkey.toString(); // } } } } catch (Exception ex) { throw new ServletException(ex); } }
From source file:org.celstec.arlearn2.upload.UploadGameServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long gameId = 0l; String auth = null;/*from www. jav a 2 s. c om*/ 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); } }
From source file:org.cvit.cabig.dmr.cmef.server.SubmitJobResource.java
@Post("multi") public Representation submitJob(Representation formRep) { RestletFileUpload upload = new RestletFileUpload(); ComputationJob job = new ComputationJob(); boolean inIframe = false; try {// w w w. j a v a 2 s . c o m 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() + "."); } }
From source file:org.daxplore.presenter.server.servlets.AdminUploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try {//from w ww .ja v a 2 s .c o m long time = System.nanoTime(); int statusCode = HttpServletResponse.SC_OK; response.setContentType("text/html; charset=UTF-8"); ServletFileUpload upload = new ServletFileUpload(); PersistenceManager pm = null; String prefix = null; try { FileItemIterator fileIterator = upload.getItemIterator(request); String fileName = ""; byte[] fileData = null; while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { if (item.getFieldName().equals("prefix")) { prefix = Streams.asString(stream); } else { throw new BadRequestException("Form contains extra fields"); } } else { fileName = item.getName(); fileData = IOUtils.toByteArray(stream); } } } if (SharedResourceTools.isSyntacticallyValidPrefix(prefix)) { if (fileData != null && !fileName.equals("")) { pm = PMF.get().getPersistenceManager(); unzipAll(pm, prefix, fileData); } else { throw new BadRequestException("No file uploaded"); } } else { throw new BadRequestException("Request made with invalid prefix: '" + prefix + "'"); } logger.log(Level.INFO, "Unpacked new data for prefix '" + prefix + "' in " + ((System.nanoTime() - time) / 1000000000.0) + " seconds"); } catch (FileUploadException | IOException | BadRequestException e) { logger.log(Level.WARNING, e.getMessage(), e); statusCode = HttpServletResponse.SC_BAD_REQUEST; } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } catch (DeadlineExceededException e) { logger.log(Level.SEVERE, "Timeout when uploading new data for prefix '" + prefix + "'", e); // the server is currently unavailable because it is overloaded (hopefully) statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE; } finally { if (pm != null) { pm.close(); } } response.setStatus(statusCode); try (PrintWriter resWriter = response.getWriter()) { if (resWriter != null) { resWriter.write(Integer.toString(statusCode)); resWriter.close(); } } } catch (IOException | RuntimeException e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.dspace.app.webui.json.SubmissionLookupJSONRequest.java
@Override public void doJSONRequest(Context context, HttpServletRequest req, HttpServletResponse resp) throws AuthorizeException, IOException { Gson json = new Gson(); String suuid = req.getParameter("s_uuid"); SubmissionLookupDTO subDTO = service.getSubmissionLookupDTO(req, suuid); // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if ("identifiers".equalsIgnoreCase(req.getParameter("type"))) { Map<String, Set<String>> identifiers = new HashMap<String, Set<String>>(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String parameterName = (String) e.nextElement(); String parameterValue = req.getParameter(parameterName); if (parameterName.startsWith("identifier_") && StringUtils.isNotBlank(parameterValue)) { Set<String> set = new HashSet<String>(); set.add(parameterValue); identifiers.put(parameterName.substring("identifier_".length()), set); }/*w w w . ja va 2s. c o m*/ } List<ItemSubmissionLookupDTO> result = new ArrayList<ItemSubmissionLookupDTO>(); TransformationEngine transformationEngine = service.getPhase1TransformationEngine(); if (transformationEngine != null) { MultipleSubmissionLookupDataLoader dataLoader = (MultipleSubmissionLookupDataLoader) transformationEngine .getDataLoader(); dataLoader.setIdentifiers(identifiers); try { SubmissionLookupOutputGenerator outputGenerator = (SubmissionLookupOutputGenerator) transformationEngine .getOutputGenerator(); outputGenerator.setDtoList(new ArrayList<ItemSubmissionLookupDTO>()); log.debug("BTE transformation is about to start!"); transformationEngine.transform(new TransformationSpec()); log.debug("BTE transformation finished!"); result = outputGenerator.getDtoList(); } catch (BadTransformationSpec e1) { log.error(e1.getMessage(), e1); } catch (MalformedSourceException e1) { log.error(e1.getMessage(), e1); } } subDTO.setItems(result); service.storeDTOs(req, suuid, subDTO); List<Map<String, Object>> dto = getLightResultList(result); JsonElement tree = json.toJsonTree(dto); JsonObject jo = new JsonObject(); jo.add("result", tree); resp.getWriter().write(jo.toString()); } else if ("search".equalsIgnoreCase(req.getParameter("type"))) { String title = req.getParameter("title"); String author = req.getParameter("authors"); int year = UIUtil.getIntParameter(req, "year"); Map<String, Set<String>> searchTerms = new HashMap<String, Set<String>>(); Set<String> tmp1 = new HashSet<String>(); tmp1.add(title); Set<String> tmp2 = new HashSet<String>(); tmp2.add(author); Set<String> tmp3 = new HashSet<String>(); tmp3.add(String.valueOf(year)); searchTerms.put("title", tmp1); searchTerms.put("authors", tmp2); searchTerms.put("year", tmp3); List<ItemSubmissionLookupDTO> result = new ArrayList<ItemSubmissionLookupDTO>(); TransformationEngine transformationEngine = service.getPhase1TransformationEngine(); if (transformationEngine != null) { MultipleSubmissionLookupDataLoader dataLoader = (MultipleSubmissionLookupDataLoader) transformationEngine .getDataLoader(); dataLoader.setSearchTerms(searchTerms); try { SubmissionLookupOutputGenerator outputGenerator = (SubmissionLookupOutputGenerator) transformationEngine .getOutputGenerator(); outputGenerator.setDtoList(new ArrayList<ItemSubmissionLookupDTO>()); log.debug("BTE transformation is about to start!"); transformationEngine.transform(new TransformationSpec()); log.debug("BTE transformation finished!"); result = outputGenerator.getDtoList(); } catch (BadTransformationSpec e1) { log.error(e1.getMessage(), e1); } catch (MalformedSourceException e1) { log.error(e1.getMessage(), e1); } } subDTO.setItems(result); service.storeDTOs(req, suuid, subDTO); List<Map<String, Object>> dto = getLightResultList(result); JsonElement tree = json.toJsonTree(dto); JsonObject jo = new JsonObject(); jo.add("result", tree); resp.getWriter().write(jo.toString()); } else if ("details".equalsIgnoreCase(req.getParameter("type"))) { String i_uuid = req.getParameter("i_uuid"); Map<String, Object> dto = getDetails(subDTO.getLookupItem(i_uuid), context); JsonElement tree = json.toJsonTree(dto); JsonObject jo = new JsonObject(); jo.add("result", tree); resp.getWriter().write(jo.toString()); } else if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request Map<String, String> valueMap = new HashMap<String, String>(); InputStream io = null; // Parse the request List<FileItem> iter; String filename = null; try { iter = upload.parseRequest(req); for (FileItem item : iter) { String name = item.getFieldName(); InputStream stream = item.getInputStream(); if (item.isFormField()) { String value = Streams.asString(stream); valueMap.put(name, value); } else { io = stream; } } } catch (FileUploadException e) { throw new IOException(e); } suuid = valueMap.get("s_uuid"); subDTO = service.getSubmissionLookupDTO(req, suuid); List<ItemSubmissionLookupDTO> result = new ArrayList<ItemSubmissionLookupDTO>(); TransformationEngine transformationEngine = service.getPhase1TransformationEngine(); if (transformationEngine != null) { MultipleSubmissionLookupDataLoader dataLoader = (MultipleSubmissionLookupDataLoader) transformationEngine .getDataLoader(); String tempDir = (ConfigurationManager.getProperty("upload.temp.dir") != null) ? ConfigurationManager.getProperty("upload.temp.dir") : System.getProperty("java.io.tmpdir"); File uploadDir = new File(tempDir); if (!uploadDir.exists()) { if (!uploadDir.mkdir()) { uploadDir = null; } } File file = File.createTempFile("submissionlookup-loader", ".temp", uploadDir); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); Utils.bufferedCopy(io, out); dataLoader.setFile(file.getAbsolutePath(), valueMap.get("provider_loader")); try { SubmissionLookupOutputGenerator outputGenerator = (SubmissionLookupOutputGenerator) transformationEngine .getOutputGenerator(); outputGenerator.setDtoList(new ArrayList<ItemSubmissionLookupDTO>()); log.debug("BTE transformation is about to start!"); transformationEngine.transform(new TransformationSpec()); log.debug("BTE transformation finished!"); result = outputGenerator.getDtoList(); } catch (BadTransformationSpec e1) { log.error(e1.getMessage(), e1); } catch (MalformedSourceException e1) { log.error(e1.getMessage(), e1); } finally { file.delete(); } } subDTO.setItems(result); service.storeDTOs(req, suuid, subDTO); List<Map<String, Object>> dto = getLightResultList(result); if (valueMap.containsKey("skip_loader")) { if (valueMap.get("skip_loader").equals("true")) { Map<String, Object> skip = new HashMap<String, Object>(); skip.put("skip", Boolean.TRUE); skip.put("uuid", valueMap.containsKey("s_uuid") ? suuid : -1); skip.put("collectionid", valueMap.containsKey("select-collection-file") ? valueMap.get("select-collection-file") : -1); dto.add(skip); } } JsonElement tree = json.toJsonTree(dto); JsonObject jo = new JsonObject(); jo.add("result", tree); resp.setContentType("text/plain"); // if you works in localhost mode and use IE10 to debug the feature uncomment the follow line // resp.setHeader("Access-Control-Allow-Origin","*"); resp.getWriter().write(jo.toString()); } }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
@Test public void test02AccessTest() throws Exception { ScepConfiguration scepConfig = (ScepConfiguration) globalConfigSession .getCachedConfiguration(ScepConfiguration.SCEP_CONFIGURATION_ID); boolean remove = false; if (!scepConfig.aliasExists("scep")) { scepConfig.addAlias("scep"); globalConfigSession.saveConfiguration(admin, scepConfig); remove = true;//from w ww . j a va 2 s . co m } String resourceName = "/ejbca/publicweb/apply/scep/pkiclient.exe?operation=GetCACert&message=" + x509ca.getName(); String httpHost = SystemTestsConfiguration.getRemoteHost("127.0.0.1"); String httpPort = SystemTestsConfiguration.getRemotePortHttp( configurationSessionRemote.getProperty(WebConfiguration.CONFIG_HTTPSERVERPUBHTTP)); String httpBaseUrl = "http://" + httpHost + ":" + httpPort; String url = httpBaseUrl + resourceName; final HttpURLConnection con; URL u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("GET"); con.getDoOutput(); con.connect(); int ret = con.getResponseCode(); log.debug("HTTP response code: " + ret); if (ret == 200) { log.debug(Streams.asString(con.getInputStream())); } con.disconnect(); if (remove) { scepConfig.removeAlias("scep"); globalConfigSession.saveConfiguration(admin, scepConfig); } assertEquals("HTTP GET is not supported. (This test expects " + httpBaseUrl + resourceName + " to exist)", 200, ret); }
From source file:org.ejbca.ui.web.pub.cluster.WebEjbcaHealthCheckTest.java
/** * Creates a number of threads that bombards the health check servlet 1000 * times each/*from w w w .j av a 2 s . co m*/ */ @Test public void testEjbcaHealthHttp() throws Exception { log.trace(">testEjbcaHealthHttp()"); // Make a quick test first that it works at all before starting all threads final HttpURLConnection con = getHttpURLConnection(httpReqPath); int ret = con.getResponseCode(); log.debug("HTTP response code: " + ret + ". Response message: " + con.getResponseMessage()); if (ret != 200) { final InputStream errStream = con.getErrorStream(); if (errStream != null) { final String errStr = Streams.asString(errStream); log.error("HTTP response error message:\n" + errStr); } fail("Got HTTP error response " + ret + ". See ERROR log message."); } assertEquals("Response code", 200, ret); String retStr = Streams.asString(con.getInputStream()); log.debug("Return String: " + retStr); assertEquals("ALLOK", retStr); con.disconnect(); // Create several threads to test long before = System.currentTimeMillis(); createThreads(); long after = System.currentTimeMillis(); long diff = after - before; log.info("All threads finished. Total time: " + diff + " ms"); assertTrue("Healt check test(s) timed out, took " + diff + " ms to complete.", diff < 40L * 1000L); log.trace("<testEjbcaHealthHttp()"); }
From source file:org.ejbca.ui.web.pub.HttpMethodsTest.java
/** Do a HTTP GET. */ private int getUrl(String url) throws IOException { final HttpURLConnection con = getHttpURLConnection(url); int ret = con.getResponseCode(); log.debug("HTTP response code: " + ret + ". Response message: " + con.getResponseMessage()); if (ret == 200) { log.debug(Streams.asString(con.getInputStream())); }/*from ww w .jav a 2 s .co m*/ con.disconnect(); return ret; }
From source file:org.elfinder.servlets.AbstractConnectorServlet.java
/** * Parse request parameters and files./*from www . ja va2 s.c om*/ * @param request * @param response */ protected void parseRequest(HttpServletRequest request, HttpServletResponse response) { requestParams = new HashMap<String, Object>(); listFiles = new ArrayList<FileItemStream>(); listFileStreams = new ArrayList<ByteArrayOutputStream>(); // Parse the request if (ServletFileUpload.isMultipartContent(request)) { // multipart request try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { listFiles.add(item); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); listFileStreams.add(os); } } } } catch (Exception e) { logger.error("Unexpected error parsing multipart content", e); } } else { // not a multipart for (Object mapKey : request.getParameterMap().keySet()) { String mapKeyString = (String) mapKey; if (mapKeyString.endsWith("[]")) { // multiple values String values[] = request.getParameterValues(mapKeyString); List<String> listeValues = new ArrayList<String>(); for (String value : values) { listeValues.add(value); } requestParams.put(mapKeyString, listeValues); } else { // single value String value = request.getParameter(mapKeyString); requestParams.put(mapKeyString, value); } } } }