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: platform-api-master  File: Runner.java View source code
@Override
public void run() {
    try {
        memoryAllocator.allocate();
        final java.io.File downloadDir = Files.createTempDirectory(deployDirectory.toPath(), ("download_" + getName().replace("/", "."))).toFile();
        final DeploymentSources deploymentSources = createDeploymentSources(request, downloadDir);
        process.addToCleanupList(downloadDir);
        if (!getDeploymentSourcesValidator().isValid(deploymentSources)) {
            throw new RunnerException(String.format("Unsupported project. Cannot deploy project %s from workspace %s with runner %s", request.getProject(), request.getWorkspace(), getName()));
        }
        final ApplicationProcess realProcess = newApplicationProcess(deploymentSources, runnerCfg);
        realProcess.start();
        process.started(realProcess);
        watcher.start(new Cancellable() {

            @Override
            public void cancel() throws Exception {
                process.getLogger().writeLine("[ERROR] Your run has been shutdown due to timeout.");
                process.internalStop(true);
            }
        });
        runningAppsCounter.incrementAndGet();
        LOG.debug("Started {}", process);
        final long endTime = System.currentTimeMillis();
        LOG.debug("Application {}/{} startup in {} ms", request.getWorkspace(), request.getProject(), (endTime - startTime));
        realProcess.waitFor();
        process.stopped();
        LOG.debug("Stopped {}", process);
    } catch (Throwable e) {
        LOG.warn(e.getMessage(), e);
        process.setError(e);
    } finally {
        watcher.stop();
        memoryAllocator.release();
        runningAppsCounter.decrementAndGet();
    }
}
Example 2
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 3
Project: sosies-generator-master  File: OldParserToNewJsonFormat.java View source code
public static void main(String[] args) throws Exception {
    InputConfiguration configuration = new InputConfiguration(args[0]);
    Factory factory = new SpoonMetaFactory().buildNewFactory(configuration.getProjectPath(), 5);
    InputProgram inputProgram = new InputProgram();
    inputProgram.setFactory(factory);
    inputProgram.configure(configuration);
    inputProgram.processCodeFragments();
    TransformationOldParser parser = new TransformationOldParser(false, inputProgram);
    List<Transformation> transf = parser.parseFile(new File(inputProgram.getPreviousTransformationsPath()));
    TransformationJsonParser.saveToFile(transf, configuration.getResultPath());
}
Example 4
Project: korsakow-editor-master  File: FileExternalSoundEncoder.java View source code
public void encode(SoundFormat srcFormat, File srcFile, File destFile) throws EncoderException, InterruptedException {
    Process process = null;
    try {
        process = createProcess(srcFormat, srcFile, destFile);
    } catch (IOException e) {
        throw new VideoEncoderException(e, srcFile);
    }
    encode(process, srcFile, destFile);
}
Example 5
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 6
Project: dk-master  File: FileFormatUtil.java View source code
/**
	 * 判断文件是否正确
	 * @param file 上传文件
	 * @param fileName 文件名称
	 * @return
	 * @throws Exception
	 */
