List of usage examples for org.apache.commons.io IOUtils toByteArray
public static byte[] toByteArray(String input) throws IOException
String
as a byte[]
using the default character encoding of the platform. From source file:com.thoughtworks.go.remote.work.HttpServiceStub.java
public void setupDownload(String url, File file) throws IOException { downloadFiles.put(url, IOUtils.toByteArray(new FileInputStream(file))); }
From source file:name.martingeisse.trading_game.platform.fakecdn.FakeCdn.java
/** * *///from w w w .java2 s . c om private FakeCdnRecord fetch(String key) throws IOException { HttpResponse response = fetchResponse("http://localhost" + key); byte[] data; try (InputStream responseStream = response.getEntity().getContent()) { data = IOUtils.toByteArray(responseStream); } return new FakeCdnRecord(response.getStatusLine().getStatusCode(), key, response.getFirstHeader("Content-Type").getValue(), data); }
From source file:com.smartitengineering.cms.spi.impl.AbstractRepresentationProvider.java
protected MutableRepresentation getMutableRepresentation(RepresentationGenerator generator, Content content, Map<String, String> params, String representationName) throws RuntimeException { final Object representationForContent = generator.getRepresentationForContent(content, params); final byte[] bytes; if (representationForContent instanceof String) { bytes = StringUtils.getBytesUtf8((String) representationForContent); } else if (representationForContent instanceof byte[]) { bytes = (byte[]) representationForContent; } else if (representationForContent instanceof InputStream) { try {/*from w ww .j a va 2s . co m*/ bytes = IOUtils.toByteArray((InputStream) representationForContent); } catch (Exception ex) { throw new RuntimeException(ex); } } else if (representationForContent instanceof Reader) { try { bytes = IOUtils.toByteArray((Reader) representationForContent); } catch (Exception ex) { throw new RuntimeException(ex); } } else { bytes = StringUtils.getBytesUtf8(representationForContent.toString()); } MutableRepresentation representation = SmartContentAPI.getInstance().getContentLoader() .createMutableRepresentation(content.getContentId()); final RepresentationDef def = content.getContentDefinition().getRepresentationDefs() .get(representationName); representation.setName(representationName); representation.setMimeType(def.getMIMEType()); representation.setRepresentation(bytes); return representation; }
From source file:be.fedict.eid.dss.model.bean.XmlSchemaManagerBean.java
public void add(String revision, InputStream xsdInputStream) throws InvalidXmlSchemaException, ExistingXmlSchemaException { byte[] xsd;//from ww w . j a va2 s.c o m try { xsd = IOUtils.toByteArray(xsdInputStream); } catch (IOException e) { throw new RuntimeException("IO error: " + e.getMessage(), e); } ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(xsd); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.entityManager)); StreamSource schemaSource = new StreamSource(schemaInputStream); try { schemaFactory.newSchema(schemaSource); } catch (SAXException e) { LOG.error("SAX error: " + e.getMessage(), e); throw new InvalidXmlSchemaException("SAX error: " + e.getMessage(), e); } catch (RuntimeException e) { LOG.error("Runtime exception: " + e.getMessage(), e); throw new InvalidXmlSchemaException(e.getMessage(), e); } DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException("DOM error: " + e.getMessage(), e); } schemaInputStream = new ByteArrayInputStream(xsd); Document schemaDocument; try { schemaDocument = documentBuilder.parse(schemaInputStream); } catch (Exception e) { throw new RuntimeException("DOM error: " + e.getMessage(), e); } String namespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace"); LOG.debug("namespace: " + namespace); XmlSchemaEntity existingXmlSchemaEntity = this.entityManager.find(XmlSchemaEntity.class, namespace); if (null != existingXmlSchemaEntity) { throw new ExistingXmlSchemaException(); } XmlSchemaEntity xmlSchemaEntity = new XmlSchemaEntity(namespace, revision, xsd); this.entityManager.persist(xmlSchemaEntity); }
From source file:com.ikon.dao.ReportDAO.java
/** * Create report from file//www . j ava 2 s . com */ public static long createFromFile(File repFile, String name, boolean active) throws DatabaseException, IOException { log.debug("createFromFile({}, {}, {})", new Object[] { repFile, name, active }); Session session = null; Transaction tx = null; FileInputStream fis = null; try { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); fis = new FileInputStream(repFile); // Fill bean Report rp = new Report(); rp.setName(name); rp.setFileName(repFile.getName()); rp.setFileMime(MimeTypeConfig.mimeTypes.getContentType(repFile.getName())); rp.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(fis))); rp.setActive(active); Long id = (Long) session.save(rp); HibernateUtil.commit(tx); log.debug("createFromFile: {}", id); return id; } catch (HibernateException e) { HibernateUtil.rollback(tx); throw new DatabaseException(e.getMessage(), e); } catch (IOException e) { HibernateUtil.rollback(tx); throw e; } finally { IOUtils.closeQuietly(fis); HibernateUtil.close(session); } }
From source file:com.bagdemir.eboda.handler.MemoryResourceHandler.java
private void readResourceIfExists(final String resourceName) { try {//from www . j a v a 2 s .c om final byte[] bytes = IOUtils.toByteArray(getClass().getClassLoader().getResource(resourceName)); final ByteArrayResource byteArrayResource = new ByteArrayResource(bytes, MIME_IMAGE_GIF); inMemoryResources.put(resourceName, byteArrayResource); } catch (IOException e) { LOGGER.error(e); } }
From source file:com.illmeyer.polygraph.syslib.tags.LoadPartTag.java
@Override public void execute(PolygraphEnvironment env) throws IOException { // TODO: Check if IOException comes from URL stream or not if ((url == null) == (vfs == null)) throw new PolygraphTemplateException("Exactly one of the parameters 'url' and 'vfs' must be specified"); MessagePart p = new MessagePart(); if (url != null) { URL u = new URL(url); @Cleanup// w w w .ja va2s . co m InputStream is = u.openStream(); p.setMessage(IOUtils.toByteArray(is)); } if (vfs != null) { @Cleanup InputStream is = env.getVfsStream(vfs); p.setMessage(IOUtils.toByteArray(is)); } env.registerMessagePart(name, p); }
From source file:com.baran.file.FileOperator.java
public static byte[] readFileToBinaryArray(File file) { byte[] bin = null; try {/*from w ww .jav a2 s . c o m*/ InputStream is = new FileInputStream(file); // commons-io-2.4.jar bin = IOUtils.toByteArray(is); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bin; }
From source file:edu.eci.pdsw.samples.managedbeans.PagoAfiliacionBean.java
public void handleFileUpload(FileUploadEvent event) throws IOException { file = event.getFile(); img = IOUtils.toByteArray(file.getInputstream()); }
From source file:edu.um.umflix.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, String> mapValues = new HashMap<String, String>(); List<Clip> clips = new ArrayList<Clip>(); List<Byte[]> listData = new ArrayList<Byte[]>(); int i = 0;//w ww . ja v a2 s. c om try { List<FileItem> items = getFileItems(request); for (FileItem item : items) { if (item.isFormField()) { // Process normal fields here. mapValues.put(item.getFieldName(), item.getString()); // w.print("Field name: " + item.getFieldName()); // w.print("Field value: " + item.getString()); } else { // Process <input type="file"> here. InputStream movie = item.getInputStream(); byte[] bytes = IOUtils.toByteArray(movie); Byte[] clipBytes = ArrayUtils.toObject(bytes); Clip clip = new Clip(Long.valueOf(0), i); clips.add(i, clip); listData.add(i, clipBytes); i++; // w.print(movie); } } } catch (FileUploadException e) { log.error("Error uploading file, please try again."); request.setAttribute("error", "Error uploading file, please try again"); request.setAttribute("token", mapValues.get("token")); request.getRequestDispatcher("/upload.jsp").forward(request, response); } //Sets duration of clip and saves clipdata for (int j = 0; j < clips.size(); j++) { int duration = timeToInt(mapValues.get("clipduration" + j)); clips.get(j).setDuration(Long.valueOf(duration)); ClipData clipData = new ClipData(listData.get(j), clips.get(j)); try { vManager.uploadClip(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), clipData); log.info("ClipData uploader!"); } catch (InvalidTokenException e) { log.error("Unknown user, please try again."); request.setAttribute("error", "Unknown user, please try again."); request.getRequestDispatcher("/index.jsp").forward(request, response); return; } } DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date endDate = null; Date startDate = null; Date premiereDate = null; try { endDate = formatter.parse(mapValues.get("endDate")); startDate = formatter.parse(mapValues.get("startDate")); premiereDate = formatter.parse(mapValues.get("premiere")); } catch (ParseException e) { log.error("Error parsing date"); request.setAttribute("token", mapValues.get("token")); request.setAttribute("error", "Invalid date, please try again"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return; } License license = new License(false, Long.valueOf(0), mapValues.get("licenseDescription"), endDate, Long.valueOf(mapValues.get("maxViews")), Long.valueOf(1), startDate, mapValues.get("licenseName")); List<License> licenses = new ArrayList<License>(); licenses.add(license); ArrayList<String> cast = new ArrayList<String>(); cast.add(mapValues.get("actor")); Movie movie = new Movie(cast, clips, mapValues.get("director"), Long.valueOf(mapValues.get("duration")), false, mapValues.get("genre"), licenses, premiereDate, mapValues.get("title")); try { vManager.uploadMovie(mapValues.get("token"), new Role(Role.RoleType.MOVIE_PROVIDER.getRole()), movie); log.info("Movie uploaded!"); } catch (InvalidTokenException e) { log.error("Unknown user, please try again."); request.setAttribute("error", "Unknown user, please try again."); request.getRequestDispatcher("/index.jsp").forward(request, response); return; } request.setAttribute("message", "Movie uploaded successfully."); request.setAttribute("token", mapValues.get("token")); request.getRequestDispatcher("/upload.jsp").forward(request, response); }