Java Examples for java.io.File
The following java examples will help you to understand the usage of java.io.File. These source code samples are taken from different open source projects.
Example 1
| Project: OpenJML-master File: DemoProgress.java View source code |
public static void main(String[] argv) {
try {
java.io.File f2 = new java.io.File("src/demo/B.java");
IAPI m = Factory.makeAPI("-noPurityCheck", "-sourcepath", "src");
m.setProgressListener(new ProgressListener());
System.out.println("PARSING");
List<JmlTree.JmlCompilationUnit> asts = m.parseFiles(f2);
System.out.println("TYPE-CHECKING");
int ret = m.typecheck(asts);
System.out.println("Errors: " + ret);
} catch (Exception e) {
System.out.println(e);
}
}Example 2
| Project: hudson_plugins-master File: StarTeamFunctions.java View source code |
/**
* Find the given folder in the given view.
*
* @param view
* The view to look in.
* @param foldername
* The view-relative path of the folder to look for.
* @return The folder or null if a folder by the given name was not found.
* @throws StarTeamSCMException
*/
public static Folder findFolderInView(final View view, final String foldername) throws StarTeamSCMException {
// Check the root folder of the view
if (view.getName().equalsIgnoreCase(foldername)) {
return view.getRootFolder();
}
// Create a File object with the folder name for system-
// independent matching
java.io.File thefolder = new java.io.File(foldername.toLowerCase());
// Search for the folder in subfolders
Folder result = findFolderInView(view.getRootFolder(), thefolder);
if (result == null) {
throw new StarTeamSCMException("Couldn't find folder " + foldername + " in view " + view.getName());
}
return result;
}Example 3
| Project: starteam-plugin-master File: StarTeamFunctions.java View source code |
/**
* Find the given folder in the given view.
*
* @param view
* The view to look in.
* @param foldername
* The view-relative path of the folder to look for.
* @return The folder or null if a folder by the given name was not found.
* @throws StarTeamSCMException
*/
public static Folder findFolderInView(final View view, final String foldername) throws StarTeamSCMException {
// Check the root folder of the view
if (view.getName().equalsIgnoreCase(foldername)) {
return view.getRootFolder();
}
// Create a File object with the folder name for system-
// independent matching
java.io.File thefolder = new java.io.File(foldername.toLowerCase());
// Search for the folder in subfolders
Folder result = findFolderInView(view.getRootFolder(), thefolder);
if (result == null) {
throw new StarTeamSCMException("Couldn't find folder " + foldername + " in view " + view.getName());
}
return result;
}Example 4
| Project: GOOL-master File: RecognizerMatcherTest.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
RecognizerMatcher.init("java");
RecognizerMatcher.matchImport("java.io.File");
RecognizerMatcher.printMatchTables();
System.out.println(RecognizerMatcher.matchClass("java.io.File"));
System.out.println(RecognizerMatcher.matchClass("java.io.FileReader"));
System.out.println(RecognizerMatcher.matchClass("java.io.FileWriter"));
System.out.println(RecognizerMatcher.matchClass("java.io.BufferedReader"));
System.out.println(RecognizerMatcher.matchClass("java.io.BufferedWriter"));
System.out.println(RecognizerMatcher.matchMethod("java.io.File.createNewFile():boolean"));
}Example 5
| Project: netifera-master File: LocalFileSystem.java View source code |
private File convert(java.io.File javaFile) { int attributes = 0; if (javaFile.isDirectory()) attributes |= File.DIRECTORY; if (javaFile.isFile()) attributes |= File.FILE; if (javaFile.isHidden()) attributes |= File.HIDDEN; return new File(this, javaFile.getAbsolutePath(), attributes, javaFile.length(), javaFile.lastModified()); }
Example 6
| Project: webtools.javaee-master File: DirectoryLoadStrategyImpl.java View source code |
protected void addFile(java.io.File aFile, List aList) { String uri = getURIFrom(aFile); if (collectedLooseArchiveFiles.containsKey(uri)) return; org.eclipse.jst.j2ee.commonarchivecore.internal.File cFile = createFile(uri); cFile.setSize(aFile.length()); cFile.setLastModified(aFile.lastModified()); aList.add(cFile); }
Example 7
| Project: Aspose_Email_Java-master File: BayesianSpamAnalyzer.java View source code |
public static void SpamFilterTest(String dataDir) {
String hamFolder = dataDir + "ham";
String spamFolder = dataDir + "spam";
String testFolder = dataDir + "test";
String dataBaseFile = dataDir + "SpamFilterDatabase.txt";
teachAndCreateDatabase(hamFolder, spamFolder, dataBaseFile);
java.io.File folder = new java.io.File(testFolder);
java.io.File[] testFiles = folder.listFiles();
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile);
for (int i = 0; i < testFiles.length; i++) {
MailMessage msg = MailMessage.load(testFiles[i].getAbsolutePath());
System.out.println(msg.getSubject());
double probability = analyzer.test(msg);
printResult(probability);
}
}Example 8
| Project: sevntu.checkstyle-master File: InputForbidInstantiationCheckWithoutDots.java View source code |
public void method() {
// !
NullPointerException ex = new NullPointerException("message");
int[] x = new int[10];
new InputForbidInstantiationCheck();
// !
NullPointerException ex2 = new java.lang.NullPointerException("message");
// !
com.github.sevntu.checkstyle.checks.coding.InputForbidInstantiationCheck File = new com.github.sevntu.checkstyle.checks.coding.InputForbidInstantiationCheck();
// 2 !
File File1 = new java.io.File("");
// 2 !
String a = new String();
InputForbidInstantiationCheck c = new InputForbidInstantiationCheck();
}Example 9
| Project: maven-confluence-plugin-master File: FileIOTest.java View source code |
@Test
public void forceMkdir() throws Exception {
FileUtils.deleteDirectory(new java.io.File("target/test"));
java.io.File outputFile = new java.io.File("target/test/io", "test.txt");
java.io.File folder = new java.io.File(outputFile.getParent());
Assert.assertThat(folder.exists(), Is.is(false));
FileUtils.forceMkdir(folder);
Assert.assertThat(folder.exists(), Is.is(true));
Assert.assertThat(folder.isDirectory(), Is.is(true));
FileUtils.writeStringToFile(outputFile, "this is test");
Assert.assertThat(outputFile.exists(), Is.is(true));
Assert.assertThat(outputFile.isFile(), Is.is(true));
}Example 10
| Project: openbd-core-master File: fileList.java View source code |
//------------------------------------------------------------ public List<File> list() { List<File> fileList = new ArrayList<File>(); List<cDirInfo> toBeDone = new ArrayList<cDirInfo>(); String dir[] = rootDir.list(new fileFilter(wildCard)); cDirInfo tX; if (dir != null) { tX = new cDirInfo(rootDir, dir); toBeDone.add(tX); } while (!toBeDone.isEmpty()) { tX = toBeDone.get(0); try { int x = 0; for (; ; ) { java.io.File newFile = new java.io.File(tX.rootDir, tX.dirList[x]); if (newFile.isDirectory()) { java.io.File t = new java.io.File(tX.rootDir, tX.dirList[x]); String a[] = newFile.list(new fileFilter(wildCard)); if (a != null) toBeDone.add(new cDirInfo(t, a)); } else { fileList.add(newFile); } x++; } } catch (ArrayIndexOutOfBoundsException E) { } toBeDone.remove(0); dir = null; } return fileList; }
Example 11
| Project: rtgov-master File: TestUtils.java View source code |
public static java.io.File copyToTmpFile(java.io.File source, String filename) { String tmpdir = System.getProperty("java.io.tmpdir"); java.io.File dir = new java.io.File(tmpdir + java.io.File.separator + "rtgovtests" + System.currentTimeMillis()); dir.mkdir(); dir.deleteOnExit(); java.io.File ret = new java.io.File(dir, filename); ret.deleteOnExit(); // Copy contents to the tmp file try { java.io.FileInputStream fis = new java.io.FileInputStream(source); java.io.FileOutputStream fos = new java.io.FileOutputStream(ret); byte[] b = new byte[10240]; int len = 0; while ((len = fis.read(b)) > 0) { fos.write(b, 0, len); } fis.close(); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); fail("Failed to copy file '" + filename + "': " + e); } return (ret); }
Example 12
| Project: cloudstore-master File: OioFileFactory.java View source code |
/** Factory method, substitutes the constructor of {@link java.io.File}. */
public static File createFile(final String parent, final String... children) {
assertNotNull(parent, "parent");
final FileFactory fileFactory = OioRegistry.getInstance().getFileFactory();
File result = null;
if (children != null) {
for (final String child : children) {
if (result == null)
result = fileFactory.createFile(parent, child);
else
result = fileFactory.createFile(result, child);
}
}
if (result == null)
result = createFile(parent);
return result;
}Example 13
| Project: savara-core-master File: DefaultResourceLocatorTest.java View source code |
@Test
public void testGetRelativePath() {
try {
java.net.URL url1 = ClassLoader.getSystemResource("project/requirements/SuccessfulPolicyQuote.scn");
java.io.File base = new java.io.File(url1.getFile());
DefaultResourceLocator locator = new DefaultResourceLocator(base.getParentFile());
java.net.URL url2 = ClassLoader.getSystemResource("project/requirements/sample-data/CreditCheckRequest.xml");
java.io.File dataFile = new java.io.File(url2.getFile());
java.io.File targetFile = new java.io.File(dataFile.getParentFile(), "../../schema/creditCheck.xsd");
String path = locator.getRelativePath(targetFile.getCanonicalPath());
if (!path.equals("../schema/creditCheck.xsd")) {
fail("Expecting path '../schema/creditCheck.xsd', but got: " + path);
}
} catch (Exception e) {
fail("Failed: " + e);
}
}Example 14
| Project: common_utils-master File: ConsoleHelperTest.java View source code |
// @org.junit.Test
public void test() {
String filePath = getClass().getClassLoader().getResource("").getFile();
File file = new File(filePath, "console.out");
ConsoleHelper consoleHelper = new ConsoleHelper(file, ConsoleHelper.FileStrategy.DAILY);
for (int i = 0; i < 1000; i++) {
System.out.println("test" + i);
}
File[] files = consoleHelper.listFiles();
for (File file1 : files) {
System.out.println(file1);
}
}Example 15
| Project: gravel-master File: JavaTestcaseClassWriter.java View source code |
public JavaTestcaseClassWriter write_(final ClassNode _aClassNode) {
final MethodNode[] _testMethods;
final StringBuilder[] _wstr;
final String _className;
final java.io.File _dir;
_wstr = new StringBuilder[1];
_testMethods = st.gravel.support.jvm.ArrayExtensions.select_(_aClassNode.methods(), new st.gravel.support.jvm.Predicate1<MethodNode>() {
@Override
public boolean value_(final MethodNode _m) {
return _m.selector().startsWith("test");
}
});
if (_testMethods.length == 0) {
return JavaTestcaseClassWriter.this;
}
_className = _aClassNode.name().asString();
_dir = new java.io.File(new java.io.File(new java.io.File(_root, "st"), "gravel"), "systemtests");
_dir.mkdirs();
_wstr[0] = st.gravel.support.jvm.WriteStreamFactory.on_(new String());
_wstr[0].append("package st.gravel.systemtests;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport st.gravel.support.jvm.runtime.ImageBootstrapper;\nimport st.gravel.support.jvm.runtime.MethodTools;\n\npublic class ");
_wstr[0].append(_className);
_wstr[0].append(" {\n\t@Before\n\tpublic void setUp() {\n\t\tst.gravel.support.compiler.testtools.TestBootstrap.getSingleton();\n\t}\n");
for (final MethodNode _each : _testMethods) {
_wstr[0].append("\t@Test\n\tpublic void ");
_wstr[0].append(_each.selector());
_wstr[0].append("() throws Throwable {\n\t\tMethodTools.debugTest(\"");
_wstr[0].append(_aClassNode.reference().toString());
_wstr[0].append("\", \"");
_wstr[0].append(_each.selector());
_wstr[0].append("\");\n\t}\n");
}
_wstr[0].append("}");
st.gravel.support.jvm.StringExtensions.writeToFile_(_wstr[0].toString(), new java.io.File(_dir, _className + ".java"));
return this;
}Example 16
| Project: openge-master File: ClientFileManager.java View source code |
/**
*
* Loads a file from the disk using reflection with the given class.
* @param <T>
*
* @param filename the swg pathname of the file to load
* @param type the class of the interpreter to use.
*
* @return the interpreter created
*/
@SuppressWarnings("unchecked")
public static <T extends VisitorInterface> T loadFile(String filename, Class<T> type) throws InstantiationException, IllegalAccessException {
if (instance == null) {
instance = new ClientFileManager(new java.io.File(".", "clientdata"));
}
T interpreter = (T) instance.loadedFiles.get(filename);
if (interpreter == null) {
interpreter = type.newInstance();
File file = new File(instance.baseFolder.getAbsolutePath(), filename);
file.setReadable(true);
file.setExecutable(true);
file.setWritable(true);
IffFile.readFile(file.getAbsolutePath(), interpreter);
instance.loadedFiles.put(filename, interpreter);
}
return interpreter;
}Example 17
| Project: sonar-java-master File: InappropriateRegexpCheck.java View source code |
void foo() {
// Noncompliant [[sc=19;ec=22]] {{Correct this regular expression.}}
"".replaceAll(".", "");
// Noncompliant [[sc=19;ec=22]] {{Correct this regular expression.}}
"".replaceAll("|", "_");
// Noncompliant [[sc=19;ec=33]] {{Correct this regular expression.}}
"".replaceAll(File.separator, "");
"".replaceAll("\\.", "");
"".replaceAll("\\|", "");
}Example 18
| Project: riftsaw-master File: DeploymentManager.java View source code |
/**
* This method creates a list of deployment units representing the distinct
* deployments that are associated with the source BPEL processes provided
* in the deployment root. Distinct deployment units may be required if
* (for example) multiple versions of the same BPEL process are defined.
*
* @param deploymentName The overall deployment name
* @param deploymentRoot The root location containing the deployment descriptor
* and associated artifacts (bpel, wsdl, xsd, etc).
* @return The list of distinct BPEL deployment units
* @throws Exception Failed to retrieve deployment units
*/
public java.util.List<DeploymentUnit> getDeploymentUnits(String deploymentName, java.io.File deploymentRoot) throws Exception {
java.util.List<DeploymentUnit> ret = new java.util.Vector<DeploymentUnit>();
if (deploymentRoot == null || !deploymentRoot.exists()) {
throw new java.lang.IllegalArgumentException("Deployment root was not supplied, or does not exist");
}
// Check if deployment root is an archive
boolean exploded = false;
if (deploymentRoot.isFile()) {
deploymentRoot = explodeJar(deploymentName, deploymentRoot);
exploded = true;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Deploy is exploded? " + exploded);
}
// Scan deployment for BPEL processes
java.util.List<java.io.File> processes = getBPELProcesses(deploymentRoot);
if (processes.size() == 1 && exploded) {
java.io.File newDir = new java.io.File(deploymentRoot.getParentFile(), getDeploymentUnitName(deploymentName, processes.get(0)));
// If exists already, then delete
if (newDir.exists()) {
delete(newDir);
}
// Rename the deployment
if (deploymentRoot.renameTo(newDir)) {
ret.add(createDeploymentUnit(newDir));
} else {
// Log error and try to copy
LOG.error("Unable to rename deployment at '" + deploymentRoot + "' to '" + newDir + "'");
copy(deploymentRoot, newDir, processes.get(0).getName(), getProcessLocalName(processes.get(0)));
ret.add(createDeploymentUnit(newDir));
}
} else if (processes.size() > 0) {
for (java.io.File bpel : processes) {
java.io.File newDir = getTemporaryFolder(getDeploymentUnitName(deploymentName, bpel));
// If exists already, then delete
if (newDir.exists()) {
delete(newDir);
}
copy(deploymentRoot, newDir, bpel.getName(), getProcessLocalName(bpel));
ret.add(createDeploymentUnit(newDir));
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Get deployment units for name '" + deploymentName + "' and root '" + deploymentRoot + " = " + ret);
}
return (ret);
}Example 19
| Project: Aspose_Java_for_Docx4j-master File: Pptx4jOpenExistingPresentations.java View source code |
public static void main(String[] args) throws Exception {
String dataPath = "src/featurescomparison/workingwithpresentations/openexisting/data/";
String inputfilepath = dataPath + "presentation.pptx";
PresentationMLPackage presentationMLPackage = (PresentationMLPackage) OpcPackage.load(new java.io.File(inputfilepath));
System.out.println("\n\n saving .. \n\n");
presentationMLPackage.save(new java.io.File(dataPath + "Pptx4j-Duplicate.pptx"));
System.out.println("\n\n done .. \n\n");
}Example 20
| Project: Aspose_Slides_Java-master File: Pptx4jOpenExistingPresentations.java View source code |
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getDataDir(Pptx4jOpenExistingPresentations.class);
String inputfilepath = dataDir + "presentation.pptx";
PresentationMLPackage presentationMLPackage = (PresentationMLPackage) OpcPackage.load(new java.io.File(inputfilepath));
System.out.println("\n\n saving .. \n\n");
presentationMLPackage.save(new java.io.File(dataDir + "Pptx4j-Duplicate.pptx"));
System.out.println("\n\n done .. \n\n");
}Example 21
| Project: blobkeeper-master File: FileListServiceImpl.java View source code |
@Nullable @Override public File getFile(int disk, int partition) { Partition partitionInfo = partitionService.getById(disk, partition); if (partitionInfo == null) { log.error("Disk:Partition not found {}:{}", disk, partition); return null; } log.info("Getting partition {}", partitionInfo); java.io.File filePath = new java.io.File(configuration.getBasePath()); checkArgument(filePath.exists(), "Base path must be exists"); java.io.File file = getFilePathByPartition(configuration, partitionInfo); if (!file.exists()) { return null; } else { return new File(file); } }
Example 22
| Project: gluster-ovirt-poc-master File: XmlDocumentTest.java View source code |
@Test
public void Load() throws IOException {
final java.io.File temp = java.io.File.createTempFile("test-", ".xml");
try {
FileWriter writer = new FileWriter(temp);
writer.write("<?xml version=\"1.0\"?>\n <foo> <bar/> <!-- comment --> </foo>");
writer.close();
final XmlDocument document = new XmlDocument();
for (int i = 0; i < 2048; i++) {
document.Load(temp.getAbsolutePath());
}
} finally {
temp.delete();
}
}Example 23
| Project: vebugger-master File: FileTemplate.java View source code |
@Override
public void render(StringBuilder sb, Object obj) {
File file = (File) obj;
sb.append("<style>");
sb.append("table.java-io-File {border-collapse: collapse; font-size: 12px;}");
sb.append("table.java-io-File > * > tr > * {padding: 4px;}");
sb.append("table.java-io-File > thead > tr {border-bottom: 2px solid black;}");
sb.append("table.java-io-File > * > tr > *:first-child:not(:last-child) {border-right: 1px dotted silver;}");
sb.append("table.java-io-File > tbody > tr > * {border-bottom: 1px dotted silver;}");
sb.append("table.java-io-File > tbody > tr:last-child > * {border-bottom: none;}");
sb.append("</style>");
sb.append("<pre>").append(file.toString()).append("</pre>");
sb.append("<table class=\"java-io-File\"><thead><tr><th>Property</th><th>Value</th></tr></thead></tbody>");
sb.append("<tr><td><code>isAbsolute()</code></td><td><code>").append(file.isAbsolute()).append("</code></td></tr>");
if (file.exists()) {
sb.append("<tr><td><code>isFile()</code></td><td><code>").append(file.isFile()).append("</code></td></tr>");
sb.append("<tr><td><code>isDirectory()</code></td><td><code>").append(file.isDirectory()).append("</code></td></tr>");
sb.append("<tr><td><code>isHidden()</code></td><td><code>").append(file.isHidden()).append("</code></td></tr>");
sb.append("<tr><td>Permissions</td><td><pre>");
boolean noPermissions = true;
if (file.canRead()) {
sb.append("readable\n");
noPermissions = false;
}
if (file.canWrite()) {
sb.append("writable\n");
noPermissions = false;
}
if (file.canExecute()) {
sb.append("executable");
noPermissions = false;
}
if (noPermissions) {
sb.append("<none>");
}
sb.append("</pre></td></tr>");
} else {
sb.append("<tr><td colspan=\"2\">(file does not exist)</td></tr>");
}
sb.append("</tbody></table>");
}Example 24
| Project: Robin-master File: CaseInsensitiveFile.java View source code |
/* ****************************************************************************** * * handle directory path search beginning with root and returning first matching * ****************************************************************************** */ protected File getCaseInsensitiveFile(String strFile) { // early return possibility if strFile exists exactly as is File theFile = new File(strFile); if (theFile.exists()) return theFile; //remove any enclosing quotes try { if (strFile.charAt(0) == (char) 34) strFile = strFile.substring(1); if (strFile.charAt(strFile.length() - 1) == (char) 34) strFile = strFile.substring(0, strFile.length() - 1); } catch (Exception x) { } // we need to work with whatever file.separator the System is using noting that // windows uses \ as a separator requiring the String.split regexp to use \\ String file_separator = File.separator; if (file_separator.equals("\\")) file_separator += "\\"; // work with array of strings that make up the strFile path String subpaths[] = strFile.split(file_separator); // the case insensitive file object File caseInsensitiveFile = null; // traverse the subpaths building foundPath as we go using the strFile // substrings exactly if they make an existing path, or case permuted variants // of the substrings if found // this will store the path to the file we find including variants of case // note that only the first case permuted variant will be used if multiple exist String foundPath = ""; // absolute and relative files behave differently and considerations must be made // for how they are specified (begin with File.separator, filesystemroot, or .) int start_idx = 0; if (theFile.isAbsolute()) { // may begin with File.separator or drive specification (c:\ for example) if (theFile.getPath().startsWith(file_separator)) { // starting with file_separator means [i.e. /file (unix) or \file (windows)] start_idx = 1; } else { // subpaths[0] should be file root specification (c: on windows for example) foundPath = subpaths[0]; start_idx = 1; } } else { // if begins with ., treat like absolute path (no else needed) if (!subpaths[0].startsWith(".")) { File relFile = findFileMP(".", subpaths[0]); // return early using original strFile if no match found if (relFile == null) return new File(strFile); foundPath = relFile.getPath().replaceFirst("." + file_separator, ""); start_idx = 1; } } // of the substrings if found for (int idx = start_idx; idx < subpaths.length; idx++) { String huntPath = null; if (!foundPath.equals("")) { // foundPath has been set, either above or in prior iteration, so go with it huntPath = foundPath + File.separator + subpaths[idx]; } else { // and possibly foundPath prior to use if (theFile.isAbsolute()) { // absolute file, start with separator and hunt for subpaths[idx] foundPath = File.separator; huntPath = subpaths[idx]; } else { // relative file, use subpaths[idx] as starting point // foundPath is set above huntPath = subpaths[idx]; } } File tfile = new File(huntPath); if (tfile.exists()) { // path exists as is, so use it exactly foundPath = tfile.getPath(); } else { // path does not exist as is, so search for case permuted variants // we know that foundPath exists so use helper method for // case insensitive compares taking the first match found caseInsensitiveFile = findFileMP(foundPath, subpaths[idx]); if (caseInsensitiveFile != null) { // variant found, use it in the foundPath foundPath = caseInsensitiveFile.getPath(); } else { // no case permuted variant exists. // return File based on current foundPath and // remaining portion of original input strFile path String therest = ""; for (int i = idx; i < subpaths.length; i++) { therest += File.separator + subpaths[i]; } return new File(foundPath + therest); } } } // of returning caseInsensitiveFile. guess is object goes out of scope. return new File(foundPath); }
Example 25
| Project: deccanplato-master File: CommonTest.java View source code |
public RequestData commonTest(String function, String activity, String provider) {
BufferedReader br = null;
String inputJsonPath;
try {
inputJsonPath = new File(".").getCanonicalPath() + java.io.File.separator + "src" + java.io.File.separator + "test" + java.io.File.separator + "resources" + java.io.File.separator + provider + java.io.File.separator + function + "_" + activity + ".json";
br = new BufferedReader(new FileReader(inputJsonPath));
String currentLine = "";
while ((currentLine = br.readLine()) != null) {
strb.append(currentLine);
}
rdb = new RequestDataBuilder(strb.toString());
reqData = rdb.data();
} catch (IOException e) {
e.printStackTrace();
}
return reqData;
}Example 26
| Project: docx4j-master File: PatcherTest.java View source code |
@Test
public void testSimpleDocx() throws Exception {
// Should return no differences
log.warn("\ntestSimpleDocx\n");
String inputfilepath = resourceDir + "paragraph-single.docx";
WordprocessingMLPackage thisPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
WordprocessingMLPackage otherPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
Alterations alterations = AlteredParts.start(thisPackage, otherPackage);
Patcher.apply(otherPackage, alterations);
// if (save) {
// SaveToZipFile saver = new SaveToZipFile(otherPackage);
// saver.save(DIR_OUT+"patch-producing-header-section2.docx");
// }
Assert.assertTrue(java.util.Arrays.equals(marshallFlatOPC(thisPackage).toByteArray(), marshallFlatOPC(otherPackage).toByteArray()));
}Example 27
| Project: pojobuilder-master File: Pojo2Builder.java View source code |
/**
* Creates a new {@link Pojo2} based on this builder's settings.
*
* @return the created Pojo2
*/
@Override
public Pojo2 get() {
try {
Pojo2 result = new Pojo2(value$file$java$io$File);
if (isSet$age$int) {
result.setAge(value$age$int);
}
if (isSet$name$java$lang$String) {
result.name = value$name$java$lang$String;
}
return result;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new java.lang.reflect.UndeclaredThrowableException(ex);
}
}Example 28
| Project: Secure-Service-Specification-and-Deployment-master File: CompositeServiceFactory.java View source code |
public static boolean createServiceInstance(String compositionPlanId, String compositionPlanName, String activitiEngineAddress, String usernameActivitiEngine, String passwordActivitiEngine) {
new java.io.File(compositionPlanName + "/").mkdir();
new java.io.File(compositionPlanName + "/WEB-INF").mkdir();
new java.io.File(compositionPlanName + "/WEB-INF/classes").mkdir();
new java.io.File(compositionPlanName + "/WEB-INF/lib").mkdir();
java.io.File serviceInterface = new java.io.File(compositionPlanName + "/" + compositionPlanName + ".java");
java.io.File serviceImplementation = new java.io.File(compositionPlanName + "/" + compositionPlanName + "Impl.java");
try {
FileWriter serviceInterfaceFW = new FileWriter(serviceInterface);
serviceInterfaceFW.write("package eu.aniketos.compositeService;\n" + "import javax.jws.WebService;\n" + "@WebService\n" + "public interface " + compositionPlanName + "{\n" + "void start" + compositionPlanName + "();\n" + "}\n");
serviceInterfaceFW.close();
FileWriter serviceImplementationFW = new FileWriter(serviceImplementation);
serviceImplementationFW.write("package eu.aniketos.compositeService;\n" + "import javax.jws.WebService;\n" + "import java.net.URL;\n" + "import org.apache.http.HttpHost;\n" + "import org.apache.http.HttpResponse;\n" + "import org.apache.http.auth.AuthScope;\n" + "import org.apache.http.auth.UsernamePasswordCredentials;\n" + "import org.apache.http.client.AuthCache;\n" + "import org.apache.http.client.ClientProtocolException;\n" + "import org.apache.http.client.methods.HttpPost;\n" + "import org.apache.http.client.protocol.ClientContext;\n" + "import org.apache.http.entity.mime.MultipartEntity;\n" + "import org.apache.http.entity.mime.content.FileBody;\n" + "import org.apache.http.entity.mime.content.StringBody;\n" + "import org.apache.http.impl.auth.BasicScheme;\n" + "import org.apache.http.impl.client.BasicAuthCache;\n" + "import org.apache.http.impl.client.DefaultHttpClient;\n" + "import org.apache.http.protocol.BasicHttpContext;\n" + "import org.apache.http.entity.StringEntity;\n" + "import java.io.IOException;\n" + "import java.io.IOException;\n" + "@WebService(endpointInterface = \"eu.aniketos.compositeService." + compositionPlanName + "\")\n" + "public class " + compositionPlanName + "Impl implements " + compositionPlanName + " {\n" + "public void start" + compositionPlanName + "() {\n" + "DefaultHttpClient httpclient = new DefaultHttpClient();\n" + "try {\n" + "URL url = new URL(\"" + activitiEngineAddress + "\");\n" + "String scheme = url.getProtocol();\n" + "String hostName = url.getHost();\n" + "int port = url.getPort();\n" + "HttpHost targetHost = new HttpHost(hostName, port, scheme);\n" + "httpclient.getCredentialsProvider().setCredentials(\n" + "new AuthScope(targetHost.getHostName(), targetHost.getPort()),new UsernamePasswordCredentials(\"" + usernameActivitiEngine + "\", \"" + passwordActivitiEngine + "\"));\n" + "AuthCache authCache = new BasicAuthCache();\n" + "BasicScheme basicAuth = new BasicScheme();\n" + "authCache.put(targetHost, basicAuth);\n" + "BasicHttpContext localcontext = new BasicHttpContext();\n" + "localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);\n" + "HttpPost httpPost = new HttpPost(\"" + activitiEngineAddress + "/activiti-rest/service/process-instance\");\n" + "StringEntity input = new StringEntity(\"{\\\"processDefinitionId\\\":\\\"" + compositionPlanId + "\\\"}\");\n" + "input.setContentType(\"application/json\");\n" + "httpPost.setEntity(input);\n" + "HttpResponse response = httpclient.execute(httpPost, localcontext);\n" + "} catch (ClientProtocolException e) {\n" + "e.printStackTrace();\n" + "} catch (IOException e) {\n" + "e.printStackTrace();\n" + "} finally {\n" + "try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}\n" + "}\n" + "}\n" + "}");
serviceImplementationFW.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new java.io.File(compositionPlanName + "/WEB-INF/classes")));
URL urlHttpclient = org.eclipse.core.runtime.FileLocator.toFileURL((Activator.getContext().getBundle().getEntry("lib/httpclient-4.2.jar")));
URL urlHttpcore = org.eclipse.core.runtime.FileLocator.toFileURL((Activator.getContext().getBundle().getEntry("lib/httpcore-4.2.jar")));
URL urlHttpmime = org.eclipse.core.runtime.FileLocator.toFileURL((Activator.getContext().getBundle().getEntry("lib/httpmime-4.2.jar")));
fileManager.setLocation(StandardLocation.CLASS_PATH, Arrays.asList(new java.io.File(urlHttpmime.getPath()), new java.io.File(urlHttpclient.getPath()), new java.io.File(urlHttpcore.getPath()), new java.io.File(compositionPlanName + "/WEB-INF/classes")));
// Compile the interface java file of the composition instance
compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(serviceInterface))).call();
// Compile the implementation java file of the composition instance
compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(serviceImplementation))).call();
fileManager.close();
serviceInterface.delete();
serviceImplementation.delete();
log.debug("Service Instance created");
return true;
} catch (IOException IOE) {
log.error("IOException", IOE);
return false;
}
}Example 29
| Project: abstools-master File: FileHandler.java View source code |
private String name(File f) {
StringBuilder builder = new StringBuilder();
for (ABSValue value : cutil.convert(filePath_f.apply(f))) {
if (value instanceof ABSString) {
builder.append(((ABSString) value).getString()).append(sep);
}
}
return builder.substring(0, builder.length() - 1).toString();
}Example 30
| Project: Secrecy_fDroid_DEPRECIATED-master File: Vault.java View source code |
public void initialize() {
java.io.File nomedia = new java.io.File(storage.getRoot().getAbsolutePath() + "/" + name + "/.nomedia");
if (!nomedia.exists())
return;
File nomediafile = new File(nomedia, key);
java.io.File tempnomedia = nomediafile.readFile(new CryptStateListener() {
@Override
public void updateProgress(int progress) {
}
@Override
public void setMax(int max) {
}
@Override
public void onFailed(int statCode) {
}
@Override
public void Finished() {
}
});
if (tempnomedia != null) {
wrongPass = false;
storage.purgeFile(tempnomedia);
}
Util.log("Password is Wrong=", wrongPass);
}Example 31
| Project: catalyst-master File: MappedBuffer.java View source code |
/**
* Allocates a mapped buffer.
* <p>
* Memory will be mapped by opening and expanding the given {@link java.io.File} to the desired {@code count} and mapping the
* file contents into memory via {@link java.nio.channels.FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
* <p>
* The resulting buffer will have a capacity of {@code initialCapacity}. The underlying {@link UnsafeMappedBytes} will be
* initialized to the next power of {@code 2}. As bytes are written to the buffer, the buffer's capacity will double
* as long as {@code maxCapacity > capacity}.
*
* @param file The file to map into memory. If the file doesn't exist it will be automatically created.
* @param mode The mode with which to map the file.
* @param initialCapacity The initial capacity of the buffer.
* @param maxCapacity The maximum capacity of the buffer.
* @return The mapped buffer.
* @throws NullPointerException If {@code file} is {@code null}
* @throws IllegalArgumentException If the {@code capacity} or {@code maxCapacity} is greater than
* {@link Integer#MAX_VALUE}.
*
* @see #allocate(java.io.File)
* @see #allocate(java.io.File, java.nio.channels.FileChannel.MapMode)
* @see #allocate(java.io.File, long)
* @see #allocate(java.io.File, java.nio.channels.FileChannel.MapMode, long)
* @see #allocate(java.io.File, long, long)
*/
public static MappedBuffer allocate(File file, FileChannel.MapMode mode, long initialCapacity, long maxCapacity) {
if (file == null)
throw new NullPointerException("file cannot be null");
if (mode == null)
mode = FileChannel.MapMode.READ_WRITE;
if (initialCapacity > maxCapacity)
throw new IllegalArgumentException("initial capacity cannot be greater than maximum capacity");
if (initialCapacity > Integer.MAX_VALUE)
throw new IllegalArgumentException("initial capacity for MappedBuffer cannot be greater than " + Integer.MAX_VALUE);
if (maxCapacity > Integer.MAX_VALUE)
throw new IllegalArgumentException("maximum capacity for MappedBuffer cannot be greater than " + Integer.MAX_VALUE);
return new MappedBuffer(MappedBytes.allocate(file, initialCapacity), 0, initialCapacity, maxCapacity);
}Example 32
| Project: opencast-master File: ZipUtil.java View source code |
/** * Utility class to ease the process of umounting a zip file * * @param zipFile * The file to umount * @throws IOException * If some problem occurs on unmounting */ private static void umount(File zipFile) throws IOException { try { File.umount(zipFile); } catch (ArchiveWarningException awe) { logger.warn("Umounting {} threw the following warning: {}", zipFile.getCanonicalPath(), awe.getMessage()); } catch (ArchiveException ae) { logger.error("Unable to umount zip file: {}", zipFile.getCanonicalPath()); throw new IOException("Unable to umount zip file: " + zipFile.getCanonicalPath(), ae); } }
Example 33
| Project: VCameraDemo-master File: ZipUtils.java View source code |
/** * å?–得压缩包ä¸çš„ æ–‡ä»¶åˆ—表(文件夹,文件自选) * * @param zipFileString 压缩包å??å— * @param bContainFolder 是å?¦åŒ…括 文件夹 * @param bContainFile 是å?¦åŒ…括 文件 * @return * @throws Exception */ public static java.util.List<java.io.File> GetFileList(String zipFileString, boolean bContainFolder, boolean bContainFile) throws Exception { java.util.List<java.io.File> fileList = new java.util.ArrayList<java.io.File>(); java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString)); java.util.zip.ZipEntry zipEntry; String szName = ""; while ((zipEntry = inZip.getNextEntry()) != null) { szName = zipEntry.getName(); if (zipEntry.isDirectory()) { // get the folder name of the widget szName = szName.substring(0, szName.length() - 1); java.io.File folder = new java.io.File(szName); if (bContainFolder) { fileList.add(folder); } } else { java.io.File file = new java.io.File(szName); if (bContainFile) { fileList.add(file); } } } //end of while inZip.close(); return fileList; }
Example 34
| Project: CameraV-master File: StorageManager.java View source code |
public static boolean mountStorage(Context context, String storagePath, byte[] passphrase) {
File dbFile = null;
if (storagePath == null) {
dbFile = new java.io.File(context.getDir("vfs", Context.MODE_PRIVATE), DEFAULT_PATH);
} else {
dbFile = new java.io.File(storagePath);
}
dbFile.getParentFile().mkdirs();
if (!dbFile.exists())
VirtualFileSystem.get().createNewContainer(dbFile.getAbsolutePath(), passphrase);
if (!VirtualFileSystem.get().isMounted()) {
// TODO don't use a hard-coded password! prompt for the password
VirtualFileSystem.get().mount(dbFile.getAbsolutePath(), passphrase);
}
return true;
}Example 35
| Project: informa-master File: IOService.java View source code |
public boolean saveBlob(byte[] data, java.io.File file, boolean isPublic) throws IOException {
if (!isPublic) {
return saveBlob(data, file);
} else {
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
}
return false;
}
}Example 36
| Project: InformaCore-master File: IOService.java View source code |
public boolean saveBlob(byte[] data, java.io.File file, boolean isPublic) throws IOException {
if (!isPublic) {
return saveBlob(data, file);
} else {
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG, e.toString());
e.printStackTrace();
}
return false;
}
}Example 37
| Project: RouteConverter-master File: DataSourceManager.java View source code |
public void initialize(String edition, java.io.File directory) throws IOException, JAXBException { java.io.File file = new File(directory, edition + DOT_XML); log.info(format("Initializing edition '%s' from %s", edition, file)); Edition anEdition = loadEdition(file); if (anEdition == null) return; this.dataSourceService = loadDataSources(anEdition.getDataSources(), directory); }
Example 38
| Project: SonarTsPlugin-master File: PathResolverImpl.java View source code |
String getAbsolutePath(SensorContext context, String toReturn) {
if (toReturn != null) {
File candidateFile = new java.io.File(toReturn);
if (!candidateFile.isAbsolute()) {
candidateFile = new java.io.File(context.fileSystem().baseDir().getAbsolutePath(), toReturn);
}
if (!doesFileExist(candidateFile)) {
return null;
}
return candidateFile.getAbsolutePath();
}
return null;
}Example 39
| Project: jajuk-master File: PasteAction.java View source code |
@SuppressWarnings("cast")
@Override
public void run() {
UtilGUI.waiting();
// Compute all files to move from various items list
if (itemsToMove.size() == 0) {
Log.debug("None item to move");
return;
}
Item first = itemsToMove.get(0);
if (first instanceof Album || first instanceof Artist || first instanceof Genre) {
List<Track> tracks = TrackManager.getInstance().getAssociatedTracks(itemsToMove, true);
for (Track track : tracks) {
alFiles.addAll(track.getFiles());
}
} else {
for (Item item : itemsToMove) {
if (item instanceof File) {
alFiles.add((File) item);
} else if (item instanceof Track) {
alFiles.addAll(((Track) item).getFiles());
} else if (item instanceof Directory) {
alDirs.add((Directory) item);
} else if (item instanceof Playlist) {
alPlaylists.add((Playlist) item);
}
}
}
// Compute destination directory
// alSelected can contain either a single Directory or a single Device
Item item = alSelected.get(0);
java.io.File dir;
Directory destDir;
if (item instanceof Directory) {
dir = new java.io.File(((Directory) item).getAbsolutePath());
destDir = (Directory) item;
} else if (item instanceof Device) {
dir = new java.io.File(((Device) item).getRootDirectory().getAbsolutePath());
destDir = ((Device) item).getRootDirectory();
} else {
dir = ((File) item).getDirectory().getFio();
destDir = ((File) item).getDirectory();
}
// Compute source directories
// We need to find the highest directory in order to refresh it along
// with the destination file to avoid phantom references
List<Directory> srcDirs = new ArrayList<Directory>(1);
for (File file : alFiles) {
boolean parentAlreadyPresent = false;
// grow
for (int i = 0; i < srcDirs.size(); i++) {
Directory directory = srcDirs.get(i);
if (file.getDirectory().isChildOf(directory)) {
parentAlreadyPresent = true;
break;
}
}
if (!parentAlreadyPresent && !srcDirs.contains(file.getDirectory())) {
srcDirs.add(file.getDirectory());
}
}
for (Playlist pl : alPlaylists) {
boolean parentAlreadyPresent = false;
// grow
for (int i = 0; i < srcDirs.size(); i++) {
Directory directory = srcDirs.get(i);
if (pl.getDirectory().isChildOf(directory)) {
parentAlreadyPresent = true;
break;
}
}
if (!parentAlreadyPresent && !srcDirs.contains(pl.getDirectory())) {
srcDirs.add(pl.getDirectory());
}
}
boolean overwriteAll = false;
boolean bErrorOccured = false;
if (moveAction == ItemMoveManager.MoveActions.CUT) {
for (File f : alFiles) {
if (!overwriteAll) {
java.io.File newFile = new java.io.File(dir.getAbsolutePath() + "/" + f.getName());
if (newFile.exists()) {
int iResu = Messages.getChoice(Messages.getString("Confirmation_file_overwrite") + " : \n\n" + f.getName(), Messages.YES_NO_ALL_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (iResu == JOptionPane.NO_OPTION || iResu == JOptionPane.CANCEL_OPTION) {
UtilGUI.stopWaiting();
return;
}
if (iResu == Messages.ALL_OPTION) {
overwriteAll = true;
}
}
}
try {
showMessage(f.getFIO());
FileManager.getInstance().changeFileDirectory(f, destDir);
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
for (Playlist pl : alPlaylists) {
if (!overwriteAll) {
java.io.File newFile = new java.io.File(dir.getAbsolutePath() + "/" + pl.getName());
if (newFile.exists()) {
int iResu = Messages.getChoice(Messages.getString("Confirmation_file_overwrite") + " : \n\n" + pl.getName(), Messages.YES_NO_ALL_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (iResu == JOptionPane.NO_OPTION || iResu == JOptionPane.CANCEL_OPTION) {
UtilGUI.stopWaiting();
return;
}
if (iResu == Messages.ALL_OPTION) {
overwriteAll = true;
}
}
}
try {
showMessage(pl.getFIO());
final java.io.File fileNew = new java.io.File(new StringBuilder(dir.getAbsolutePath()).append("/").append(pl.getName()).toString());
if (!pl.getFIO().renameTo(fileNew)) {
throw new Exception("Cannot move item: " + pl.getFIO().getAbsolutePath() + " to " + fileNew.getAbsolutePath());
}
// Refresh source and destination
destDir.refresh(false);
// Refresh source directories as well
for (Directory srcDir : srcDirs) {
srcDir.refresh(false);
}
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
for (Directory d : alDirs) {
try {
java.io.File src = new java.io.File(d.getAbsolutePath());
java.io.File dst = new java.io.File(dir.getAbsolutePath() + "/" + d.getName());
showMessage(src);
java.io.File newDir = new java.io.File(new StringBuilder(dst.getAbsolutePath()).toString());
if (!src.renameTo(newDir)) {
throw new Exception("Cannot move item: " + src.getAbsolutePath() + " to " + dst.getAbsolutePath());
}
DirectoryManager.getInstance().removeDirectory(d.getID());
destDir.refresh(false);
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
try {
destDir.refresh(false);
// Refresh source directories as well
for (Directory srcDir : srcDirs) {
srcDir.refresh(false);
}
} catch (Exception e1) {
Log.error(e1);
bErrorOccured = true;
}
} else if (moveAction == ItemMoveManager.MoveActions.COPY) {
for (File f : alFiles) {
if (!overwriteAll) {
java.io.File newFile = new java.io.File(dir.getAbsolutePath() + "/" + f.getName());
if (newFile.exists()) {
int iResu = Messages.getChoice(Messages.getString("Confirmation_file_overwrite") + " : \n\n" + f.getName(), Messages.YES_NO_ALL_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (iResu == JOptionPane.NO_OPTION || iResu == JOptionPane.CANCEL_OPTION) {
UtilGUI.stopWaiting();
return;
}
if (iResu == Messages.ALL_OPTION) {
overwriteAll = true;
}
}
}
try {
showMessage(f.getFIO());
UtilSystem.copyToDir(f.getFIO(), dir);
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
for (Playlist pl : alPlaylists) {
if (!overwriteAll) {
java.io.File newFile = new java.io.File(dir.getAbsolutePath() + "/" + pl.getName());
if (newFile.exists()) {
int iResu = Messages.getChoice(Messages.getString("Confirmation_file_overwrite") + " : \n\n" + pl.getName(), Messages.YES_NO_ALL_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (iResu == JOptionPane.NO_OPTION || iResu == JOptionPane.CANCEL_OPTION) {
UtilGUI.stopWaiting();
return;
}
if (iResu == Messages.ALL_OPTION) {
overwriteAll = true;
}
}
}
try {
showMessage(pl.getFIO());
UtilSystem.copyToDir(pl.getFIO(), dir);
// Refresh source and destination
destDir.refresh(false);
// Refresh source directories as well
for (Directory srcDir : srcDirs) {
srcDir.refresh(false);
}
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
for (Directory d : alDirs) {
try {
java.io.File src = new java.io.File(d.getAbsolutePath());
java.io.File dst = new java.io.File(dir.getAbsolutePath() + "/" + d.getName());
showMessage(src);
UtilSystem.copyRecursively(src, dst);
} catch (Exception ioe) {
Log.error(131, ioe);
Messages.showErrorMessage(131);
bErrorOccured = true;
}
}
try {
destDir.refresh(false);
} catch (Exception e1) {
Log.error(e1);
bErrorOccured = true;
}
}
ObservationManager.notify(new JajukEvent(JajukEvents.DEVICE_REFRESH));
UtilGUI.stopWaiting();
if (!bErrorOccured) {
InformationJPanel.getInstance().setMessage(Messages.getString("Success"), InformationJPanel.MessageType.INFORMATIVE);
}
}Example 40
| Project: platform-api-master File: DefaultBuilderConfigurationFactory.java View source code |
@Override
public BuilderConfiguration createBuilderConfiguration(BaseBuilderRequest request) throws BuilderException {
if (request instanceof BuildRequest) {
final java.io.File buildDir = createBuildDir();
return new BuilderConfiguration(buildDir, createWorkDir(buildDir, request), BuilderTaskType.DEFAULT, request);
} else if (request instanceof DependencyRequest) {
final DependencyRequest myRequest = (DependencyRequest) request;
String type = myRequest.getType();
if (type == null) {
type = "list";
}
final BuilderTaskType taskType;
switch(type) {
case "copy":
taskType = BuilderTaskType.COPY_DEPS;
break;
case "list":
taskType = BuilderTaskType.LIST_DEPS;
break;
default:
throw new BuilderException(String.format("Unsupported type of an analysis task: %s. Should be either 'list' or 'copy'", type));
}
final java.io.File buildDir = createBuildDir();
return new BuilderConfiguration(buildDir, createWorkDir(buildDir, request), taskType, myRequest);
}
throw new BuilderException("Unsupported type of request");
}Example 41
| Project: basespace-igv-master File: BaseSpaceResourceLocator.java View source code |
protected java.io.File getLocalFile(final File file) throws IOException { try { java.io.File localFile = getCachedLocalFile(file); // Crude staleness check -- if more than a day old discard long age = System.currentTimeMillis() - localFile.lastModified(); if (age > oneDay) { localFile.delete(); } if (!localFile.exists() || localFile.length() < 1) { log.info("Downloading file from BaseSpace->" + file.getName() + " to " + localFile.toString()); ApiClient client = BaseSpaceMain.instance().getApiClient(getClientId()); BaseSpaceUtil.downloadFile(client, file, localFile); // TODO: This doesn't actually work because the file is left open localFile.deleteOnExit(); } return localFile; } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } }
Example 42
| Project: bazel-master File: MultipleDelimitedArgumentsTest.java View source code |
@Test
public void supportsMultipleDelimitedArguments() {
OptionParser parser = new OptionParser();
OptionSpec<File> path = parser.accepts("path").withRequiredArg().ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
OptionSet options = parser.parse("--path", join(pathSeparatorChar, "/tmp", "/var", "/opt"));
assertTrue(options.has(path));
assertTrue(options.hasArgument(path));
assertEquals(asList(new File("/tmp"), new File("/var"), new File("/opt")), options.valuesOf(path));
}Example 43
| Project: casperjs-runner-maven-plugin-master File: PathToNameBuilder.java View source code |
public static String buildName(File rootDir, File path) { String result = path.getAbsolutePath(); String rootPath = rootDir.getAbsolutePath(); if (!rootPath.endsWith(separator)) { rootPath += separator; } if (!result.contains(rootPath)) { throw new IllegalArgumentException(path + " should be a child of " + rootDir); } result = result.replace(rootPath, ""); // for Linux paths result = result.replaceAll("/", REPLACEMENT_CHAR); // for Windows paths result = result.replaceAll("\\\\", REPLACEMENT_CHAR); result = result.replaceAll("\\.", REPLACEMENT_CHAR); return result; }
Example 44
| Project: checkstyle-master File: AvoidStaticImportCheckTest.java View source code |
@Test
public void testDefaultOperation() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(AvoidStaticImportCheck.class);
final String[] expected = { "23: " + getCheckMessage(MSG_KEY, "java.io.File.listRoots"), "25: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "26: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "27: " + getCheckMessage(MSG_KEY, "java.io.File.createTempFile"), "28: " + getCheckMessage(MSG_KEY, "java.io.File.pathSeparator"), "29: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "InputAvoidStaticImportNestedClass.InnerClass"), "30: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "InputAvoidStaticImportNestedClass.InnerClass.one") };
verify(checkConfig, getPath("InputAvoidStaticImport.java"), expected);
}Example 45
| Project: Correct-master File: MultipleDelimitedArgumentsTest.java View source code |
@Test
public void supportsMultipleDelimitedArguments() {
OptionParser parser = new OptionParser();
OptionSpec<File> path = parser.accepts("path").withRequiredArg().ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
OptionSet options = parser.parse("--path", join(pathSeparatorChar, "/tmp", "/var", "/opt"));
assertTrue(options.has(path));
assertTrue(options.hasArgument(path));
assertEquals(asList(new File("/tmp"), new File("/var"), new File("/opt")), options.valuesOf(path));
}Example 46
| Project: folioxml-master File: OutputRedirector.java View source code |
public void open() throws FileNotFoundException, UnsupportedEncodingException {
//Save so we can restore them later.
stdout = System.out;
stderr = System.err;
//Make the dir if it is missing
if (!new java.io.File(filename).getParentFile().exists())
new java.io.File(filename).getParentFile().mkdirs();
out = new FileOutputStream(filename);
System.out.println("Redirecting output to " + filename);
System.setOut(new PrintStream(out, true, "UTF-8"));
System.setErr(new PrintStream(out, true, "UTF-8"));
}Example 47
| Project: jopt-simple-master File: MultipleDelimitedArgumentsTest.java View source code |
@Test
public void supportsMultipleDelimitedArguments() {
OptionParser parser = new OptionParser();
OptionSpec<File> path = parser.accepts("path").withRequiredArg().ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
OptionSet options = parser.parse("--path", Stream.of("/tmp", "/var", "/opt").collect(joining(pathSeparator)));
assertTrue(options.has(path));
assertTrue(options.hasArgument(path));
assertEquals(asList(new File("/tmp"), new File("/var"), new File("/opt")), options.valuesOf(path));
}Example 48
| Project: plugin-java-master File: AntUtils.java View source code |
public static String getAntExecCommand() {
final java.io.File antHome = getAntHome();
if (antHome != null) {
final String ant = "bin" + java.io.File.separatorChar + "ant";
// If ant home directory set use it
return new java.io.File(antHome, ant).getAbsolutePath();
} else {
// otherwise 'ant' should be in PATH variable
return "ant";
}
}Example 49
| Project: rasterizer-master File: PdfFileFilter.java View source code |
/* (non-Javadoc) * @see javax.swing.filechooser.FileFilter#accept(java.io.File) */ public boolean accept(File f) { if (f.isDirectory()) { return true; } String s = f.getName(); int i = s.lastIndexOf("."); String extension = null; if (i > 0 && i < s.length() - 1) { extension = s.substring(i + 1).toLowerCase(); } if (extension != null) { if (extension.equals("pdf")) { return true; } else { return false; } } return false; }
Example 50
| Project: test-master File: MultipleDelimitedArgumentsTest.java View source code |
@Test
public void supportsMultipleDelimitedArguments() {
OptionParser parser = new OptionParser();
OptionSpec<File> path = parser.accepts("path").withRequiredArg().ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
OptionSet options = parser.parse("--path", join(pathSeparatorChar, "/tmp", "/var", "/opt"));
assertTrue(options.has(path));
assertTrue(options.hasArgument(path));
assertEquals(asList(new File("/tmp"), new File("/var"), new File("/opt")), options.valuesOf(path));
}Example 51
| Project: CommunityWebsite-master File: FileAction.java View source code |
/**
* 文件é‡?命å??
* @param oldName 原å??
* @param newName æ–°å??
* @return
*/
public static boolean reName(String oldName, String newName) {
boolean result = false;
try {
java.io.File myFile = new java.io.File(oldName);
java.io.File NewFile = new java.io.File(newName);
myFile.renameTo(NewFile);
result = true;
} catch (Exception e) {
System.out.println("åˆ é™¤æ–‡ä»¶æ“?作出错");
}
return result;
}Example 52
| Project: pegasus-master File: RosettaDAX.java View source code |
public void constructDAX(String daxfile) {
try {
java.io.File cwdFile = new java.io.File(".");
String cwd = cwdFile.getCanonicalPath();
// construct a dax object
ADAG dax = new ADAG("rosetta");
// executables and transformations
// including this in the dax is a new feature in
// 3.0. Earlier you had a standalone transformation catalog
Executable exe = new Executable("rosetta.exe");
// the executable is not installed on the remote sites, so
// pick it up from the local file system
exe.setInstalled(false);
exe.addPhysicalFile("file://" + cwd + "/rosetta.exe", "local");
// cluster the jobs together to lessen the grid overhead
exe.addProfile("pegasus", "clusters.size", "3");
// the dag needs to know about the executable to handle
// transferrring
dax.addExecutable(exe);
// all jobs depend on the flatfile databases
List<File> inputs = new ArrayList<File>();
recursiveAddToFileCollection(inputs, "minirosetta_database", "Rosetta Database");
// for replica catalog
dax.addFiles(inputs);
// and some top level files
File f1 = new File("design.resfile", File.LINK.INPUT);
f1.addPhysicalFile("file://" + cwd + "/design.resfile", "local");
dax.addFile(f1);
// dependency for the job
inputs.add(f1);
File f2 = new File("repack.resfile", File.LINK.INPUT);
f2.addPhysicalFile("file://" + cwd + "/repack.resfile", "local");
dax.addFile(f2);
// dependency for the job
inputs.add(f2);
java.io.File pdbDir = new java.io.File("pdbs/");
String pdbs[] = pdbDir.list();
//for (int i = 0; i < pdbs.length; i++) {
for (int i = 0; i < 2; i++) {
java.io.File pdb = new java.io.File("pdbs/" + pdbs[i]);
if (pdb.isFile()) {
Job j = createJobFromPDB(dax, pdb, inputs);
dax.addJob(j);
}
}
//write DAX to file
dax.writeToFile(daxfile);
} catch (Exception e) {
e.printStackTrace();
}
}Example 53
| Project: sosies-generator-master File: CompositeFileComparatorTest.java View source code |
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
comparator = new CompositeFileComparator(SizeFileComparator.SIZE_COMPARATOR, ExtensionFileComparator.EXTENSION_COMPARATOR);
reverse = new ReverseComparator(comparator);
File dir = org.apache.commons.io.testtools.FileBasedTestCase.getTestDirectory();
lessFile = new File(dir, "xyz.txt");
equalFile1 = new File(dir, "foo.txt");
equalFile2 = new File(dir, "bar.txt");
moreFile = new File(dir, "foo.xyz");
createFile(lessFile, 32);
createFile(equalFile1, 48);
createFile(equalFile2, 48);
createFile(moreFile, 48);
}Example 54
| Project: wicket-master File: FilesTest.java View source code |
/**
* Tests for {@link Files#remove(java.io.File)}
*
* @throws IOException
*/
@Test
public void remove() throws IOException {
assertFalse("'null' files are not deleted.", Files.remove(null));
assertFalse("Non existing files are not deleted.", Files.remove(new File("/somethingThatDoesntExistsOnMostMachines-111111111111111111111111111111")));
java.io.File file = getFile();
file.createNewFile();
assertTrue("The just created file should exist!", file.isFile());
boolean removed = Files.remove(file);
assertFalse("The just removed file should not exist!", file.exists());
assertTrue("Files.remove(file) should remove the file", removed);
// try to remove non-existing file
removed = Files.remove(file);
assertFalse("The just removed file should not exist!", file.exists());
assertFalse("Files.remove(file) should not remove the file", removed);
// try to remove a folder
java.io.File folder = getFolder();
Files.mkdirs(folder);
assertTrue(folder.isDirectory());
assertFalse("Should not be able to delete a folder, even empty one.", Files.remove(folder));
assertTrue("Should not be able to delete a folder.", Files.removeFolder(folder));
}Example 55
| Project: twiterra-master File: AbstractFileCache.java View source code |
public void addCacheLocation(int index, String newPath) {
if (newPath == null || newPath.length() == 0) {
String message = Logging.getMessage("nullValue.FileCachePathIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (index < 0) {
String message = Logging.getMessage("generic.InvalidIndex", index);
Logging.logger().fine(message);
throw new IllegalArgumentException(message);
}
if (index > 0 && index > this.cacheDirs.size())
index = this.cacheDirs.size();
java.io.File newFile = new java.io.File(newPath);
if (this.cacheDirs.contains(newFile))
this.cacheDirs.remove(newFile);
this.cacheDirs.add(index, newFile);
}Example 56
| Project: che-master File: AntUtils.java View source code |
public static String getAntExecCommand() {
final java.io.File antHome = getAntHome();
if (antHome != null) {
final String ant = "bin" + java.io.File.separatorChar + "ant";
// If ant home directory set use it
return new java.io.File(antHome, ant).getAbsolutePath();
} else {
// otherwise 'ant' should be in PATH variable
return "ant";
}
}Example 57
| Project: che-plugins-master File: AntUtils.java View source code |
public static String getAntExecCommand() {
final java.io.File antHome = getAntHome();
if (antHome != null) {
final String ant = "bin" + java.io.File.separatorChar + "ant";
// If ant home directory set use it
return new java.io.File(antHome, ant).getAbsolutePath();
} else {
// otherwise 'ant' should be in PATH variable
return "ant";
}
}Example 58
| Project: DevTools-master File: AntUtils.java View source code |
public static String getAntExecCommand() {
final java.io.File antHome = getAntHome();
if (antHome != null) {
final String ant = "bin" + java.io.File.separatorChar + "ant";
// If ant home directory set use it
return new java.io.File(antHome, ant).getAbsolutePath();
} else {
// otherwise 'ant' should be in PATH variable
return "ant";
}
}Example 59
| Project: android-toolkit-master File: ParserTest.java View source code |
@Test
public void testReadAxml() throws Exception {
File pFile = new File("./test-apk/error.apk");
Parser parser = new Parser(pFile);
ManifestInfo manifestInfo = parser.getManifestInfo();
//
// for (String key : manifestInfo.metaData.keySet()) {
// System.out.println(key + ":" + manifestInfo.metaData.get(key));
// }
System.out.println(manifestInfo);
}Example 60
| Project: AndroidAsync-master File: FileUtility.java View source code |
public static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } } return (path.delete()); }
Example 61
| Project: AndroidRepeaterProject-master File: ConfigUtils.java View source code |
public static int getHttpManagerPort() {
File configFile = new File("/data/data/fq.router2/etc/fqsocks.json");
if (!configFile.exists()) {
return 2515;
}
try {
return new JSONObject(IOUtils.readFromFile(configFile)).getJSONObject("http_manager").getInt("port");
} catch (Exception e) {
LogUtils.e("failed to parse config", e);
return 2515;
}
}Example 62
| Project: ApkCategoryChecker-master File: ToolJar2Class.java View source code |
/**
* Extract the content of a jar file
*
* @param _jarPath Path of jar file
* @param _apkDecodedPath Path of decoded APK
*/
public void ConvertJar2Class(String _jarPath, String _apkDecodedPath) {
/*--Initialize the jar file and the destination path directory--*/
File jarFile = new File(_jarPath);
String destDir = _apkDecodedPath + "/classes";
/*--Instance of a JarFile--*/
JarFile jar = null;
try {
jar = new java.util.jar.JarFile(jarFile);
} catch (IOException e) {
e.printStackTrace();
}
Enumeration<JarEntry> en = jar.entries();
while (en.hasMoreElements()) try {
{
java.util.jar.JarEntry file = (java.util.jar.JarEntry) en.nextElement();
java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName());
if (// if its a directory, create it
file.isDirectory()) {
f.mkdir();
continue;
}
java.io.InputStream is = null;
try {
is = jar.getInputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
// get the input stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
while (// write contents of 'is' to 'fos'
is.available() > 0) {
fos.write(is.read());
}
fos.close();
is.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 63
| Project: apollo-android-master File: Utils.java View source code |
static void deleteDirectory(File directory) { if (directory.exists()) { File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } } } directory.delete(); }
Example 64
| Project: ApprovalTests.Java-master File: FileTestUtils.java View source code |
/***********************************************************************/
public static void assertFileRecentlyCreated(String fileName, boolean delete) {
File file = new File(fileName);
try {
TestCase.assertTrue("File exists", file.exists());
TestCase.assertTrue("File recently created", (System.currentTimeMillis() - file.lastModified()) < 5000);
} finally {
if (delete && file.exists()) {
file.delete();
}
}
}Example 65
| Project: ares-studio-master File: Test.java View source code |
public static void main(String[] args) {
ActionInfo ai = new ActionInfo();
// ai.properties.get("id").equals(obj)
// ai.other = "other";
File file = new File("ttt.test");
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
//XStreamConverter.getInstance().write(fos, ai);
} catch (IOException e) {
e.printStackTrace();
}
}Example 66
| Project: Aspose_Pdf_Java-master File: ReplaceImageInExistingPDFFile.java View source code |
public static void main(String[] args) throws Exception {
// Open a document
Document pdfDocument = new Document("input.pdf");
// Replace a particular image
pdfDocument.getPages().get_Item(1).getResources().getImages().replace(1, new java.io.FileInputStream(new java.io.File("apose.png")));
// Save the updated PDF file
pdfDocument.save("output.pdf");
}Example 67
| Project: atlas-master File: PatchCleaner.java View source code |
public void clearUpdatePath(String bundleUpdatePath) {
File updatePath = new File(bundleUpdatePath);
if (updatePath.exists()) {
File[] updatePathArray = updatePath.listFiles();
for (File file : updatePathArray) {
if (file.isDirectory()) {
clearUpdatePath(file.getAbsolutePath());
} else {
file.delete();
}
}
updatePath.delete();
}
}Example 68
| Project: AutoGrader-master File: FileParser.java View source code |
public static DefaultListModel<String> parser(String directory) {
DefaultListModel<String> textFiles = new DefaultListModel<>();
File dir = new File(directory);
if (dir.exists()) {
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.addElement(file.getName().replace(".txt", ""));
}
}
} else
ErrorHandling.ioError();
return textFiles;
}Example 69
| Project: beanfuse-master File: DownloadHelperTest.java View source code |
public void download() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
URL testDoc = DownloadHelperTest.class.getClassLoader().getResource("test.doc");
File file = new File(testDoc.getPath());
DownloadHelper.download(request, response, file);
}Example 70
| Project: Bison-master File: Main.java View source code |
public static void main(String[] args) throws Exception {
if (System.getProperty("conf.dir") == null) {
System.setProperty("conf.dir", "./conf");
}
String config = "";
if ((args == null) || (args.length == 0))
config = System.getProperty("conf.dir") + File.separator + "config.xml";
else {
config = args[0];
}
new Main(config);
}Example 71
| Project: Bringers-of-Singularity-master File: PreprocessSMS.java View source code |
public static void main(String[] args) {
smsCorpusToText.main(null);
CorpusPreprocess.main(new String[] { "50000", "1000", "0" });
try {
asketTest.removeMultiplePunctuations(new File("testSentences0.txt"));
asketTest.removeMultiplePunctuations(new File("ppCorpus.txt"));
asketTest.removeMultiplePunctuations(new File("testSentencesCorrection0.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}Example 72
| Project: ClearJS-master File: BatchTest.java View source code |
public void testBatch() {
File scenariosFolder = new File("scenarios");
File[] scenarios = scenariosFolder.listFiles();
for (File scenario : scenarios) {
if (!scenario.getName().equals(".svn") && !scenario.getName().equals(".DS_Store")) {
executeCDBBuild(scenario.getName(), Project.MSG_INFO);
//executeCDBSpringBuild(scenario.getName(), Project.MSG_INFO);
}
}
}Example 73
| Project: coding2017-master File: Driver.java View source code |
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
File xml = new File("data//xmlparser", "hello.xml");
try {
SAXParser parser = factory.newSAXParser();
parser.parse(xml, new HelloSaxParser());
} catch (Exception e) {
e.printStackTrace();
}
}Example 74
| Project: collaboro-master File: ModelManagerFactory.java View source code |
public static ModelManager createModelManager(Object resource) {
ModelManager modelManager = null;
if (resource instanceof File) {
modelManager = new LocalModelManager();
((LocalModelManager) modelManager).initialize((File) resource);
// } else if(resource instanceof CDOResource) {
//modelManager = new CDOModelManager();
//((CDOModelManager) modelManager).initialize((CDOResource) resource);
} else {
modelManager = new LocalModelManager();
}
return modelManager;
}Example 75
| Project: consulo-master File: PluginDescriptorTest.java View source code |
public void testDescriptorLoading() throws Exception {
String path = TestPathUtil.getTestDataPath().replace(File.separatorChar, '/') + "/ide/plugins/pluginDescriptor";
File file = new File(path + "/asp.jar");
assertTrue(file + " not exist", file.exists());
IdeaPluginDescriptorImpl descriptor = PluginManagerCore.loadDescriptorFromJar(file);
assertNotNull(descriptor);
}Example 76
| Project: Cosmic-Force-master File: ConfigurationHandler.java View source code |
public static void init(File configFile) {
//Create the configuration object from the given configuration file
Configuration configuration = new Configuration(configFile);
try {
//Load the configuration file
configuration.load();
//Read in properties from configuration file
} catch (Exception e) {
} finally {
//Save the configuration file
configuration.save();
}
}Example 77
| Project: crash-master File: FilePublicKeyProviderTest.java View source code |
@Test
public void test() {
String pubKeyFile = Thread.currentThread().getContextClassLoader().getResource("test_authorized_key.pem").getFile();
assertTrue(new File(pubKeyFile).exists());
FilePublicKeyProvider SUT = new FilePublicKeyProvider(new String[] { pubKeyFile });
assertTrue(SUT.loadKeys().iterator().hasNext());
}Example 78
| Project: deadcode4j-master File: FileLoader.java View source code |
/** Returns a file relative to the test classes' directory. */ public static File getFile(String fileName) { Class<FileLoader> fileLoaderClass = FileLoader.class; String classFile = fileLoaderClass.getSimpleName() + ".class"; String pathToClass = fileLoaderClass.getResource(classFile).getFile(); String baseDir = pathToClass.substring(0, pathToClass.length() - (fileLoaderClass.getPackage().getName() + "/" + classFile).length()); return new File(new File(baseDir), fileName); }
Example 79
| Project: deepnighttwo-master File: RootFolderSelector.java View source code |
public static File getRootFolder() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(mainFrame);
return fc.getSelectedFile();
}Example 80
| Project: delight-nashorn-sandbox-master File: TestAllowAndDisallowClasses.java View source code |
@Test
public void test_file() {
final NashornSandbox sandbox = NashornSandboxes.create();
final String testClassScript = "var File = Java.type(\"java.io.File\"); File;";
sandbox.allow(File.class);
sandbox.eval(testClassScript);
boolean _isAllowed = sandbox.isAllowed(File.class);
boolean _not = (!_isAllowed);
if (_not) {
Assert.fail("Expected class File is allowed.");
}
sandbox.disallow(File.class);
try {
sandbox.eval(testClassScript);
Assert.fail("When disallow the File class expected a ClassNotFoundException!");
} catch (final Throwable _t) {
if (_t instanceof RuntimeException) {
final RuntimeException e = (RuntimeException) _t;
if (((!(e.getCause() instanceof ClassNotFoundException)) || (!Objects.equal(e.getCause().getMessage(), "java.io.File")))) {
throw e;
}
} else {
throw Exceptions.sneakyThrow(_t);
}
}
sandbox.allow(File.class);
sandbox.eval(testClassScript);
sandbox.disallowAllClasses();
try {
sandbox.eval(testClassScript);
Assert.fail("When disallow all classes expected a ClassNotFoundException!");
} catch (final Throwable _t_1) {
if (_t_1 instanceof RuntimeException) {
final RuntimeException e_1 = (RuntimeException) _t_1;
if (((!(e_1.getCause() instanceof ClassNotFoundException)) || (!Objects.equal(e_1.getCause().getMessage(), "java.io.File")))) {
throw e_1;
}
} else {
throw Exceptions.sneakyThrow(_t_1);
}
}
}Example 81
| Project: Desktop-master File: DirectoryFileFilter.java View source code |
public boolean accept(File file) {
if (file.isDirectory()) {
List<String> subfolders = getStringList(DocearController.getPropertiesController().getProperty("docear_subdirs_to_ignore", null));
for (String subfolder : subfolders) {
if (file.getName().equals(subfolder)) {
return false;
}
}
return true;
} else {
return false;
}
}Example 82
| Project: dgrid-master File: MimeTypeHelperTestCase.java View source code |
public void testMimeTypeHelper() throws IOException {
MimeTypeHelper helper = (MimeTypeHelper) super.getBean(MimeTypeHelper.NAME);
File textFile = File.createTempFile("test-file", ".txt");
textFile.deleteOnExit();
assertEquals("text/plain", helper.getContentType(textFile));
assertEquals("text/plain", helper.getContentType(textFile.getAbsolutePath()));
}Example 83
| Project: Doris-master File: BaseTestCase.java View source code |
protected String getCurrentClassPath() {
Class<?> clazz = this.getClass();
String path = clazz.getClassLoader().getResource("").getPath();
String clazzName = clazz.getName();
int index = clazzName.lastIndexOf('.');
if (index > 0) {
clazzName = clazzName.substring(0, index);
}
return path + clazzName.replace('.', File.separatorChar);
}Example 84
| Project: dstream-master File: SampleUtils.java View source code |
public static void clean(String applicationName) {
try {
File workDir = new File(System.getProperty("user.dir"));
if (workDir.isDirectory()) {
for (String sub : workDir.list()) {
if (sub.startsWith(applicationName)) {
File file = new File(workDir, sub);
FileUtils.deleteDirectory(file);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 85
| Project: edu-master File: AcceptanceTests.java View source code |
public void testAcceptance() throws Exception {
File targetDirectory = new File("target/storytests");
targetDirectory.mkdirs();
FolderRunner runner = new FolderRunner();
Report report = runner.run(new File("src/test/resources/storytests").getAbsolutePath(), targetDirectory.getAbsolutePath());
System.out.println(report.getCounts());
}Example 86
| Project: epicsarchiverap-master File: PVNameToKeyConverterTest.java View source code |
@Test
public void testKeyName() throws Exception {
DefaultConfigService configService = new ConfigServiceForTests(new File("./bin"));
String expectedKeyName = "A/B/C/D:";
String keyName = configService.getPVNameToKeyConverter().convertPVNameToKey("A:B:C-D");
assertTrue("We were expecting " + expectedKeyName + " instead we got " + keyName, expectedKeyName.equals(keyName));
}Example 87
| Project: FB2OnlineConverter-master File: TempFileUtil.java View source code |
public static File createTempDir() throws IOException { File temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } return temp; }
Example 88
| Project: FolderCamera-master File: ListFileObservable.java View source code |
public Observable<File> create(final File rootDirectory) { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File[] childDirectories = rootDirectory.listFiles(); for (File child : childDirectories) { subscriber.onNext(child); } subscriber.onCompleted(); } }); }
Example 89
| Project: fqrouter-master File: ConfigUtils.java View source code |
public static int getHttpManagerPort() {
File configFile = new File("/data/data/fq.router2/etc/fqsocks.json");
if (!configFile.exists()) {
return 2515;
}
try {
return new JSONObject(IOUtils.readFromFile(configFile)).getJSONObject("http_manager").getInt("port");
} catch (Exception e) {
LogUtils.e("failed to parse config", e);
return 2515;
}
}Example 90
| Project: gradle-master File: TestMain.java View source code |
public static void main(String[] args) throws Exception {
File expectedWorkingDir = new File(args[0]).getCanonicalFile();
File actualWorkingDir = new File(System.getProperty("user.dir")).getCanonicalFile();
if (!expectedWorkingDir.getCanonicalFile().equals(actualWorkingDir)) {
throw new RuntimeException(String.format("Unexpected working directory '%s', expected '%s'.", actualWorkingDir, expectedWorkingDir));
}
File file = new File(args[1]);
file.getParentFile().mkdirs();
file.createNewFile();
}Example 91
| Project: H2-Research-master File: DeleteClasses.java View source code |
public static void listFilesRecursive(File file) throws Exception { File[] files = file.listFiles(); for (File f : files) { String name = f.getName().toLowerCase(); if (f.isDirectory()) listFilesRecursive(f); else if (name.endsWith(".class")) { System.out.println(f); f.delete(); } } }
Example 92
| Project: Hentoid-master File: ListFileObservable.java View source code |
Observable<File> create(final File rootDir) { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File[] childDirs = rootDir.listFiles(); for (File child : childDirs) { subscriber.onNext(child); } subscriber.onCompleted(); } }); }
Example 93
| Project: intellij-community-master File: ExceptionCollectionWithLambda.java View source code |
public void test() throws IOException {
File file = new File("temp");
try {
for (int t = 0; t < 4; ++t) {
for (int i = 0; i < 10; ++i) {
I appender = out -> File.createTempFile("", "").exists();
appender.m("");
}
}
} finally {
System.out.println(file);
}
}Example 94
| Project: java-api-wrapper-master File: DumpToken.java View source code |
public static void main(String[] args) throws Exception {
final File wrapperFile = CreateWrapper.WRAPPER_SER;
if (!wrapperFile.exists()) {
System.err.println("\nThe serialised wrapper (" + wrapperFile + ") does not exist.\n" + "Run CreateWrapper first to create it.");
System.exit(1);
} else {
System.err.println(ApiWrapper.fromFile(wrapperFile).getToken());
}
}Example 95
| Project: JAVA-KOANS-master File: Backup.java View source code |
@Override
protected void copy(String backupSrcDirectory, String appSrcDirectory) throws IOException {
File backupDir = new File(backupSrcDirectory);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
File sourceDir = new File(appSrcDirectory);
new CopyFileOperation(sourceDir, backupDir) {
public void onNew(File file) throws IOException {
file.mkdirs();
}
;
}.operate();
}Example 96
| Project: jdrivesync-master File: FileUtil.java View source code |
public static String toRelativePath(File file, Options options) {
String absolutePathFile = file.getAbsolutePath();
String absolutePathStartDir = options.getLocalRootDir().get().getAbsolutePath();
String relativePath = "/";
if (absolutePathFile.length() > absolutePathStartDir.length()) {
relativePath = absolutePathFile.substring(absolutePathStartDir.length(), absolutePathFile.length());
relativePath = relativePath.replace('\\', '/');
if (!relativePath.startsWith("/")) {
relativePath = "/" + relativePath;
}
}
return relativePath;
}Example 97
| Project: jforth-config-master File: ConfigManagerMain.java View source code |
public static void main(String args[]) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:configBundle-manager.xml");
RemoteConfigManager remoteConfigManager = (RemoteConfigManager) context.getBean("remoteConfigManager");
File config = new File(remoteConfigManager.getClass().getClassLoader().getResource("mkt-appservice.properties").toURI());
remoteConfigManager.initByProperties("mkt-appservice", config);
}Example 98
| Project: JianShuApp-master File: FileUtils.java View source code |
public static boolean deleteDirectory(File dir) { if (!dir.exists() || !dir.isDirectory()) { return false; } String[] files = dir.list(); for (int i = 0, len = files.length; i < len; i++) { File f = new File(dir, files[i]); if (f.isDirectory()) { deleteDirectory(f); } else { f.delete(); } } return dir.delete(); }
Example 99
| Project: jmeter-plugins-master File: STSInstallerTest.java View source code |
@Test
public void name() throws Exception {
File self = new File(STSInstaller.class.getProtectionDomain().getCodeSource().getLocation().getFile());
String home = self.getParentFile().getParentFile().getParent();
File dest = new File(home + File.separator + "bin");
dest.mkdirs();
STSInstaller.main(new String[0]);
FileUtils.deleteDirectory(dest);
}Example 100
| Project: jop-master File: JOPDirectoryValidator.java View source code |
public static boolean isValid(IPath path) {
File f = path.toFile();
if (!f.exists() || !f.isDirectory()) {
return false;
}
File[] children = f.listFiles();
if (children == null) {
return false;
}
for (File c : children) {
if (c.getName().equals("build.xml")) {
return true;
}
}
return false;
}Example 101
| Project: jpcsp-master File: FileUtilTest.java View source code |
@Test
public void testGetExtension() throws Exception {
Assert.assertEquals("txt", FileUtil.getExtension(new File("test/test.txt")));
Assert.assertEquals("demo", FileUtil.getExtension(new File("test/test.DEMO")));
Assert.assertEquals("", FileUtil.getExtension(new File("test/test.")));
Assert.assertEquals("", FileUtil.getExtension(new File("test/test")));
}