public static String fileIsTrue(File file, String fileName) throws Exception {
    if (file == null) {
        return "请上传文件!";
    }
    if (!file.exists()) {
        return "文件不存在";
    }
    //从后面查找
    int lastIndex = fileName.lastIndexOf(".");
    String suffix = fileName.substring(//截取
    lastIndex + //截取
    1);
    if (!"XLS".equalsIgnoreCase(suffix)) {
        return "文件格式不正确";
    }
    return null;
}
Example 7
Project: securereader-master  File: EPubMediaContentPreviewView.java View source code
@Override
public void setMediaContent(MediaContent mediaContent, File mediaFile, java.io.File mediaFileNonVFS, boolean useThisThread) {
    mMediaContent = mediaContent;
    mMediaFile = mediaFileNonVFS;
    if (mMediaFile == null) {
        Log.v("EPubMediaContentPreviewView", "Failed to download media, no file.");
        return;
    }
}
Example 8
Project: erlide-master  File: MD5Checksum.java View source code
public static String getMD5(final File file) throws Exception {
    try (final FileInputStream f = new FileInputStream(file)) {
        final byte[] buffer = new byte[1024];
        final MessageDigest digest = MessageDigest.getInstance("MD5");
        int numRead;
        while ((numRead = f.read(buffer)) != -1) {
            digest.update(buffer, 0, numRead);
        }
        return new String(digest.digest());
    }
}
Example 9
Project: schach-master  File: ListReader.java View source code
public static ArrayList<String> loadStrings(File aFile) {
    ArrayList<String> pVec = new ArrayList<String>();
    if (!aFile.exists())
        return pVec;
    try {
        BufferedReader pReader = new BufferedReader(new FileReader(aFile));
        String pLine;
        while ((pLine = pReader.readLine()) != null) {
            pLine = pLine.trim();
            if (pLine.startsWith("#") || pLine.equals(""))
                continue;
            pVec.add(pLine);
        }
        pReader.close();
    } catch (IOException aE) {
        aE.printStackTrace();
    }
    return pVec;
}
Example 10
Project: osmdroid-master  File: FolderDeleter.java View source code
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
	 * @return <code>true</code> on success, <code>false</code> otherwise.
	 */
public static boolean deleteFolder(final File pFolder) {
    final File[] children = pFolder.listFiles();
    for (final File c : children) {
        if (c.isDirectory()) {
            if (!deleteFolder(c)) {
                System.err.println("Could not delete " + c.getAbsolutePath());
                return false;
            }
        } else {
            if (!c.delete()) {
                System.err.println("Could not delete " + c.getAbsolutePath());
                return false;
            }
        }
    }
    return pFolder.delete();
}
Example 11
Project: ilarkesto-master  File: AScmTool.java View source code
public AScmProject getProject(File projectDir) {
    if (!projectDir.exists())
        throw new RuntimeException("Project does not exist: " + projectDir.getPath());
    if (!isProjectDir(projectDir))
        throw new RuntimeException("Not a " + getName() + " project: " + projectDir.getPath());
    return createProject(projectDir);
}
Example 12
Project: fdroidclient-master  File: CleanCacheService21.java View source code
static void deleteIfOld(File file, long olderThan) {
    try {
        StructStat stat = Os.lstat(file.getAbsolutePath());
        if ((stat.st_atime * 1000L) < olderThan) {
            file.delete();
        }
    } catch (ErrnoException e) {
        e.printStackTrace();
    }
}
Example 13
Project: QEditor-master  File: TedFontActivity.java View source code
/**
	 * Set the result of this activity to open a file
	 * 
	 * @param file
	 *            the file to return
	 * @return if the result was set correctly
	 */
