public static File createTestFile(long largerThanMB) throws IOException { File outputFile = new File("target/test/csv/perftest.csv"); if (outputFile.exists()) { return outputFile; } File toCopy = new File("../parquet-testdata/tpch/customer.csv"); FileUtils.copyFile( new File("../parquet-testdata/tpch/customer.schema"), new File("target/test/csv/perftest.schema")); OutputStream output = null; InputStream input = null; try { output = new BufferedOutputStream(new FileOutputStream(outputFile, true)); input = new BufferedInputStream(new FileInputStream(toCopy)); input.mark(Integer.MAX_VALUE); while (outputFile.length() <= largerThanMB * 1024 * 1024) { // appendFile(output, toCopy); IOUtils.copy(input, output); input.reset(); } } finally { closeQuietly(input); closeQuietly(output); } return outputFile; }
private void initHomeDir() throws IOException { String[] filesToCheck = new String[] {"logs", "tmp", "log4j.xml", "templates"}; if (!Files.exists(config.getHomeDir())) { Files.createDirectories(config.getHomeDir()); } if (Files.exists(config.getHomeDir()) && Files.isDirectory(config.getHomeDir())) { for (String fileToCheck : filesToCheck) { Path sourceFile = config.getResourceFetcher().getFile(fileToCheck); if (sourceFile != null && Files.exists(sourceFile)) { Path destFile = config.getHomeDir().resolve(fileToCheck); if (!Files.exists(destFile)) { if (Files.isDirectory(sourceFile)) { Files.createDirectories(destFile); for (Path f : PathUtils.list(sourceFile)) { if (Files.isDirectory(f)) { Path destDir2 = destFile.resolve(f.getFileName().toString()); for (Path x : PathUtils.list(f)) { FileUtils.copyFile( x.toFile(), destDir2.resolve(x.getFileName().toString()).toFile()); } } else if (Files.isDirectory(f)) { FileUtils.copyFile( f.toFile(), destFile.resolve(f.getFileName().toString()).toFile()); } } } else { FileUtils.copyFile(sourceFile.toFile(), destFile.toFile()); } } } } } }
@BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("Moving test fits.xml in"); // Copy fits.xml to fits_back.xml FileUtils.copyFile(FileUtils.getFile("xml/fits.xml"), FileUtils.getFile("xml/fits_back.xml")); // Copy in test fits.xml FileUtils.copyFile( FileUtils.getFile("testfiles/properties/fits_no_md5_audio.xml"), FileUtils.getFile("xml/fits.xml")); }
@Action( value = "images-save", results = { @Result( name = "success", location = "/WEB-INF/content/ajax/customer/ajax-error-response.jsp"), @Result( name = "input", location = "/WEB-INF/content/ajax/customer/ajax-error-response.jsp"), @Result(name = "error", location = "/WEB-INF/content/ajax/customer/ajax-error-response.jsp") }) public String ImagesaveAction() throws IOException { try { if (files.size() <= 0) { request.setAttribute("imageResult", Messages.getString("emptyError")); return INPUT; } String filePathd = request.getSession().getServletContext().getRealPath("/") + "\\uploads"; String filePath = "c:/temp/"; imageList = new LinkedList<Image>(); for (int i = 0; i < files.size(); i++) { if (files.get(i).length() > 5500000) { request.setAttribute("imageResult", Messages.getString("maxSizeLimitError")); return INPUT; } Image image = new Image(); String name = imFileName.get(i); image.setName(name); image.setContentType(imContentType.get(i)); if (i != 0) { image.setIsMain(false); } else { image.setIsMain(true); } File fileToCreate = new File(filePath, name); FileUtils.copyFile(files.get(i), fileToCreate); File fileToCreated = new File(filePathd, name); FileUtils.copyFile(files.get(i), fileToCreated); imageService.saveOrUpdate(image); imageList.add(image); } session.put("imageList", imageList); request.setAttribute("imageResult", "success"); return SUCCESS; } catch (Exception e) { request.setAttribute("imageResult", Messages.getString("somethingWrong")); return ERROR; } }
/** * Takes screenshot and adds it to TestNG report. * * @param driver WebDriver instance. */ public void makeScreenshot(WebDriver driver, String screenshotName) { WebDriver augmentedDriver = new Augmenter().augment(driver); /* Take a screenshot */ File screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE); String nameWithExtention = screenshotName + ".png"; /* Copy screenshot to specific folder */ try { /*String reportFolder = "target" + File.separator + "failsafe-reports" + File.separator + "firefox" + File.separator; */ String reportFolder = "test-output" + File.separator; String screenshotsFolder = "screenshots"; File screenshotFolder = new File(reportFolder + screenshotsFolder); if (!screenshotFolder.getAbsoluteFile().exists()) { screenshotFolder.mkdir(); } FileUtils.copyFile( screenshot, new File(screenshotFolder + File.separator + nameWithExtention).getAbsoluteFile()); } catch (IOException e) { this.log("Failed to capture screenshot: " + e.getMessage()); } log(getScreenshotLink(nameWithExtention, nameWithExtention)); // add // screenshot // link // to // the // report }
public void start() { // see initialization of this property in sonar-application String driverPath = settings.getString(ProcessProperties.JDBC_DRIVER_PATH); if (driverPath == null) { // Medium tests return; } File driver = new File(driverPath); File deployedDriver = new File(fileSystem.getDeployDir(), driver.getName()); if (!deployedDriver.exists() || FileUtils.sizeOf(deployedDriver) != FileUtils.sizeOf(driver)) { try { FileUtils.copyFile(driver, deployedDriver); } catch (IOException e) { throw new IllegalStateException( String.format("Can not copy the JDBC driver from %s to %s", driver, deployedDriver), e); } } File deployedDriverIndex = fileSystem.getDeployedJdbcDriverIndex(); try { FileUtils.writeStringToFile(deployedDriverIndex, driverIndexContent(deployedDriver)); } catch (IOException e) { throw new IllegalStateException("Can not generate index of JDBC driver", e); } }
// 上传文件 public String upLoadOne() throws Exception { JSONObject jsonObject = new JSONObject(); String id = ((String[]) formMap.get("id"))[0] + ""; // 获取id String uploadName = ((String[]) formMap.get("uploadName"))[0] + ""; // 获取id ReptTechDtl rt = techReptDtlService.get(Long.parseLong(id)); // dtl try { String targetDirectory = getTechPath() + rt.getTechReptDef().getId() + rt.getTechReptDef().getName(); String temArr[] = uploadName.split("\\."); String fileName = UUID.randomUUID().toString(); // 读取 if (temArr.length != 0) { fileName = fileName + "." + temArr[temArr.length - 1]; } File target = new File(targetDirectory, fileName); FileUtils.copyFile(formFile, target); // 更新技办人 和上传名称和实际存放的名称 rt.setTekofficer(getCurUser().getName()); // rt.setUploadName(uploadName); rt.setSaveName(fileName); rt.setUpdDate(DateUtil.dateToDateByFormat(utilService.getSysTime(), DateUtil.FORMAT)); techReptDtlService.save(rt); } catch (Exception e) { e.printStackTrace(); jsonObject.put("result", false); json = jsonObject.toString(); return EASYFILE; } jsonObject.put("result", true); json = jsonObject.toString(); return EASYFILE; }
private static void copyFile(String testClassName, String testMethodName, String fileName) throws Exception { File srcFile = new File(Env.DIR_TEST_DATA_SOURCE.value() + "/" + fileName); File destFile = new File(getDestDirName(testClassName, testMethodName) + "/" + fileName); FileUtils.copyFile(srcFile, destFile); }
// adds file to S3 Data store or offline cache (if working offline) public String addPointSet(File pointSetFile, String pointSetId) throws IOException { if (pointSetId == null) throw new NullPointerException("null point set id"); File renamedPointSetFile = new File(POINT_DIR, pointSetId + ".json"); if (renamedPointSetFile.exists()) return pointSetId; FileUtils.copyFile(pointSetFile, renamedPointSetFile); if (!this.workOffline) { // only upload if it doesn't exist try { s3.getObjectMetadata(pointsetBucket, pointSetId + ".json.gz"); } catch (AmazonServiceException e) { // gzip compression in storage, not because we're worried about file size but to speed file // transfer FileInputStream fis = new FileInputStream(pointSetFile); File tempFile = File.createTempFile(pointSetId, ".json.gz"); FileOutputStream fos = new FileOutputStream(tempFile); GZIPOutputStream gos = new GZIPOutputStream(fos); try { ByteStreams.copy(fis, gos); } finally { gos.close(); fis.close(); } s3.putObject(pointsetBucket, pointSetId + ".json.gz", tempFile); tempFile.delete(); } } return pointSetId; }
/** * Deploys Jenkins plugins to given {@code dest} * * @param src * @param dest * @throws IOException - if the error occurred while copying plugins to {@code dest} folder. * IllegalArgumentException - invalid plugin source location is given. */ protected void copyBundledPlugin(String src, String dest) throws IOException { String pluginPath = src + File.separator + JenkinsTenantConstants.COMMON_PLUGINS_DIR; File source = new File(pluginPath); if (!source.exists()) { throw new IllegalArgumentException("Common plugin location cannot be found at " + pluginPath); } File destination = new File(dest, "plugins"); // Copy if doesnot exists String files[] = source.list(); for (String file : files) { File srcFile = new File(src, file); File destFile; try { destFile = new File(destination, file); if (!destFile.exists()) { destFile.createNewFile(); FileUtils.copyFile(srcFile, destFile); } } catch (FileNotFoundException e) { } } }
/** {@inheritDoc} */ @Override public boolean save() { try { final String dbLocTemp = mConn.getMetaData().getURL().substring(DB_PREFIX.length()); final String dbLoc = dbLocTemp.substring(0, dbLocTemp.lastIndexOf("-")); // Closing the connection will make sure all updates are in the file mConn.close(); // Move the file to the original DB FileUtils.copyFile(new File(dbLocTemp + DB_SUFFIX), new File(dbLoc + DB_SUFFIX)); l.info("Saved temp DB [" + dbLocTemp + "] to [" + dbLoc + "]"); // Now that the DB is saved, connect again mConn = connect(dbLocTemp); return true; } catch (final SQLException ex) { l.error("Can't save database", ex); return false; } catch (final IOException ex) { l.error("Can't save database", ex); return false; } }
private void copyNativeLibraryArtifactFileToDirectory( Artifact artifact, File destinationDirectory, String ndkArchitecture) throws MojoExecutionException { final File artifactFile = getArtifactResolverHelper().resolveArtifactToFile(artifact); try { final String artifactId = artifact.getArtifactId(); String filename = artifactId.startsWith("lib") ? artifactId + ".so" : "lib" + artifactId + ".so"; if (ndkFinalLibraryName != null && artifact.getFile().getName().startsWith("lib" + ndkFinalLibraryName)) { // The artifact looks like one we built with the NDK in this module // preserve the name from the NDK build filename = artifact.getFile().getName(); } final File finalDestinationDirectory = getFinalDestinationDirectoryFor(artifact, destinationDirectory, ndkArchitecture); final File file = new File(finalDestinationDirectory, filename); getLog() .debug( "Copying native dependency " + artifactId + " (" + artifact.getGroupId() + ") to " + file); FileUtils.copyFile(artifactFile, file); } catch (Exception e) { throw new MojoExecutionException("Could not copy native dependency.", e); } }
/** * Delete files previously deployed by templates. If a file had been overwritten by a template, it * will be restored. Helps the server returning to the state before any template was applied. * * @throws IOException * @throws ConfigurationException */ private void deleteTemplateFiles() throws IOException, ConfigurationException { File newFiles = new File(generator.getNuxeoHome(), NEW_FILES); if (!newFiles.exists()) { return; } BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(newFiles)); String line; while ((line = reader.readLine()) != null) { if (line.endsWith(".bak")) { log.debug("Restore " + line); try { File backup = new File(generator.getNuxeoHome(), line); File original = new File(generator.getNuxeoHome(), line.substring(0, line.length() - 4)); FileUtils.copyFile(backup, original); backup.delete(); } catch (IOException e) { throw new ConfigurationException( String.format( "Failed to restore %s from %s\nEdit or " + "delete %s to bypass that error.", line.substring(0, line.length() - 4), line, newFiles), e); } } else { log.debug("Remove " + line); new File(generator.getNuxeoHome(), line).delete(); } } } finally { IOUtils.closeQuietly(reader); } newFiles.delete(); }
/** * Do actual dependency copying and update project's copy dependency path. * * @throws IOException */ private boolean copyDependencies() throws IOException { boolean result = true; projectCopy.setResourceRoot("${projectDir}"); List<ExternalDependency> dependencies = projectCopy.getExternalDependencies(); for (ExternalDependency dependency : dependencies) { switch (dependency.getType()) { case FILE: File originalDependency = new File(dependency.getPath()); if (originalDependency.exists()) { File targetDependency = new File(tmpDir, originalDependency.getName()); FileUtils.copyFile(originalDependency, targetDependency); dependency.updatePath(targetDependency.getPath()); } else { SoapUI.log.warn( "Do not exists on local file system [" + originalDependency.getPath() + "]"); } break; case FOLDER: originalDependency = new File(dependency.getPath()); File targetDependency = new File(tmpDir, originalDependency.getName()); targetDependency.mkdir(); FileUtils.copyDirectory(originalDependency, targetDependency, false); dependency.updatePath(targetDependency.getPath()); break; default: break; } } return result; }
public File takeScreenshot(WebElement element) { if (!WebDriverRunner.hasWebDriverStarted()) { log.warning("Cannot take screenshot because browser is not started"); return null; } WebDriver webdriver = getWebDriver(); if (!(webdriver instanceof TakesScreenshot)) { log.warning("Cannot take screenshot because browser does not support screenshots"); return null; } File screen = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.FILE); Point p = element.getLocation(); Dimension elementSize = element.getSize(); try { BufferedImage img = ImageIO.read(screen); BufferedImage dest = img.getSubimage(p.getX(), p.getY(), elementSize.getWidth(), elementSize.getHeight()); ImageIO.write(dest, "png", screen); File screenshotOfElement = new File(generateScreenshotFileName()); FileUtils.copyFile(screen, screenshotOfElement); return screenshotOfElement; } catch (IOException e) { printOnce("takeScreenshotImage", e); return null; } }
@Test public void getPersonalise() throws Exception { driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get(url); for (int i = 1; i <= count; i++) { midRow = merchantFile.getRow(i); username = midRow.getCell(0).toString(); password = "******"; expUsername = "******" + username; Thread.sleep(500); LoginPage lp = new LoginPage(driver, clientProps); lp.LoginUser(username, password); log.info(username + " logged in sucessufully"); PersonalisePage pp = new PersonalisePage(driver, clientProps); pp.personaliseMerchant(expUsername); log.info(expUsername + " personalised sucessfully"); // take the screenshot at the end of every test File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); // now save the screenshto to a file some place FileUtils.copyFile(scrFile, new java.io.File("ComplianceProject/Screenshots")); // Assertions pers = new Assertions(driver, clientProps); // pers.assertTitle("Personalise"); Thread.sleep(3000); LogoutPage lop = new LogoutPage(driver, clientProps); lop.userLogout(); // driver.switchTo().alert().accept(); } }
public void buildScenes(String targetPath) { ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME); String srcPath = projectManager.getCurrentWorkingPath() + "/" + projectManager.currentProjectVO.projectName + "/scenes"; FileHandle scenesDirectoryHandle = Gdx.files.absolute(srcPath); File fileTarget = new File(targetPath + "/" + scenesDirectoryHandle.name()); try { FileUtils.copyDirectory(scenesDirectoryHandle.file(), fileTarget); } catch (IOException e) { e.printStackTrace(); } // copy project dt try { FileUtils.copyFile( new File( projectManager.getCurrentWorkingPath() + "/" + projectManager.currentProjectVO.projectName + "/project.dt"), new File(targetPath + "/project.dt")); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String args[]) throws Exception { if (args.length < 2) { System.out.println("Invalid usage!"); return; } final File currentPath = PlatformUtils.getApplicationPath("mualauncher"); Logger.initialize(new File(currentPath, "updater.log")); File tempFile = new File(args[0]); File launcherFile = new File(args[1]); try { Logger.info("Removing old version"); if (!launcherFile.delete()) { throw new IOException("Unable to remove old file " + launcherFile); } Logger.info("Copying new launcher from %s", tempFile.getAbsolutePath()); FileUtils.copyFile(tempFile, launcherFile); } catch (IOException e) { Logger.info("Autoupdate failed: %s ", e.getMessage()); } // Start launcher Logger.info("Starting launcher %s", launcherFile.getAbsolutePath()); PlatformUtils.launchJavaApplication( launcherFile.getAbsolutePath(), Launcher.class.getCanonicalName(), "updated"); Logger.info("Update done!"); System.exit(0); }
/** * @param path test name and picture name "userJourney/login" * @return */ public static String captureScreen(String path, WebDriver driver1) { File scrFile = null; if (runRemote) { WebDriver augmentedDriver = new Augmenter().augment(driver1); scrFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE); } else try { scrFile = ((TakesScreenshot) driver1).getScreenshotAs(OutputType.FILE); } catch (Exception e) { System.out.println("Error when trying to get local screenshot: " + e); } try { // System.out.println("Calea: " + "./test-output/screenshots/" + // DriverInitialization.getTimeStamp() + "/" + path + ".png"); FileUtils.copyFile( scrFile, new File( "./test-output/screenshots/" + DriverInitialization.getTimeStamp() + "/" + path + ".png")); } catch (IOException e) { System.err.println("Error when try to take a screenshot: " + e); } return "Created screenshot at:" + path + "png"; }
public String uploadImage() { System.out.println("1111" + albumId); HttpSession session = ServletActionContext.getRequest().getSession(false); User user = (User) session.getAttribute("user"); System.out.println("UserPostAction Photo===>" + picFileName); System.out.println("UserPostAction Photo===>" + picContentType); System.out.println("UserPostAction Photo===>" + pic); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateobj = new Date(); UserImageUploadDAO up = new UserImageUploadDAOImpl(); String destpath = ""; String imageExtension = ""; if (picContentType != null && picContentType.contains("jpeg")) { imageExtension = ".jpeg"; } else if (picContentType != null && picContentType.contains("png")) { imageExtension = ".png"; } else if (picContentType != null && picContentType.contains("gif")) { imageExtension = ".gif"; } else if (picContentType != null && picContentType.contains("jpg")) { imageExtension = ".jpg"; } if (picFileName != null) { Random randomGenerator = new Random(); Integer randomInt = randomGenerator.nextInt(1000000); picFileName = randomInt.toString() + imageExtension; System.out.println("UserPostAction Photo===>" + picFileName); String name = up.getAlbumName(getAlbumId()); destpath = StringUtils.photoPath + File.separator + user.getUserId() + "_" + name; System.out.println("Server path:" + destpath); File destFile = new File(destpath, picFileName); try { FileUtils.copyFile(pic, destFile); } catch (IOException e) { System.out.println("error occurred"); e.printStackTrace(); return ERROR; } } // if(friendId==null || friendId=="") // { user_id = user.getUserId(); setUser_id(user_id); up.uploadImage(df.format(dateobj).toString(), albumId, picFileName); Integer aid = albumId; HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("albumId", aid.toString()); request.setAttribute("imageList", imageList); // } // else{ /*NewsFeedDAOImpl nfd=new NewsFeedDAOImpl(); String userName=nfd.getFullUserName(friendId); up.postOnWall(postDesc, user.getUserId(),friendId, df.format(dateobj).toString(),userName+" status Update","timeline",youtubeLink,picFileName);*/ // } addActionMessage("Content has been posted successfully."); return "success"; }
public void renameRole(String roleName, String newRoleName, User currentUser) throws IOException { Assert.hasLength(roleName); Assert.hasLength(newRoleName); Assert.notNull(currentUser); // check that role exists by trying to load it getRole(roleName); // check that new role does not exist by trying to load it try { getRole(newRoleName); throw new IllegalArgumentException("role already exists: " + newRoleName); // $NON-NLS-1$ } catch (RoleNotFoundException e) { // okay } log.info("renaming role: {} -> {}", roleName, newRoleName); // $NON-NLS-1$ ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File file = new File(workingDir, roleName + ROLE_SUFFIX); File newFile = new File(workingDir, newRoleName + ROLE_SUFFIX); FileUtils.copyFile(file, newFile); Git git = Git.wrap(repo.r()); git.rm().addFilepattern(roleName + ROLE_SUFFIX).call(); git.add().addFilepattern(newRoleName + ROLE_SUFFIX).call(); List<String> users = listUsers(repo); users.add(ANONYMOUS_USER_LOGIN_NAME); for (String user : users) { List<RoleGrantedAuthority> authorities = getUserAuthorities(user, repo); Set<RoleGrantedAuthority> newAuthorities = Sets.newHashSet(); for (Iterator<RoleGrantedAuthority> iter = authorities.iterator(); iter.hasNext(); ) { RoleGrantedAuthority rga = iter.next(); if (rga.getRoleName().equals(roleName)) { RoleGrantedAuthority newRga = new RoleGrantedAuthority(rga.getTarget(), newRoleName); newAuthorities.add(newRga); iter.remove(); } } if (!newAuthorities.isEmpty()) { authorities.addAll(newAuthorities); saveUserAuthorities(user, Sets.newHashSet(authorities), repo, currentUser, false); } } PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail()); git.commit() .setAuthor(ident) .setCommitter(ident) .setMessage("rename role " + roleName + " to " + newRoleName) // $NON-NLS-1$ //$NON-NLS-2$ .call(); } catch (GitAPIException e) { throw new IOException(e); } finally { Util.closeQuietly(repo); } }
/** * Test that exporting twice overrides the previous files * * @throws Exception */ @Test public void testExportOverridesPreviousExport() throws Exception { closeFileHandlesInEtc(); resetInitialState(); String firstExportMessage = console.runCommand(EXPORT_COMMAND); File firstExport = getExportSubDirectory(getDefaultExportDirectory(), "system.properties").toFile(); long firstLength = firstExport.length(); FileUtils.copyFile(SYSTEM_PROPERTIES.toFile(), SYSTEM_PROPERTIES_COPY.toFile()); FileUtils.writeStringToFile(SYSTEM_PROPERTIES.toFile(), "testtesttest", true); String secondExportMessage = console.runCommand(EXPORT_COMMAND); File secondExport = getExportSubDirectory(getDefaultExportDirectory(), "system.properties").toFile(); long secondLength = secondExport.length(); assertThat( "The first export failed to export", firstExportMessage, not(containsString("Failed to export all configurations"))); assertThat( "The second export failed to export", secondExportMessage, not(containsString("Failed to export all configurations"))); assertThat( "The second failed to modify the first export's files.", firstLength, is(not(equalTo(secondLength)))); }
/** * Sends invitation mail to all participants. * * @return the SUCCESS result */ public String send() throws Exception { UserUtil.permissionCheck("update_call"); String content = ""; if (to != null && to.trim().length() > 0) { String[] tos = to.split(","); if (this.isText_only()) { content = this.getText_body(); } else { content = this.getHtml_body(); } // Gets attachments String realPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/upload"); String targetDirectory = realPath; String[] tNames = new String[uploads.length]; File[] tFiles = new File[uploads.length]; for (int i = 0; i < uploads.length; i++) { tNames[i] = generateFileName(uploadFileNames[i]); File target = new File(targetDirectory, tNames[i]); FileUtils.copyFile(uploads[i], target); tFiles[i] = target; } mailService.asynSendHtmlMail(from, tos, subject, content, this.getUploadFileName(), tFiles); } return SUCCESS; }
private void copyDefaultFiles(String taskId, String directoryPath, String targetPath) throws Exception { File taskMetaInfo = new File(String.format("%s/%s/metaInfo.xml", directoryPath, taskId)); File targetMetaInfo = new File(String.format("%s/metaInfo.xml", targetPath)); targetMetaInfo.createNewFile(); FileUtils.copyFile(taskMetaInfo, targetMetaInfo); File taskLogicalSubprogramDiagrams = new File( String.format( "%s/%s/%s/SubprogramDiagram", directoryPath, taskId, PathConstants.PATH_TO_LOGICAL_PART)); File taskGraphicalSubprogramDiagrams = new File( String.format( "%s/%s/%s/SubprogramDiagram", directoryPath, taskId, PathConstants.PATH_TO_GRAPHICAL_PART)); if (taskLogicalSubprogramDiagrams.exists() && taskGraphicalSubprogramDiagrams.exists()) { File targetLogicalSubprogramDiagrams = new File( String.format( "%s/%s/SubprogramDiagram", targetPath, PathConstants.PATH_TO_LOGICAL_PART)); FileUtils.copyDirectory(taskLogicalSubprogramDiagrams, targetLogicalSubprogramDiagrams); File targetGraphicalSubprogramDiagrams = new File( String.format( "%s/%s/SubprogramDiagram", targetPath, PathConstants.PATH_TO_GRAPHICAL_PART)); FileUtils.copyDirectory(taskGraphicalSubprogramDiagrams, targetGraphicalSubprogramDiagrams); copySubprogramNodes(taskId, directoryPath, targetPath); } }
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) { try { FileUtils.copyFile(srcFile, destFile, preserveFileDate); } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public List<Object> uploadImg(File img, String imgFileName, String imgContentType, int types) { if (img == null) { return null; } List<Object> reList = new ArrayList<Object>(); try { ImagesProp p = new ImagesProp(); String saveName = System.currentTimeMillis() + imgFileName.substring(imgFileName.lastIndexOf(".")); String url = setUrl(types, saveName); String local = setLocal(types, saveName); FileUtils.copyFile(img, new File(local)); p.setAlt_prop(""); p.setLocalurl(local); p.setUrl(url); p.setTitle(""); p.setBelongs_table(relateTable(types)); p.setId(saveNewData(p)); Map<Object, Object> map = new HashMap<Object, Object>(); map.put("id", p.getId()); map.put("alt", p.getAlt_prop()); map.put("url", p.getUrl()); map.put("title", p.getTitle()); reList.add(map); } catch (Exception e) { log.error("AJAX上传图片异常:", e); reList.add(1); } return reList; }
@Test public void testDeleteInstanceDirAfterCreateFailure() throws Exception { assumeFalse( "Ignore test on windows because it does not delete data directory immediately after unload", Constants.WINDOWS); File solrHomeDirectory = new File(initCoreDataDir, getClass().getName() + "-corex-" + System.nanoTime()); solrHomeDirectory.mkdirs(); copySolrHomeToTemp(solrHomeDirectory, "corex"); File corex = new File(solrHomeDirectory, "corex"); FileUtils.write(new File(corex, "core.properties"), "", StandardCharsets.UTF_8); JettySolrRunner runner = new JettySolrRunner(solrHomeDirectory.getAbsolutePath(), buildJettyConfig("/solr")); runner.start(); try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl() + "/corex")) { client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT); client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", "123"); client.add(doc); client.commit(); } Path dataDir = null; try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) { CoreStatus status = CoreAdminRequest.getCoreStatus("corex", true, client); String dataDirectory = status.getDataDirectory(); dataDir = Paths.get(dataDirectory); assertTrue(Files.exists(dataDir)); } File subHome = new File(solrHomeDirectory, "corex" + File.separator + "conf"); String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf"; FileUtils.copyFile( new File(top, "bad-error-solrconfig.xml"), new File(subHome, "solrconfig.xml")); try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) { client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT); client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT); try { CoreAdminRequest.reloadCore("corex", client); } catch (Exception e) { // this is expected because we put a bad solrconfig -- ignore } CoreAdminRequest.Unload req = new CoreAdminRequest.Unload(false); req.setDeleteDataDir(true); req.setDeleteInstanceDir( false); // important because the data directory is inside the instance directory req.setCoreName("corex"); req.process(client); } runner.stop(); assertTrue( "The data directory was not cleaned up on unload after a failed core reload", Files.notExists(dataDir)); }
public String execute() throws Exception { String userId = (String) ActionContext.getContext().getSession().get("userId"); String targetDirectory = servletContext.getRealPath("Excel"); // 获得路径 if (upload != null) { try { String targetFileName = GenerateUtils.generateFileName(uploadFileName); File target = new File(targetDirectory, targetFileName); FileUtils.copyFile(upload, target); String userInfoExcelPath = targetDirectory + "\\" + targetFileName; File excelfile = new File(userInfoExcelPath); String info = excelToDBService.readInfoExceltoDB(excelfile, userId, targetDirectory); if ("ALLSUC".equals(info)) { warning = "数据全部导入成功!"; } else if ("ERR".equals(info)) { warning = "数据导入中出现问题,请看是否上传的是正确的excel,否则请联系管理员!"; } else { warning = "部分未导入的数据生成的excel,请及时下载!"; url = info; } if (target.exists()) { target.delete(); } return SUCCESS; } catch (Exception e) { e.printStackTrace(); return ERROR; } } warning = "请上传材料"; return ERROR; }
@Test public void testRemoteWebDriver() { DesiredCapabilities cap = new DesiredCapabilities(); cap.setPlatform(Platform.ANY); cap.setBrowserName("opera"); RemoteWebDriver driver = null; try { driver = new RemoteWebDriver(new URL("http://192.168.1.176:4444/wd/hub"), cap); } catch (MalformedURLException e) { e.printStackTrace(); } // Navigate to Google using firefox driver.get("http://www.google.com"); driver .findElement(By.name("q")) .sendKeys("selenium automation using grid on windows 8.1 with firefox machine"); driver = (RemoteWebDriver) new Augmenter().augment(driver); File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(srcFile, new File("remoteScreenshot.jpg")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(driver.getCurrentUrl()); driver.quit(); }
/** * The method creates an screenshot usually saved in output/screenshots It also adds the * screenshot to the index.html file generated by surefire-reports for ease of debugging The * method checks to see if the safari driver is used and if it is it will maximize the window so * that it catches most of the page. * * @param LOG_FILE //@param the parameter is used to form the file usually is * test_errorLocation_failed.png * @param driver */ public static void screenShooter(String LOG_FILE, WebDriver driver) { File dest = new File("test-output\\Screen.png"); try { // ((TakesScreenshot)driver).getScreenshotAs(target) System.setProperty("org.uncommons.reportng.escape-output", "false"); File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, dest); String absolute = dest.getAbsolutePath(); int beginIndex = absolute.indexOf("."); String relative = absolute.substring(beginIndex).replace(".\\", ""); String screenShot = relative.replace('\\', '/'); Reporter.log( "<a href=\"" + screenShot + "\"><p align=\"left\">Screenshot at " + new Date() + "</p>"); Reporter.log( "<p style='border:1px solid red;'><img width=\"800\" src=\"" + dest.getAbsoluteFile() + "\" alt=\"screenshot at " + new Date() + "\"/></p></a><br />"); } catch (IOException e) { // Logger.Log(LOG_FILE, "Couldn't take the screenshot ",driver); } }