List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data) throws IOException
From source file:it.drwolf.ridire.session.async.Mapper.java
@SuppressWarnings("unchecked") private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager) throws IOException, InterruptedException { String workingDirName = System.getProperty("java.io.tmpdir"); String userDir = System.getProperty("user.dir"); byte[] buf = new byte[Mapper.BUFLENGTH]; int count = 0; GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((count = gzis.read(buf)) != -1) { baos.write(buf, 0, count);/* w w w. j av a 2s . c o m*/ } gzis.close(); baos.close(); byte[] byteArray = baos.toByteArray(); String uuid = UUID.randomUUID().toString(); String pdfFileName = uuid + ".pdf"; String htmlFileName = uuid + ".html"; File tmpDir = new File(workingDirName); String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName; File fileToConvert = new File(tmpDir, pdfFileName); FileUtils.writeByteArrayToFile(fileToConvert, byteArray); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY); CommandLine commandLine = CommandLine.parse(cp.getCommandValue()); commandLine.addArgument("-c"); commandLine.addArgument("-i"); commandLine.addArgument(fileToConvert.getAbsolutePath()); commandLine.addArgument(htmlFileNameCompletePath); executor.setExitValue(0); executor.execute(commandLine); try { FileUtils.moveFileToDirectory( new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false); } catch (IOException e) { } cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY); commandLine = CommandLine .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue()); commandLine.addArgument(htmlFileNameCompletePath); commandLine.addArgument("39"); commandLine.addArgument("6"); commandLine.addArgument("5"); executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null); executor.setStreamHandler(executeStreamHandler); int exitValue = executor.execute(commandLine); String htmlString = null; if (exitValue == 0) { htmlString = baosStdOut.toString(); } FileUtils.deleteQuietly(new File(htmlFileNameCompletePath)); PrefixFileFilter pff = new PrefixFileFilter(uuid); for (File f : FileUtils.listFiles(tmpDir, pff, null)) { FileUtils.deleteQuietly(f); } if (htmlString != null) { htmlString = htmlString.replaceAll(" ", " "); htmlString = htmlString.replaceAll("<br.*?>", " "); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(htmlString.getBytes()); String encoding = charsetDetector.detect().getName(); return new StringWithEncoding(htmlString, encoding); } return null; }
From source file:fr.novia.zaproxyplugin.ZAProxy.java
/** * Generates security report for one format. Reports are saved into build's workspace. * /*ww w . ja va 2 s. c o m*/ * @param reportFormat the format of the report * @param listener the listener to display log during the job execution in jenkins * @param workspace a {@link FilePath} representing the build's workspace * @param clientApi the ZAP client API to call method * @throws ClientApiException * @throws IOException */ private void saveReport(ZAPreport reportFormat, BuildListener listener, FilePath workspace, ClientApi clientApi) throws IOException, ClientApiException { final String fullFileName = evaluatedFilenameReports + "." + reportFormat.getFormat(); File reportsFile = new File(workspace.getRemote(), fullFileName); FileUtils.writeByteArrayToFile(reportsFile, reportFormat.generateReport(clientApi, API_KEY)); listener.getLogger().println("File [" + reportsFile.getAbsolutePath() + "] saved"); }
From source file:com.igormaznitsa.zxpoly.MainForm.java
private void menuServiceSaveScreenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuServiceSaveScreenActionPerformed final RenderedImage img = this.board.getVideoController().makeCopyOfCurrentPicture(); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); this.stepSemaphor.lock(); try {/*from ww w .j a va2s. com*/ ImageIO.write(img, "png", buffer); final File thefile = chooseFileForSave("Save screenshot", lastScreenshotFolder, new PNGFileFilter()); if (thefile != null) { this.lastScreenshotFolder = thefile.getParentFile(); FileUtils.writeByteArrayToFile(thefile, buffer.toByteArray()); } } catch (IOException ex) { JOptionPane.showMessageDialog(this, "Can't save screenshot for error, see the log!", "Error", JOptionPane.ERROR_MESSAGE); log.log(Level.SEVERE, "Can't make screenshot", ex); } finally { this.keyboardAndTapeModule.doReset(); this.stepSemaphor.unlock(); } }
From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java
/** * create local topology files /local-dir/nimbus/topologyId/stormjar.jar * /local-dir/nimbus/topologyId/stormcode.ser * /local-dir/nimbus/topologyId/stormconf.ser * * @param conf// ww w. j av a 2 s . c o m * @param topologyId * @param tmpJarLocation * @param stormConf * @param topology * @throws IOException */ private void setupStormCode(Map<Object, Object> conf, String topologyId, String tmpJarLocation, Map<Object, Object> stormConf, StormTopology topology) throws IOException { // local-dir/nimbus/stormdist/topologyId String stormroot = StormConfig.masterStormdistRoot(conf, topologyId); FileUtils.forceMkdir(new File(stormroot)); FileUtils.cleanDirectory(new File(stormroot)); // copy jar to /local-dir/nimbus/topologyId/stormjar.jar setupJar(conf, tmpJarLocation, stormroot); // serialize to file /local-dir/nimbus/topologyId/stormcode.ser FileUtils.writeByteArrayToFile(new File(StormConfig.stormcode_path(stormroot)), Utils.serialize(topology)); // serialize to file /local-dir/nimbus/topologyId/stormconf.ser FileUtils.writeByteArrayToFile(new File(StormConfig.stormconf_path(stormroot)), Utils.serialize(stormConf)); // Update downloadCode timeStamp StormConfig.write_nimbus_topology_timestamp(data.getConf(), topologyId, System.currentTimeMillis()); }
From source file:info.raack.appliancelabeler.data.JDBCDatabase.java
@Override public void saveAlgorithmResult(final AlgorithmResult result) { int id = -1;/*from w ww . j av a 2 s . c o m*/ try { id = jdbcTemplate.queryForInt( "select id from algorithm_models where energy_monitor_id = ? and detection_algorithm = ?", new Object[] { result.getMonitor().getId(), result.getAlgorithm().getId() }); } catch (EmptyResultDataAccessException e) { // no model saved yet - no problem } byte[] bytes = SerializationUtils.serialize(result.getResult()); if (result.getResult() instanceof byte[]) { logger.debug("Attempting to save model with " + ((byte[]) result.getResult()).length + " bytes"); } if (id > 0) { // algorithm row already exists - update FileUtils.deleteQuietly(getResultFile(result.getMonitor().getId())); } else { // does not exist - add new row jdbcTemplate.update( "insert into algorithm_models (energy_monitor_id, detection_algorithm) values (?, ?)", new Object[] { result.getMonitor().getId(), result.getAlgorithm().getId() }); } try { FileUtils.writeByteArrayToFile(getResultFile(result.getMonitor().getId()), bytes); } catch (IOException e) { throw new RuntimeException("Could not save model result to file", e); } }
From source file:com.t3.client.TabletopTool.java
/** * If we're running on OSX we should call this method to download and * install the TabletopTool logo from the main web site. We cache this image so * that it appears correctly if the application is later executed in * "offline" mode, so to speak.//from w w w . ja va 2 s. co m */ private static void macOSXicon() { // If we're running on OSX, add the dock icon image // -- and change our application name to just "TabletopTool" (not currently) // We wait until after we call initialize() so that the asset and image managers // are configured. Image img = null; File logoFile = new File(AppUtil.getAppHome("config"), "tabletoptool-dock-icon.png"); URL logoURL = null; try { logoURL = new URL("http://services.tabletoptool.com/logo_large.png"); } catch (MalformedURLException e) { showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e); } try { img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile)); } catch (IOException e) { log.debug("Attemping to read cached icon: " + logoFile, e); try { img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL)); // If we did download the logo, save it to the 'config' dir for later use. BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null), null); FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png")); img = bimg; } catch (IOException e1) { log.warn("Cannot read '" + logoURL + "' or cached '" + logoFile + "'; no dock icon", e1); } } /* * Unfortunately the next line doesn't allow Eclipse to compile the code * on anything but a Mac. Too bad because there's no problem at runtime * since this code wouldn't be executed an any machine *except* a Mac. * Sigh. * * com.apple.eawt.Application appl = * com.apple.eawt.Application.getApplication(); */ try { Class<?> appClass = Class.forName("com.apple.eawt.Application"); Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null); Object appl = getApplication.invoke(null, (Object[]) null); Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage", new Class[] { java.awt.Image.class }); // If we couldn't grab the image for some reason, don't set the dock bar icon! Duh! if (img != null) setDockIconImage.invoke(appl, new Object[] { img }); if (T3Util.isDebugEnabled()) { // For some reason Mac users don't like the dock badge icon. But from a development standpoint I like seeing the // version number in the dock bar. So we'll only include it when running with T3_DEV on the command line. Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge", new Class[] { java.lang.String.class }); String vers = getVersion(); vers = vers.substring(vers.length() - 2); vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes setDockIconBadge.invoke(appl, new Object[] { vers }); } } catch (Exception e) { log.info( "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes", e); } }
From source file:net.rptools.maptool.client.MapTool.java
/** * If we're running on OSX we should call this method to download and * install the MapTool logo from the main web site. We cache this image so * that it appears correctly if the application is later executed in * "offline" mode, so to speak.//from w w w .j a v a2 s. co m */ private static void macOSXicon() { // If we're running on OSX, add the dock icon image // -- and change our application name to just "MapTool" (not currently) // We wait until after we call initialize() so that the asset and image managers // are configured. Image img = null; File logoFile = new File(AppUtil.getAppHome("config"), "maptool-dock-icon.png"); URL logoURL = null; try { logoURL = new URL("http://www.rptools.net/images/logo/RPTools_Map_Logo.png"); } catch (MalformedURLException e) { showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e); } try { img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile)); } catch (IOException e) { log.debug("Attemping to read cached icon: " + logoFile, e); try { img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL)); // If we did download the logo, save it to the 'config' dir for later use. BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null), null); FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png")); img = bimg; } catch (IOException e1) { log.warn("Cannot read '" + logoURL + "' or cached '" + logoFile + "'; no dock icon", e1); } } /* * Unfortunately the next line doesn't allow Eclipse to compile the code * on anything but a Mac. Too bad because there's no problem at runtime * since this code wouldn't be executed an any machine *except* a Mac. * Sigh. * * com.apple.eawt.Application appl = * com.apple.eawt.Application.getApplication(); */ try { Class<?> appClass = Class.forName("com.apple.eawt.Application"); Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null); Object appl = getApplication.invoke(null, (Object[]) null); Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage", new Class[] { java.awt.Image.class }); // If we couldn't grab the image for some reason, don't set the dock bar icon! Duh! if (img != null) setDockIconImage.invoke(appl, new Object[] { img }); if (MapToolUtil.isDebugEnabled()) { // For some reason Mac users don't like the dock badge icon. But from a development standpoint I like seeing the // version number in the dock bar. So we'll only include it when running with MAPTOOL_DEV on the command line. Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge", new Class[] { java.lang.String.class }); String vers = getVersion(); vers = vers.substring(vers.length() - 2); vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes setDockIconBadge.invoke(appl, new Object[] { vers }); } } catch (Exception e) { log.info( "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes", e); } }
From source file:ddf.test.itests.catalog.TestCatalog.java
private File createTemporaryFile(String fileName, InputStream data) throws IOException { File file = new File(fileName); if (!file.createNewFile()) { fail("Unable to create " + fileName + " file."); }//from w ww . j a v a2 s. c om FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(data)); return file; }
From source file:controllers.ParseController.java
@RequestMapping("/addFile") public String addFile(Map<String, Object> model, @RequestParam("newFile") MultipartFile file) throws IOException { File newFile = new File("/usr/local/etc/newFile"); if (!newFile.exists()) { FileUtils.writeByteArrayToFile(newFile, file.getBytes()); } else {//from www. j ava 2s. c o m newFile.delete(); FileUtils.writeByteArrayToFile(newFile, file.getBytes()); } if (newFile.exists()) { JsonReader reader = new JsonReader(new FileReader(newFile)); try { reader.beginObject(); while (reader.hasNext()) { String objectName = reader.nextName(); if (objectName.equals("colors")) { reader.beginObject(); while (reader.hasNext()) { String colorNameId = reader.nextName(); reader.beginObject(); Long oldColorId = Long.valueOf("0"); String title = "0"; String titleEng = "0"; while (reader.hasNext()) { String objectField = reader.nextName(); if (objectField.equals("id")) { oldColorId = reader.nextLong(); } if (objectField.equals("title")) { title = reader.nextString(); } if (objectField.equals("title_eng")) { titleEng = reader.nextString(); } if (objectField.equals("aliases")) { String oldId = ""; String name = ""; if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) { reader.beginArray(); reader.endArray(); oldId = "0"; name = "? "; Color c = new Color(); c.setName(name); c.setTitle(title); c.setTitleEng(titleEng); c.setOldGroupId(oldColorId); c.setOldId(Long.valueOf(oldId)); colorService.createColor(c); //keys.add(oldColorId + " - " + title + " - " + titleEng + " - " + oldId + " - " + name); } else { reader.beginObject(); while (reader.hasNext()) { oldId = reader.nextName(); name = reader.nextString(); Color c = new Color(); c.setName(name); c.setTitle(title); c.setTitleEng(titleEng); c.setOldGroupId(oldColorId); c.setOldId(Long.valueOf(oldId)); colorService.createColor(c); //keys.add(oldColorId + " - " + title + " - " + titleEng + " - " + oldId + " - " + name); } reader.endObject(); } } } reader.endObject(); } reader.endObject(); } else if (objectName.equals("color_groups")) { reader.beginObject(); while (reader.hasNext()) { String colorGroupNameId = reader.nextName(); reader.beginObject(); Long oldGroupId = Long.valueOf("0"); String title = ""; while (reader.hasNext()) { String objectField = reader.nextName(); if (objectField.equals("id")) { oldGroupId = reader.nextLong(); } else if (objectField.equals("title")) { title = reader.nextString(); } else if (objectField.equals("aliases")) { reader.beginObject(); while (reader.hasNext()) { String oldId = reader.nextName(); String name = reader.nextString(); ColorGroup cg = new ColorGroup(); cg.setName(name); cg.setTitle(title); cg.setOldGroupId(oldGroupId); cg.setOldId(Long.valueOf(oldId)); colorGroupService.createColorGroup(cg); //keys.add(oldGroupId + " - " + title + " - " + oldId + " - " + name); } reader.endObject(); } } reader.endObject(); } reader.endObject(); //keys.add(name); } else if (objectName.equals("features")) { reader.beginObject(); while (reader.hasNext()) { String featureNameId = reader.nextName(); reader.beginObject(); Long featureId = Long.valueOf("0"); String title = ""; String description = ""; Long cmgId = null; Long ccoId = null; String media = ""; while (reader.hasNext()) { String objectField = reader.nextName(); if (objectField.equals("id")) { featureId = reader.nextLong(); } else if (objectField.equals("title")) { title = reader.nextString(); } else if (objectField.equals("description")) { description = reader.nextString(); } else if (objectField.equals("car_model_generation_id")) { if (!reader.peek().equals(JsonToken.NULL)) { cmgId = reader.nextLong(); } else { reader.skipValue(); } } else if (objectField.equals("car_completion_option_id")) { if (!reader.peek().equals(JsonToken.NULL)) { ccoId = reader.nextLong(); } else { reader.skipValue(); } } else if (objectField.equals("media")) { //reader.skipValue(); if (reader.peek().equals(JsonToken.BEGIN_OBJECT)) { reader.beginObject(); while (reader.hasNext()) { if (reader.peek().equals(JsonToken.NAME)) { String mediaName = reader.nextName(); media += mediaName + " : [ "; reader.beginArray(); while (reader.hasNext()) { media += " { "; reader.beginObject(); while (reader.hasNext()) { String mediaParamName = reader.nextName(); media += mediaParamName + " : "; if (!mediaParamName.equals("url")) { if (!reader.peek().equals(JsonToken.NULL)) { media += reader.nextString(); } else { reader.skipValue(); media += "null"; } } else { reader.beginObject(); media += "{"; while (reader.hasNext()) { media += reader.nextName() + " : " + reader.nextString(); } media += "}"; reader.endObject(); } } reader.endObject(); media += " } "; } reader.endArray(); media += " ] "; } } reader.endObject(); } else { reader.skipValue(); } } } reader.endObject(); Feature f = new Feature(); f.setOldId(featureId); f.setTitle(title); f.setDescription(description); f.setCmgId(cmgId); f.setCcoId(ccoId); f.setMedia(media); //keys.add(featureId + " - " + title + " - " + description + " - " + cmgId + " - " + ccoId + " - " + media); featureService.createFeature(f); } reader.endObject(); } else { reader.skipValue(); } } reader.endObject(); reader.close(); } catch (Exception e) { model.put("error", "? ? :" + StringAdapter.getStackTraceException(e)); reader.close(); return "ParseShow"; } } return "redirect:/ParseController/show"; }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Create an atome and return to the choice create atome * @param request the Http request/* w w w . ja v a2 s . c o m*/ * @throws ParseException ParseException * @return HTML * @throws IOException IOException */ public String doCreateAtome(HttpServletRequest request) throws ParseException, IOException { int nIdPlu = Integer.parseInt(request.getParameter(PARAMETER_PLU_ID)); Plu plu = _pluServices.findByPrimaryKey(nIdPlu); int nIdFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID_ATOME)); Folder folder = _folderServices.findByPrimaryKey(nIdFolder); int nIdAtome = Integer.parseInt(request.getParameter(PARAMETER_ATOME_NUM)); int numVersion = Integer.parseInt(request.getParameter(PARAMETER_VERSION_NUM)); Atome atome = new Atome(); atome.setId(nIdAtome); atome.setName(request.getParameter(PARAMETER_ATOME_NAME)); atome.setTitle(request.getParameter(PARAMETER_ATOME_TITLE)); atome.setDescription(request.getParameter(PARAMETER_ATOME_DESCRIPTION)); _atomeServices.create(atome); Version version = new Version(); version.setAtome(atome); version.setVersion(numVersion); // if the plu is approved, set the same value to the atome version.setD1(plu.getDj()); version.setD2(plu.getDa()); _versionServices.create(version); Version version2 = _versionServices.findByAtomeAndNumVersion(nIdAtome, numVersion); FolderVersion folderVersion = new FolderVersion(); folderVersion.setVersion(version2); folderVersion.setFolder(folder); _folderVersionServices.create(folderVersion); String[] fileTitle = request.getParameterValues(PARAMETER_FILE_TITLE_ATOME); String[] check = request.getParameterValues(PARAMETER_FILE_CHECK); int i = 0; int order = 1; String strNumVersion; if (numVersion < 10) { strNumVersion = "-V0" + numVersion; } else { strNumVersion = "-V" + numVersion; } for (File file : _fileList) { for (int j = 0; j < check.length; ++j) { int c = Integer.parseInt(check[j]); if (c == i) { if (!file.getTitle().equals(fileTitle[i])) { file.setTitle(fileTitle[i]); } file.setAtome(nIdAtome); file.setOrder(order); file.setVersion(version2.getId()); // Test if file name contains extension, if yes remove extension to file name // Test if file name contains extension, if yes remove // extension to file name int a = file.getName().lastIndexOf("."); String nameWithoutExt = file.getName(); String nameExt = ""; if (a > 0) { nameWithoutExt = file.getName().substring(0, a); nameExt = file.getName().substring(a); } a = nameWithoutExt.lastIndexOf("-V"); if (a > 0) { nameWithoutExt = nameWithoutExt.substring(0, a) + strNumVersion; } else { nameWithoutExt = nameWithoutExt + strNumVersion; } file.setName(nameWithoutExt + nameExt); file.setId(0); _fileServices.create(file); FileFilter fileFilter = new FileFilter(); fileFilter.setName(file.getName()); fileFilter.setTitle(file.getTitle()); AtomeFilter atomeFilter = new AtomeFilter(); atomeFilter.setId(atome.getId()); List<File> fileCreate = _fileServices.findByFilter(fileFilter, atomeFilter); java.io.File fileDest = new java.io.File( new java.io.File(AppPropertiesService.getProperty("plu.docs.path")), fileCreate.get(fileCreate.size() - 1).getId() + "_" + file.getName()); FileUtils.writeByteArrayToFile(fileDest, file.getFile()); order++; } } i++; } Date date = new Date(); Plu newPlu = _pluServices.findPluWork(); if (newPlu.getDa() != null) { newPlu.setDj(date); _pluServices.create(newPlu); } return JSP_REDIRECT_TO_TREE_PLU_ATOME + "?id_plu=" + plu.getId() + "&id_folder=" + folder.getId() + "&atome_all=1"; }