protected boolean setOpenResult(File file) {
    Intent result;
    if (!file.canRead()) {
        Crouton.showText(this, R.string.toast_file_cant_read, Style.ALERT);
        return false;
    }
    result = new Intent();
    result.setData(Uri.fromFile(file));
    setResult(RESULT_OK, result);
    return true;
}
Example 14
Project: MUtils-master  File: FileModifiedComparator.java View source code
@Override
public int compare(File lhs, File rhs) {
    long diff = lhs.lastModified() - rhs.lastModified();
    if (diff > 0) {
        return mOrder == Order.ASC ? 1 : -1;
    } else if (diff < 0) {
        return mOrder == Order.ASC ? -1 : 1;
    } else {
        return 0;
    }
}
Example 15
Project: openjdk-master  File: Abort.java View source code
public static void main(String... args) throws Exception {
    String SCRATCH_DIR = System.getProperty("user.dir");
    JavaCompiler javacTool = ToolProvider.getSystemJavaCompiler();
    java.io.File testDir = new java.io.File(SCRATCH_DIR);
    sourceA.dumpTo(testDir);
    sourceB.dumpTo(testDir);
    DiagnosticChecker diagChecker = new DiagnosticChecker();
    JavacTask ct = (JavacTask) javacTool.getTask(null, null, diagChecker, Arrays.asList("-XDrawDiagnostics", "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sourceA.asJFO(testDir)));
    try {
        ct.analyze();
    } catch (Throwable ex) {
    }
    if (!diagChecker.errorFound) {
        throw new AssertionError("Missing diagnostic");
    }
}
Example 16
Project: open-mika-master  File: TrustManagerFactoryImpl.java View source code
/**
     * @see javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore)
     */
@Override
public void engineInit(KeyStore ks) throws KeyStoreException {
    if (ks != null) {
        keyStore = ks;
    } else {
        // BEGIN android-added
        if (System.getProperty("javax.net.ssl.trustStore") == null) {
            String file = System.getProperty("java.home") + java.io.File.separator + "etc" + java.io.File.separator + "security" + java.io.File.separator + "cacerts.bks";
            System.setProperty("javax.net.ssl.trustStore", file);
        }
        // END android-added
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        String keyStoreName = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {

            public String run() {
                return System.getProperty("javax.net.ssl.trustStore");
            }
        });
        String keyStorePwd = null;
        if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") || keyStoreName.length() == 0) {
            try {
                keyStore.load(null, null);
            } catch (IOException e) {
                throw new KeyStoreException(e);
            } catch (CertificateException e) {
                throw new KeyStoreException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new KeyStoreException(e);
            }
        } else {
            keyStorePwd = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {

                public String run() {
                    return System.getProperty("javax.net.ssl.trustStorePassword");
                }
            });
            char[] pwd;
            if (keyStorePwd == null) {
                pwd = new char[0];
            } else {
                pwd = keyStorePwd.toCharArray();
            }
            try {
                keyStore.load(new FileInputStream(new File(keyStoreName)), pwd);
            } catch (FileNotFoundException e) {
                throw new KeyStoreException(e);
            } catch (IOException e) {
                throw new KeyStoreException(e);
            } catch (CertificateException e) {
                throw new KeyStoreException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new KeyStoreException(e);
            }
        }
    }
}
Example 17
Project: googleplaycrawler-master  File: FileResponse.java View source code
// get file as http response
private void getFileAsHttpResponse(java.io.File f) throws FileException, IOException {
    // ignore file of size larger than
    // Integer.MAX_VALUE = 2^31-1 = 2147483647
    long size = f.length();
    if (size > Integer.MAX_VALUE) {
        throw new FileException("file is too large, size: " + size);
    // or we can do this?
    // this.code = 400; // http Bad request
    // return;
    }
    // capture content
    int len = (int) size;
    if (this.file.maxContentLength >= 0 && len > this.file.maxContentLength)
        len = this.file.maxContentLength;
    this.content = new byte[len];
    java.io.InputStream is = new java.io.FileInputStream(f);
    int offset = 0;
    int n = 0;
    while (offset < len && (n = is.read(this.content, offset, len - offset)) >= 0) {
        offset += n;
    }
    if (offset < len) {
        // keep whatever already have, but issue a warning
        if (File.LOG.isWarnEnabled()) {
            File.LOG.warn("not enough bytes read from file: " + f.getPath());
        }
    }
    is.close();
    // set headers
    headers.set(Response.CONTENT_LENGTH, new Long(size).toString());
    headers.set(Response.LAST_MODIFIED, HttpDateFormat.toString(f.lastModified()));
    String mimeType = MIME.getMimeType(f);
    headers.set(Response.CONTENT_TYPE, mimeType != null ? mimeType : "");
    // response code
    // http OK
    this.code = 200;
}
Example 18
Project: jease-master  File: Transit.java View source code
public java.io.File getFile() {
    if (uri != null) {
        java.io.File file = new java.io.File(URI.create(uri));
        try {
            if (!file.exists()) {
                try {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        } catch (RuntimeException e) {
            return null;
        }
        return file;
    } else {
        return null;
    }
}
Example 19
Project: Strata-master  File: MarketDataRootValidator.java View source code
@Override
public void validate(String name, File value) throws ParameterException {
    if (!value.exists()) {
        throw new ParameterException(Messages.format("Invalid market data root directory: {}", value.getAbsolutePath()));
    }
    if (!value.isDirectory()) {
        throw new ParameterException(Messages.format("Market data root must be a directory: {}", value.getAbsolutePath()));
    }
}
Example 20
Project: molgenis-master  File: JarRunnerImpl.java View source code
@Override
public File runJar(String outputFile, List<String> params, File inputVcf) throws IOException, InterruptedException {
    File outputVcf = File.createTempFile(outputFile, ".vcf");
    List<String> command = new ArrayList<>();
    command.add("java");
    command.add("-jar");
    command.addAll(params);
    command.add(inputVcf.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectOutput(outputVcf);
    // Error logging to standard logging.
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process p = pb.start();
    p.waitFor();
    return outputVcf;
}
Example 21
Project: dtangler-master  File: FileNameExtensionFilter.java View source code
public boolean accept(File f) {
    if (f.isDirectory()) {
        return true;
    }
    String name = f.getName().toLowerCase();
    for (int i = fileNameExtensions.length - 1; i >= 0; i--) {
        if (name.endsWith(fileNameExtensions[i])) {
            return true;
        }
    }
    return false;
}
Example 22
Project: bixie-master  File: MainClassTest.java View source code
@Test
public void test() {
    final File source_file = new File(testRoot + "ic_java/true_positives/TruePositives02.java");
    File classFileDir = null;
    try {
        classFileDir = compileJavaFile(source_file);
        Bixie.main(new String[] { "-j", classFileDir.getAbsolutePath(), "-logProver", "test" });
    } catch (IOException e) {
        e.printStackTrace();
        fail("Not yet implemented");
    } finally {
        if (classFileDir != null) {
            try {
                delete(classFileDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 23
Project: JPaxos-master  File: DirectoryHelper.java View source code
private static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    // The directory is now empty so delete it
    return dir.delete();
}
Example 24
Project: ISAcreator-master  File: ConfigurationLoadTest.java View source code
@Test
public void configurationTestLoad() {
    System.out.println("_____TESTING configurationTestLoad()");
    File configurationDirectory = new File("Configurations");
    if (configurationDirectory.exists() && configurationDirectory.isDirectory()) {
        File[] configurationFiles = configurationDirectory.listFiles();
        assert configurationFiles != null;
        for (File file : configurationFiles) {
            if (!file.isHidden() && !file.getName().startsWith(".")) {
                ConfigXMLParser parser = new ConfigXMLParser(ConfigurationLoadingSource.ISACREATOR, file.getAbsolutePath());
                System.out.println("___loading configuration " + file.getName().toLowerCase());
                parser.loadConfiguration();
                assertTrue("Oh, the configuration size is 0!", parser.getTables().size() > 0);
                System.out.println("Configuration " + file.getName().toLowerCase() + " loaded successfully");
            }
        }
    }
}
Example 25
Project: traffic-balance-master  File: Simulator.java View source code
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("required args: <service url> <input file>");
        System.exit(-1);
    }
    String url = args[0];
    File inputFile = new File(args[1]);
    if (!inputFile.exists()) {
        throw new FileNotFoundException(args[1]);
    }
    LocationDataSender sender = new LocationDataSender(url, new Date());
    parser = new FileParser(inputFile, sender);
    parser.start();
    System.out.println("sending rate: " + sender.getSendingRate() + ", total vehicles: " + sender.getTotalCars());
    System.out.println("maximum single request time: " + sender.getMaxRequestTime() + " ms");
}
Example 26
Project: sonar-java-master  File: ThreadSleepCall.java View source code
public void echoFile(PrintStream ps, File f) throws IOException, InterruptedException {
    BufferedReader br = new BufferedReader(new FileReader(f));
    try {
        while (okToPrint) {
            Thread.sleep(1000);
            ps.println(br.readLine());
        }
    } catch (IOException ex) {
        if (okToPrint) {
            throw new RuntimeException("Couldn't read a line", ex);
        }
        throw new RuntimeException("Got an error, but it's not OK to print", ex);
    }
}
Example 27
Project: node-go-better-than-random-master  File: GameFileFilter.java View source code
/** Accept function.
        @param file The file to check.
        @return true if file has extension .sgf or .SGF or is a directory */
public boolean accept(File file) {
    if (file.isDirectory())
        return true;
    return (FileUtil.hasExtension(file, "sgf") || FileUtil.hasExtension(file, "SGF") || FileUtil.hasExtension(file, "xml") || FileUtil.hasExtension(file, "XML"));
}
Example 28
Project: platform_tools_adt_idea-master  File: SafeSignedJarBuilder.java View source code
@Override
public void writeFile(File inputFile, String jarPath) throws IOException {
    if (FileUtil.pathsEqual(inputFile.getPath(), myOutFilePath)) {
        throw new IOException("Cannot pack file " + myOutFilePath + " into itself");
    }
    super.writeFile(inputFile, jarPath);
}
Example 29
Project: milton2-master  File: TransferableResourceList.java View source code
public synchronized Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
    System.out.println("getTransferData: " + flavor);
    if (flavor == RESOURCE_LIST_FLAVOR) {
        return this;
    //    } else if (flavor.equals(DataFlavor.javaFileListFlavor)) {
    //      java.util.List data = new java.util.ArrayList();
    //      java.io.File file = new java.io.File("/home/j2ee/Desktop/beergroup");
    //      data.add(file);
    //      return data;
    //    } else if (flavor.equals(uriListFlavor)) {
    //      java.io.File file = new java.io.File("/home/j2ee/Desktop/beergroup");
    //      // refer to RFC 2483 for the text/uri-list format
    //      String data = file.toURI() + "\r\n";
    //      System.out.println("returning files list: " + data);
    //      return data;
    } else {
        throw new UnsupportedFlavorException(flavor);
    }
}
Example 30
Project: picard-tools-master  File: FastqWriterFactory.java View source code
public FastqWriter newWriter(final File out) {
    final FastqWriter writer = new BasicFastqWriter(out, createMd5);
    if (useAsyncIo) {
        return new AsyncFastqWriter(writer, AsyncFastqWriter.DEFAULT_QUEUE_SIZE);
    } else {
        return writer;
    }
}
Example 31
Project: blogracy-master  File: Magnet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String hash = request.getParameter("hash");
    final String CACHE_FOLDER = Configurations.getPathConfig().getCachedFilesDirectoryPath();
    File file = new File(CACHE_FOLDER + File.separator + hash);
    if (file.exists()) {
        // response.sendRedirect("/cache/" + hash);
        // TODO! ...
        response.setContentType("video/mp4");
        request.getRequestDispatcher("/cache/" + hash).forward(request, response);
    } else {
        int dot = hash.lastIndexOf(".");
        if (dot >= 0) {
            hash = hash.substring(0, dot);
        }
        FileSharing.getSingleton().downloadByHash(hash);
        response.sendError(503);
    }
}
Example 32
Project: tern.java-master  File: Start.java View source code
static List<String> createCommands(File nodejsTernFile, Integer port) throws IOException {
    List<String> commands = new LinkedList<String>();
    commands.add("node");
    commands.add(nodejsTernFile.getCanonicalPath());
    if (port != null) {
        commands.add("--port");
        commands.add(port.toString());
    }
    return commands;
}
Example 33
Project: codemap-master  File: Dat3.java View source code
public static void main(String... args) throws FileNotFoundException {
    Svdlib svdlib = new Svdlib();
    SMat A = Svdlib.svdLoadSparseTextHBFile(new File("lib/dat3.txt"));
    int dimensions = Math.min(A.cols, A.rows);
    int iterations = 100;
    double[] end = new double[] { -1e-30, 1e-30 };
    double kappa = 1e-6;
    long time = System.currentTimeMillis();
    SVDRec R = svdlib.svdLAS2(A, dimensions, iterations, end, kappa);
    System.out.println("-----------" + (System.currentTimeMillis() - time));
    for (int n = 0; n < R.d; n++) {
        System.out.println(R.S[n]);
    }
}
Example 34
Project: virgo.kernel-master  File: TestUtils.java View source code
public static boolean deleteRecursively(File root) {
    if (root.exists()) {
        if (root.isDirectory()) {
            File[] children = root.listFiles();
            if (children == null) {
                throw new IllegalStateException("Failed to list files in '" + root + "'.");
            }
            for (File file : children) {
                deleteRecursively(file);
            }
        }
        return root.delete();
    }
    return false;
}
Example 35
Project: schemacrawler-master  File: TestSqliteDistribution.java View source code
@Test
public void testSqliteMain() throws Exception {
    final OutputFormat outputFormat = OutputFormat.text;
    final String referenceFile = "sqlite.main" + "." + outputFormat.name();
    final File testOutputFile = File.createTempFile("schemacrawler." + referenceFile + ".", ".test");
    testOutputFile.delete();
    final File sqliteDbFile = copyResourceToTempFile("/sc.db");
    schemacrawler.tools.sqlite.Main.main(new String[] { "-database=" + sqliteDbFile.getAbsolutePath(), "-command=details,dump,count", "-infolevel=detailed", "-outputfile=" + testOutputFile });
    final List<String> failures = compareOutput(referenceFile, testOutputFile, outputFormat.name());
    if (failures.size() > 0) {
        fail(failures.toString());
    }
}
Example 36
Project: many-ql-master  File: FileFilter.java View source code
@Override
public boolean accept(File path) {
    if (path.isDirectory()) {
        return true;
    }
    String extension = getExtension(path);
    if (extension != null) {
        if (extension.equals(filterExtension)) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}
Example 37
Project: TFC2-master  File: JSONReader.java View source code
public boolean read(File file) {
    try {
        Gson gson = new Gson();
        InputStream stream;
        if (file == null)
            stream = this.getClass().getResourceAsStream(path);
        else if (file.exists()) {
            stream = Files.asByteSource(file).openStream();
        } else {
            return false;
        }
        InputStreamReader sr = new InputStreamReader(stream);
        JsonReader reader = new JsonReader(sr);
        process(reader);
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return true;
}
Example 38
Project: Katari-master  File: KatariWicketTesterTest.java View source code
@Test
public void dumpResultTest() throws Exception {
    ApplicationContextMock appctx = new ApplicationContextMock();
    KatariWicketTester app = new KatariWicketTester(appctx);
    app.startPage(new WicketTestPage());
    app.clickLink("users:1:delete");
    app.assertRenderedPage(WicketTestPage.class);
    String fileName = "target/wicket-test/" + KatariWicketTesterTest.class.getName() + ".dumpResultTest." + WicketTestPage.class.getName() + ".html";
    File output = new File(fileName);
    assertTrue("The file " + fileName + " was not found.", output.exists());
}
Example 39
Project: usergrid-master  File: EmbeddedServerHelper.java View source code
/** Copies a resource from within the jar to a directory. */
private static void copy(String resource, String directory) throws java.io.IOException {
    mkdir(directory);
    java.io.InputStream is = EmbeddedServerHelper.class.getResourceAsStream(resource);
    String fileName = resource.substring(resource.lastIndexOf("/") + 1);
    java.io.File file = new java.io.File(directory + System.getProperty("file.separator") + fileName);
    java.io.OutputStream out = new java.io.FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    while ((len = is.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    out.close();
    is.close();
}
Example 40
Project: my-ministry-assistant-master  File: DailyBackupService.java View source code
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    File intDB = getApplicationContext().getDatabasePath(MinistryDatabase.DATABASE_NAME);
    File extDB = FileUtils.getExternalDBFile(getApplicationContext(), "auto-daily.db");
    try {
        if (extDB != null) {
            if (!extDB.exists())
                extDB.createNewFile();
            FileUtils.copyFile(intDB, extDB);
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Error during daily backup", Toast.LENGTH_LONG).show();
    }
    return Service.START_NOT_STICKY;
}
Example 41
Project: GATECH-master  File: ObjLoader.java View source code
public static List<Vector3f> importObj(final File objFile) throws FileNotFoundException {
    Scanner objScanner = new Scanner(objFile);
    List<Vector3f> vertices = new LinkedList<Vector3f>();
    while (objScanner.hasNextLine()) {
        String line = objScanner.nextLine().trim();
        if (line.startsWith("v ")) {
            String vS[] = line.substring(2).trim().split(" ");
            vertices.add(new Vector3f(Float.parseFloat(vS[0]), Float.parseFloat(vS[1]), Float.parseFloat(vS[2])));
        }
    }
    return vertices;
}
Example 42
Project: RapidBeans-master  File: ConfigApplicationTest.java View source code
/**
	 * load a test configuration.
	 */
public void testLoadConfiguration() {
    Document doc = new Document(new File("../org.rapidbeans/testdata/rapidclubadmin/config/Client.xml"));
    ConfigApplication configRoot = (ConfigApplication) doc.getRoot();
    ConfigDocument doccfg = configRoot.getDocuments().iterator().next();
    assertEquals("billingperiod", doccfg.getName());
    ConfigView stdViewcfg = doccfg.getViews().iterator().next();
    assertEquals("trainings", stdViewcfg.getName());
    List<ConfigEditorBean> edCfgs = (List<ConfigEditorBean>) configRoot.getBeaneditors();
    ConfigEditorBean edTrainer = edCfgs.get(4);
    assertNull(edTrainer.getEditorclass());
    assertEquals("org.rapidbeans.clubadmin.domain.Trainer", edTrainer.getBeantype());
}
Example 43
Project: org.openntf.domino-master  File: OnDiskProject.java View source code
public void export(final org.openntf.domino.design.DesignBase elem_) throws IOException {
    //elem.getDxlString(null)
    AbstractDesignBase elem = (AbstractDesignBase) elem_;
    String odp = elem.getOnDiskPath();
    if (StringUtil.isEmpty(odp)) {
        odp = elem.getNoteID() + ".note";
    }
    //elem.getLastModified();
    File odsFile = new File(root_, odp);
    System.out.println(elem.getClass().getName() + "\t\t\t" + odsFile + "\t" + elem.getNoteID());
    // ensure the path exists
    odsFile.getParentFile().mkdirs();
    elem.writeOnDiskFile(odsFile);
    if (elem instanceof HasMetadata) {
        File meta = new File(odsFile.getAbsolutePath() + ".metadata");
        ((HasMetadata) elem).writeOnDiskMeta(meta);
    }
}
Example 44
Project: nmonvisualizer-master  File: FileHelper.java View source code
public static void recurseDirectories(File[] files, FileFilter filter, List<String> filenames) {
    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            recurseDirectories(files[i].listFiles(), filter, filenames);
        } else {
            if (filter.accept(files[i])) {
                filenames.add(files[i].getAbsolutePath());
            }
        }
    }
}
Example 45
Project: SimplePortables-master  File: Config.java View source code
public static void init(File file) {
    Configuration config = new Configuration(file);
    try {
        config.load();
        CommonProxy.portableItemID = config.get(Configuration.CATEGORY_GENERAL, "Portable", 15500).getInt();
        CommonProxy.portableBlockID = config.get(Configuration.CATEGORY_GENERAL, "Remote Block", 15501).getInt();
        CommonProxy.componentsID = config.get(Configuration.CATEGORY_GENERAL, "Crafting Components", 15502).getInt();
        CommonProxy.lockID = config.get(Configuration.CATEGORY_GENERAL, "Lock", 15503).getInt();
        PortableItem.durability = config.get(Configuration.CATEGORY_GENERAL, "Portable Durability", 300).getInt();
        PortableBlock.durability = config.get(Configuration.CATEGORY_GENERAL, "Remote Block Durability", 10).getInt();
    } catch (Exception e) {
    } finally {
        config.save();
    }
}
Example 46
Project: airlift-master  File: TestTempFile.java View source code
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
@Test
public void testTempFile() throws Exception {
    TempFile tempFile = new TempFile();
    File file = tempFile.file();
    assertEquals(file, tempFile.path().toFile());
    assertTrue(file.exists());
    assertTrue(file.isFile());
    assertTrue(file.canRead());
    assertTrue(file.canWrite());
    tempFile.close();
    assertFalse(file.exists());
    // verify close does not delete file again
    assertTrue(file.createNewFile());
    assertTrue(file.exists());
    tempFile.close();
    assertTrue(file.exists());
    assertTrue(file.delete());
}
Example 47
Project: FireflowEngine20-master  File: CleanCode.java View source code
public void visit(File file) {
    if (file.isDirectory())
        return;
    if (!file.getName().endsWith(".java"))
        return;
    String str = Files.read(file);
    if (!str.contains("\t"))
        return;
    str = str.replaceAll("\t", "    ");
    Files.write(file, str);
    re[0]++;
}
Example 48
Project: Jorum-DSpace-master  File: JettyWebAppLoader.java View source code
public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        usage();
    }
    try {
        Server server = new Server();
        XmlConfiguration configuration = new XmlConfiguration(new File(args[0]).toURL());
        configuration.configure(server);
        server.start();
        JettyStopListener monitor = new JettyStopListener(Integer.parseInt(args[1]), args[2], server, true);
        monitor.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Example 49
Project: compomics-utilities-master  File: Ms2FileFilter.java View source code
/**
     * Accept all directories, *.ms2 files.
     *
     * @param f the file
     * @return true if the file passes the filter
     */
public boolean accept(File f) {
    if (f.isDirectory()) {
        return true;
    }
    String extension = FileFilterUtils.getExtension(f);
    if (extension != null) {
        if (extension.equals(FileFilterUtils.ms2) || extension.equals(FileFilterUtils.MS2)) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}
Example 50
Project: android-simple-storage-master  File: OrderType.java View source code
public Comparator<File> getComparator() {
    switch(ordinal()) {
        case // name
        0:
            return new Comparator<File>() {

                @Override
                public int compare(File lhs, File rhs) {
                    return lhs.getName().compareTo(rhs.getName());
                }
            };
        case // date
        1:
            return new Comparator<File>() {

                @Override
                public int compare(File lhs, File rhs) {
                    return (int) (rhs.lastModified() - lhs.lastModified());
                }
            };
        case // size
        2:
            return new Comparator<File>() {

                @Override
                public int compare(File lhs, File rhs) {
                    return (int) (lhs.length() - rhs.length());
                }
            };
        default:
            break;
    }
    return null;
}
Example 51
Project: FallUML2013-master  File: SequencePngFile.java View source code
public static void createPngFile(String pFileName, String pInFileName, String pFileDir, String pLibPath) {
    try {
        final String umlPicutilPath = "D:\\GnuWin32\\bin\\pic2plot.exe";
        //logging.Log.LogCreate().Info("pFileName =" + pFileName + " pInFileName=" + pInFileName + " pFileDir= " + pFileDir + " pLibPath = " + pLibPath);
        logging.Log.LogCreate().Info(umlPicutilPath);
        Path srcSeqPicFile = new java.io.File(pLibPath + "sequence.pic").toPath();
        Path dstSeqPicFile = new java.io.File(pFileDir + "sequence.pic").toPath();
        Path temp = java.nio.file.Files.copy(srcSeqPicFile, dstSeqPicFile, REPLACE_EXISTING);
        logging.Log.LogCreate().Info(temp.toString());
        String picFileName = pFileDir + pInFileName;
        String pngFileName = pFileDir + pFileName + ".png";
        logging.Log.LogCreate().Info(picFileName);
        logging.Log.LogCreate().Info(pngFileName);
        // Command to generate PNG file from pic file
        FileWriter fw = null;
        try {
            fw = new FileWriter("C:\\test.bat");
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(umlPicutilPath + " -Tpng --bitmap-size 1000x1000 " + picFileName + ">" + pngFileName + "\n" + "EXIT");
        bw.close();
        fw.close();
        String command[] = new String[] { "cmd", "/k", "start", "C:\\test.bat" };
        try {
            //Process procObj = Runtime.getRuntime().exec(command);
            Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            e.printStackTrace();
            Log.LogCreate().Info("Error 2: generating png file failed .." + e.getMessage());
        }
    } catch (Exception e) {
        Log.LogCreate().Info("Error in creating the png file............." + e.getMessage());
    }
}