List of usage examples for org.apache.commons.io FileUtils readFileToByteArray
public static byte[] readFileToByteArray(File file) throws IOException
From source file:com.huawei.ais.demo.TokenDemo.java
/** * Base64???Token???//from w w w. j a v a 2s. com * @param token token? * @param formFile * @throws IOException */ public static void requestOcrGeneralTextBase64(String token, String formFile) { // 1.??? String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/general-text"; Header[] headers = new Header[] { new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) }; try { byte[] fileData = FileUtils.readFileToByteArray(new File(formFile)); String fileBase64Str = Base64.encodeBase64String(fileData); JSONObject json = new JSONObject(); json.put("image", fileBase64Str); // // 1.a ???????? // detect_direction?:true, false // json.put("detect_direction", false); StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8"); // 2.??, POST?? HttpResponse response = HttpClientUtils.post(url, headers, stringEntity); System.out.println(response); String content = IOUtils.toString(response.getEntity().getContent()); System.out.println(content); } catch (Exception e) { e.printStackTrace(); } }
From source file:fr.eurecom.hybris.demogui.HybrisDemoGui.java
public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Get")) { if (lstHybris.getSelectedIndex() >= 0) { try { System.out.println("Retrieving " + lstHybris.getSelectedValue() + "..."); byte[] retrieved = cm.hybris.get(lstHybris.getSelectedValue()); if (retrieved != null) { JFileChooser fc = new JFileChooser( System.getProperty("user.home") + File.separator + "Desktop"); fc.setSelectedFile(new File("RETRIEVED_" + lstHybris.getSelectedValue())); int returnVal = fc.showSaveDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); FileUtils.writeByteArrayToFile(file, retrieved); System.out.println("Saved: " + file.getName() + "."); }/*from w w w . j a va 2s. co m*/ } else JOptionPane.showMessageDialog(frame, "Hybris could not download the file.", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { e1.printStackTrace(); } } } if (cmd.equals("Put")) { JFileChooser fc = new JFileChooser(System.getProperty("user.home") + File.separator + "Desktop"); int returnVal = fc.showOpenDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); System.out.println("Putting: " + file.getName() + "."); byte[] array; try { array = FileUtils.readFileToByteArray(file); new Thread(cm.new BackgroundWorker(OperationType.PUT, ClientType.HYBRIS, file.getName(), array)) .start(); } catch (Exception e1) { e1.printStackTrace(); } } } if (cmd.equals("Delete")) { if (lstHybris.getSelectedIndex() >= 0) { new Thread(cm.new BackgroundWorker(OperationType.DELETE, ClientType.HYBRIS, lstHybris.getSelectedValue(), null)).start(); System.out.println("Removed " + lstHybris.getSelectedValue() + " from Hybris."); } } }
From source file:com.gargoylesoftware.htmlunit.html.HtmlPage2Test.java
/** * @throws Exception if the test fails/*from w ww . j a va 2s . c o m*/ */ @Test public void save_frames() throws Exception { final String mainContent = "<html><head><title>First</title></head>\n" + "<frameset cols='50%,*'>\n" + " <frame name='left' src='" + URL_SECOND + "' frameborder='1' />\n" + " <frame name='right' src='" + URL_THIRD + "' frameborder='1' />\n" + " <frame name='withoutsrc' />\n" + "</frameset>\n" + "</html>"; final String frameLeftContent = "<html><head><title>Second</title></head><body>\n" + "<iframe src='iframe.html'></iframe>\n" + "<img src='img.jpg'>\n" + "</body></html>"; final String frameRightContent = "<html><head><title>Third</title></head><body>frame right</body></html>"; final String iframeContent = "<html><head><title>Iframe</title></head><body>iframe</body></html>"; final InputStream is = getClass().getClassLoader().getResourceAsStream("testfiles/tiny-jpg.img"); final byte[] directBytes = IOUtils.toByteArray(is); is.close(); final WebClient webClient = getWebClientWithMockWebConnection(); final MockWebConnection webConnection = getMockWebConnection(); webConnection.setResponse(URL_FIRST, mainContent); webConnection.setResponse(URL_SECOND, frameLeftContent); webConnection.setResponse(URL_THIRD, frameRightContent); final URL urlIframe = new URL(URL_SECOND, "iframe.html"); webConnection.setResponse(urlIframe, iframeContent); final List<NameValuePair> emptyList = Collections.emptyList(); final URL urlImage = new URL(URL_SECOND, "img.jpg"); webConnection.setResponse(urlImage, directBytes, 200, "ok", "image/jpg", emptyList); final HtmlPage page = webClient.getPage(URL_FIRST); final HtmlFrame leftFrame = page.getElementByName("left"); assertEquals(URL_SECOND.toString(), leftFrame.getSrcAttribute()); final File tmpFolder = tmpFolderProvider_.newFolder("hu"); final File file = new File(tmpFolder, "hu_HtmlPageTest_saveFrame.html"); final File expectedLeftFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second.html"); final File expectedRightFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/third.html"); final File expectedIFrameFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second/iframe.html"); final File expectedImgFile = new File(tmpFolder, "hu_HtmlPageTest_saveFrame/second/img.jpg"); final File[] allFiles = { file, expectedLeftFrameFile, expectedImgFile, expectedIFrameFile, expectedRightFrameFile }; page.save(file); for (final File f : allFiles) { assertTrue(f.toString(), f.exists()); assertTrue(f.toString(), f.isFile()); } final byte[] loadedBytes = FileUtils.readFileToByteArray(expectedImgFile); assertTrue(loadedBytes.length > 0); // ensure that saving the page hasn't changed the DOM assertEquals(URL_SECOND.toString(), leftFrame.getSrcAttribute()); }
From source file:com.abm.mainet.water.ui.model.PlumberLicenseFormModel.java
/** * This method is used for generating byte code for uploaded files * //from w w w .jav a 2s. com * @param docs * is list of uploaded file * @return uploaded file name and byte code */ @SuppressWarnings("static-access") private List<DocumentDetailsVO> setFileUploadMethod(List<DocumentDetailsVO> docs) { Map<Long, String> listOfString = new HashMap<Long, String>(); Map<Long, String> fileName = new HashMap<Long, String>(); if (fileupload.getCurrent().getFileMap() != null && !fileupload.getCurrent().getFileMap().isEmpty()) { for (Iterator<Entry<Long, Set<File>>> it = FileUploadUtility.getCurrent().getFileMap().entrySet() .iterator(); it.hasNext();) { Entry<Long, Set<File>> entry = it.next(); if (entry.getKey().longValue() == 0) { it.remove(); break; } } for (Map.Entry<Long, Set<File>> entry : fileupload.getCurrent().getFileMap().entrySet()) { List<File> list = new ArrayList<File>(entry.getValue()); for (File file : list) { try { Base64 base64 = new Base64(); String bytestring = base64.encodeToString(FileUtils.readFileToByteArray(file)); fileName.put(entry.getKey(), file.getName()); listOfString.put(entry.getKey(), bytestring); } catch (IOException e) { logger.error("Exception has been occurred in file byte to string conversions", e); } } } } if (!docs.isEmpty() && !listOfString.isEmpty()) { for (DocumentDetailsVO d : docs) { long count = d.getDocumentSerialNo(); if (listOfString.containsKey(count) && fileName.containsKey(count)) { d.setDocumentByteCode(listOfString.get(count)); d.setDocumentName(fileName.get(count)); } } } return docs; }
From source file:com.alibaba.jstorm.cluster.StormConfig.java
public static long read_supervisor_topology_timestamp(Map conf, String topologyId) throws IOException { String stormRoot = supervisor_stormdist_root(conf, topologyId); String timeStampPath = stormts_path(stormRoot); byte[] data = FileUtils.readFileToByteArray(new File(timeStampPath)); return JStormUtils.bytesToLong(data); }
From source file:com.hangum.tadpole.rdb.core.dialog.export.sqlresult.ResultSetDownloadDialog.java
/** * download file/*w ww . j ava2 s . c o m*/ * @param strFileLocation * @throws Exception */ protected void downloadFile(String fileName, String strFileLocation, String encoding) throws Exception { //TODO: ? ? ... String strZipFile = ZipUtils.pack(strFileLocation); byte[] bytesZip = FileUtils.readFileToByteArray(new File(strZipFile)); _downloadExtFile(fileName + ".zip", bytesZip); //$NON-NLS-1$ }
From source file:com.frostwire.bittorrent.BTEngine.java
File readTorrentPath(String infoHash) { File torrent = null;/*from w w w. ja va2 s . co m*/ try { byte[] arr = FileUtils.readFileToByteArray(resumeTorrentFile(infoHash)); entry e = entry.bdecode(Vectors.bytes2byte_vector(arr)); torrent = new File(e.dict().get(TORRENT_ORIG_PATH_KEY).string()); } catch (Throwable e) { // can't recover original torrent path } return torrent; }
From source file:com.redhat.red.offliner.Main.java
/** * Creates a new {@link Callable} capable of downloading a single file from a path and a set of base URLs, or * determining that the file has already been downloaded. If the checksums map is given, attempt to verify the * checksum of the file in the target directory or the stream as it's being downloaded. * @param baseUrls The list of base URLs representing the repositories from which files should be downloaded. * Each will be tried in order when downloading a path, until one works. * @param path The path to attempt to download from one of the repositories given in baseUrls * @param checksums The map of path -> checksum to use when attempting to verify the integrity of existing files or * the download stream/*from www .j av a 2 s . c om*/ * @return The Callable that will perform the actual download. At this point it will NOT have been queued for * execution. */ private Callable<DownloadResult> newDownloader(final List<String> baseUrls, final String path, final Map<String, String> checksums) { final Logger logger = LoggerFactory.getLogger(getClass()); return () -> { final String name = Thread.currentThread().getName(); Thread.currentThread().setName("download--" + path); try { final File target = new File(opts.getDownloads(), path); if (target.exists()) { if (null == checksums || checksums.isEmpty() || !checksums.containsKey(path) || null == checksums.get(path)) { return DownloadResult.avoid(path, true); } byte[] b = FileUtils.readFileToByteArray(target); String original = checksums.get(path); String current = sha256Hex(b); if (original.equals(current)) { return DownloadResult.avoid(path, true); } } final File dir = target.getParentFile(); dir.mkdirs(); final File part = new File(dir, target.getName() + ".part"); part.deleteOnExit(); int reposRemaining = baseUrls.size(); for (String baseUrl : baseUrls) { reposRemaining--; String url; try { url = UrlUtils.buildUrl(baseUrl, path); } catch (final Exception e) { return DownloadResult.error(path, e); } System.out.println(">>>Downloading: " + url); final HttpClientContext context = new HttpClientContext(); context.setCookieStore(cookieStore); final HttpGet request = new HttpGet(url); try (CloseableHttpResponse response = client.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { try (ChecksumOutputStream out = new ChecksumOutputStream(new FileOutputStream(part))) { IOUtils.copy(response.getEntity().getContent(), out); if (checksums != null) { String checksum = checksums.get(path); if (checksum != null && !isBlank(checksum) && !checksum.equalsIgnoreCase(out.getChecksum())) { return DownloadResult.error(path, new IOException("Checksum mismatch on file: " + path + " (calculated: '" + out.getChecksum() + "'; expected: '" + checksum + "')")); } } } part.renameTo(target); return DownloadResult.success(baseUrl, path); } else if (statusCode == 404) { System.out.println("<<<Not Found: " + url); if (reposRemaining == 0) { return DownloadResult.error(path, new IOException( "Error downloading path: " + path + ". The artifact was not " + "found in any of the provided repositories.")); } } else { final String serverError = IOUtils.toString(response.getEntity().getContent()); String message = String.format( "Error downloading path: %s.\n%s\nServer status: %s\nServer response was:\n%s\n%s", path, SEP, response.getStatusLine(), serverError, SEP); if (reposRemaining == 0) { return DownloadResult.error(path, new IOException(message)); } else { System.out.println("<<<" + message); } } } catch (final IOException e) { if (logger.isTraceEnabled()) { logger.error("Download failed for: " + url, e); } return DownloadResult.error(path, new IOException("URL: " + url + " failed.", e)); } finally { if (request != null) { request.releaseConnection(); if (request instanceof AbstractExecutionAwareRequest) { ((AbstractExecutionAwareRequest) request).reset(); } } } } } finally { Thread.currentThread().setName(name); } return null; }; }
From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java
public void attach() { selectedDir = cb.getVfsUrl();/* ww w .j a va2 s. c o m*/ try { final VFSFileExplorerPortlet app = instance; final User user = (User) app.getUser(); final FileSystemManager fFileSystemManager = fileSystemManager; final FileSystemOptions fOpts = opts; final Table table = new Table() { private static final long serialVersionUID = 1L; protected String formatPropertyValue(Object rowId, Object colId, Property property) { if (TABLE_PROP_FILE_NAME.equals(colId)) { if (property != null && property.getValue() != null) { return getDisplayPath(property.getValue().toString()); } } if (TABLE_PROP_FILE_DATE.equals(colId)) { if (property != null && property.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss"); return sdf.format((Date) property.getValue()); } } return super.formatPropertyValue(rowId, colId, property); } }; table.setSizeFull(); table.setMultiSelect(true); table.setSelectable(true); table.setImmediate(true); table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null); table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null); table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null); if (app != null) { app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() { private static final long serialVersionUID = 1L; @Override public void onValueChanged(TableChangedEvent event) { try { selectedDir = event.getNewDirectory(); fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } }); } table.addListener(new Table.ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { Set<?> value = (Set<?>) event.getProperty().getValue(); if (null == value || value.size() == 0) { markedRows = null; } else { markedRows = value; } } }); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); Button btDownload = new Button("Download File(s)"); btDownload.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { String[] files = new String[markedRows.size()]; int fileCount = 0; for (Object item : markedRows) { Item it = table.getItem(item); files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); fileCount++; } File dlFile = null; if (fileCount == 1) { try { String fileName = files[0]; dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); } catch (Exception e) { e.printStackTrace(); } } else { byte[] buf = new byte[1024]; try { dlFile = File.createTempFile("Files", ".zip"); ZipOutputStream out = new ZipOutputStream( new FileOutputStream(dlFile.getAbsolutePath())); for (int i = 0; i < files.length; i++) { String fileName = files[i]; logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); FileInputStream in = new FileInputStream(f); out.putNextEntry(new ZipEntry(f.getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { } } if (dlFile != null) { try { DownloadResource downloadResource = new DownloadResource(dlFile, getApplication()); getApplication().getMainWindow().open(downloadResource, "_new"); } catch (FileNotFoundException e) { getWindow().showNotification("File not found !", Window.Notification.TYPE_ERROR_MESSAGE); e.printStackTrace(); } } if (dlFile != null) { dlFile.delete(); } } } }); Button btDelete = new Button("Delete File(s)"); btDelete.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { for (Object item : markedRows) { Item it = table.getItem(item); String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); logger.log(Level.INFO, "Delete File " + fileToDelete); try { FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts); logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by " + user.getScreenName()); boolean b = delFile.delete(); if (b) logger.log(Level.INFO, "delete ok"); else logger.log(Level.INFO, "delete failed"); } catch (FileSystemException e) { e.printStackTrace(); } } try { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } } }); Button selAll = new Button("Select All", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(table.getItemIds()); } }); Button selNone = new Button("Select None", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(null); } }); final UploadReceiver receiver = new UploadReceiver(); upload = new Upload(null, receiver); upload.setImmediate(true); upload.setButtonCaption("File Upload"); upload.addListener((new Upload.SucceededListener() { private static final long serialVersionUID = 1L; public void uploadSucceeded(SucceededEvent event) { try { String fileName = receiver.getFileName(); ByteArrayOutputStream bos = receiver.getUploadedFile(); byte[] buf = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); app.getMainWindow().showNotification("Upload " + fileName + " successful ! ", Notification.TYPE_TRAY_NOTIFICATION); } catch (Exception e) { e.printStackTrace(); } } })); upload.addListener(new Upload.FailedListener() { private static final long serialVersionUID = 1L; public void uploadFailed(FailedEvent event) { System.out.println("Upload failed ! "); } }); multiFileUpload = new MultiFileUpload() { private static final long serialVersionUID = 1L; protected void handleFile(File file, String fileName, String mimeType, long length) { try { byte[] buf = FileUtils.readFileToByteArray(file); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (FileSystemException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected FileBuffer createReceiver() { FileBuffer receiver = super.createReceiver(); /* * Make receiver not to delete files after they have been * handled by #handleFile(). */ receiver.setDeleteFiles(false); return receiver; } }; multiFileUpload.setUploadButtonCaption("Upload File(s)"); HorizontalLayout filterGrp = new HorizontalLayout(); filterGrp.setSpacing(true); final TextField tfFilter = new TextField(); Button btFileFilter = new Button("Filter", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { String filterVal = (String) tfFilter.getValue(); try { if (filterVal == null || filterVal.length() == 0) { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } else { fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal); } } catch (IOException e) { e.printStackTrace(); } } }); Button btResetFileFilter = new Button("Reset", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { try { tfFilter.setValue(""); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (ReadOnlyException e) { e.printStackTrace(); } catch (ConversionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); filterGrp.addComponent(tfFilter); filterGrp.addComponent(btFileFilter); filterGrp.addComponent(btResetFileFilter); addComponent(filterGrp); addComponent(table); HorizontalLayout btGrp = new HorizontalLayout(); btGrp.setSpacing(true); btGrp.addComponent(selAll); btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER); btGrp.addComponent(selNone); btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER); btGrp.addComponent(btDownload); btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER); List<Role> roles = null; boolean matchUserRole = false; try { if (user != null) { roles = user.getRoles(); } } catch (SystemException e) { e.printStackTrace(); } if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getDeleteRoles()); if (matchUserRole) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } } if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getUploadRoles()); if (matchUserRole) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } } addComponent(btGrp); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }