javatips.net counter

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: Builder.java View source code
/** Initialize Builder. Sub-classes should invoke [email protected] super.start} at the begin of this method. */
@PostConstruct
public void start() {
    if (started.compareAndSet(false, true)) {
        repository = new java.io.File(rootDirectory, getName());
        if (!(repository.exists() || repository.mkdirs())) {
            throw new IllegalStateException(String.format("Unable create directory %s", repository.getAbsolutePath()));
        }
        final java.io.File sources = new java.io.File(repository, "sources");
        if (!(sources.exists() || sources.mkdirs())) {
            throw new IllegalStateException(String.format("Unable create directory %s", sources.getAbsolutePath()));
        }
        builds = new java.io.File(repository, "builds");
        if (!(builds.exists() || builds.mkdirs())) {
            throw new IllegalStateException(String.format("Unable create directory %s", builds.getAbsolutePath()));
        }
        // TODO: use single instance of SourceManager
        sourcesManager = new SourcesManagerImpl(sources);
        // TODO: guice must do this
        sourcesManager.start();
        executor = new MyThreadPoolExecutor(numberOfWorkers <= 0 ? Runtime.getRuntime().availableProcessors() : numberOfWorkers, queueSize);
        scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat(getName() + "-BuilderSchedulerPool-").setDaemon(true).build());
        scheduler.scheduleAtFixedRate(new Runnable() {

            public void run() {
                int num = 0;
                for (Iterator<FutureBuildTask> i = tasks.values().iterator(); i.hasNext(); ) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }
                    final FutureBuildTask task = i.next();
                    if (task.isExpired()) {
                        i.remove();
                        try {
                            cleanup(task);
                        } catch (RuntimeException e) {
                            LOG.error(e.getMessage(), e);
                        }
                        num++;
                    }
                }
                if (num > 0) {
                    LOG.debug("Remove {} expired tasks", num);
                }
            }
        }, 1, 1, TimeUnit.MINUTES);
    } else {
        throw new IllegalStateException("Already started");
    }
}
Example 2
Project: checkstyle-master  File: AvoidStarImportCheckTest.java View source code
@Test
public void testDefaultOperation() throws Exception {
    final DefaultConfiguration checkConfig = createCheckConfig(AvoidStarImportCheck.class);
    final String[] expected = { "7: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports.*"), "9: " + getCheckMessage(MSG_KEY, "java.io.*"), "10: " + getCheckMessage(MSG_KEY, "java.lang.*"), "25: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "26: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "28: " + getCheckMessage(MSG_KEY, "java.io.File.*") };
    verify(checkConfig, getPath("InputAvoidStarImport.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: ExportInterchangeInterfaceCommand.java View source code
public void execute() throws CommandException {
    try {
        long interfaceId = request.getLong("interface_id");
        String filename = request.getString("filename");
        IInterface interf = InterfaceInputMapper.map(interfaceId);
        Document document = DataRegistry.createDefaultEmptyDocument();
        InterchangeInterfaceOutputMapper interfaceOutputMapper = OutputMapperFactory.createInterfaceOutputMapper(document);
        Element interfaceElement = interfaceOutputMapper.output(interf);
        document.getDocumentElement().appendChild(interfaceElement);
        DomUtil.writeDomXML(document, new File(filename));
    } catch (Exception e) {
        throw new CommandException(e);
    }
}
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: ClearAllCachesAction.java View source code
public static void clearAllCaches() {
    final String cacheFileOSPath = ErlangEngine.getInstance().getStateDir();
    final File cacheFile = new File(cacheFileOSPath);
    cacheFile.delete();
    for (final IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
        for (final IWorkbenchPage page : window.getPages()) {
            for (final IEditorReference editor : page.getEditorReferences()) {
                final IEditorPart ed = editor.getEditor(false);
                if (ed instanceof ErlangEditor) {
                    ((ErlangEditor) ed).resetAndCacheScannerAndParser();
                }
            }
        }
    }
}
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: MkProject.java View source code
public static void main(String[] args) {
    if (args.length != 1)
        throw new RuntimeException("A project name must be specified as parameter.");
    String name = args[0];
    File dir = new File(name);
    mkdir(name);
    mkdir(name + "/tags");
    mkdir(name + "/branches");
    String trunkPath = name + "/trunk";
    mkdir(trunkPath);
    mkdir(trunkPath + "/src/main/java");
    mkdir(trunkPath + "/src/main/resources");
    mkdir(trunkPath + "/src/test/java");
    mkdir(trunkPath + "/src/test/resources");
    mkdir(trunkPath + "/target/classes");
    mkdir(trunkPath + "/target/test-classes");
}
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: TedSaveAsActivity.java View source code
/**
	 * Sets the result data when the user presses save
	 * 
	 * @return if the result is OK (if not, it means the user must change its
	 *         selection / input)
	 */
@SuppressWarnings("deprecation")
protected boolean setSaveResult() {
    Intent result;
    String fileName;
    if ((mCurrentFolder == null) || (!mCurrentFolder.exists())) {
        showToast(this, R.string.toast_folder_doesnt_exist, true);
        return false;
    }
    if (!mCurrentFolder.canWrite()) {
        showToast(this, R.string.toast_folder_cant_write, true);
        return false;
    }
    fileName = mFileName.getText().toString();
    if (fileName.length() == 0) {
        showToast(this, R.string.toast_filename_empty, true);
        return false;
    }
    result = new Intent();
    result.putExtra("path", mCurrentFolder.getAbsolutePath() + File.separator + fileName);
    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: ReportTemplateParameterConverter.java View source code
@Override
public ReportTemplate convert(String fileName) {
    try {
        File file = new File(fileName);
        CharSource charSource = ResourceLocator.ofFile(file).getCharSource();
        IniFile ini = IniFile.of(charSource);
        return ReportTemplate.load(ini);
    } catch (RuntimeException ex) {
        if (ex.getCause() instanceof FileNotFoundException) {
            throw new ParameterException(Messages.format("File not found: {}", fileName));
        }
        throw new ParameterException(Messages.format("Invalid report template file: {}" + System.lineSeparator() + "Exception: {}", fileName, ex.getMessage()));
    }
}
Example 20
Project: molgenis-master  File: ScriptTest.java View source code
@Test
public void generateScript() throws IOException {
    FileStore fileStore = new FileStore(System.getProperty("java.io.tmpdir"));
    Map<String, Object> parameterValues = Collections.singletonMap("name", "Piet");
    Script script = mock(Script.class);
    when(script.getContent()).thenReturn("Hey ${name}");
    when(script.generateScript(fileStore, "txt", parameterValues)).thenCallRealMethod();
    File f = script.generateScript(fileStore, "txt", parameterValues);
    assertNotNull(f);
    assertTrue(f.exists());
    assertTrue(f.getPath().endsWith(".txt"));
    String s = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(f)));
    assertEquals("Hey Piet", s);
    f.delete();
}
Example 21
Project: dtangler-master  File: ArgumentBuilder.java View source code
public Arguments build(String[] cmdLineArgs) {
    Map<String, String> values = new CommandLineParser(ParserConstants.VALID_KEYS).parseValues(cmdLineArgs);
    ArgumentParser parser = new ArgumentParser();
    // if config file was given, read it first
    if (values.containsKey(ParserConstants.CONFIG_FILE_KEY)) {
        File configFile = new File(values.get(ParserConstants.CONFIG_FILE_KEY));
        Map<String, String> configFileValues = new ConfigFileParser(configFile, ParserConstants.VALID_KEYS).parseValues();
        parser.parseArguments(configFileValues);
    }
    return parser.parseArguments(values);
}
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: FileCreateTempFileCheck_no_version.java View source code
private void noncompliant() throws IOException {
    File tempDir;
    tempDir = (File.createTempFile("", "."));
    tempDir.delete();
    // Noncompliant [[sc=13;ec=18]] {{Use "Files.createTempDirectory" or a library function to create this directory instead. (sonar.java.source not set. Assuming 7 or greater.)}}
    tempDir.mkdir();
    File tempDir2 = File.createTempFile("", ".");
    tempDir2.delete();
    // Noncompliant
    tempDir2.mkdir();
    // issue already raised
    tempDir2.mkdir();
    b = File.createTempFile("", ".");
    b.delete();
    A a = new A() {

        private void noncompliant() throws IOException {
            b = File.createTempFile("", ".");
            b.delete();
            // Noncompliant
            b.mkdir();
        }
    };
    // Noncompliant
    b.mkdir();
    // issue already raised
    b.mkdir();
}
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: AndroidConversionTest.java View source code
public void testConvert() throws IOException {
    final String testDataPath = AndroidTestCase.getTestDataPath() + "/conversion/proguardOptions";
    final File testData = new File(testDataPath, "before");
    final File tempDir = FileUtil.createTempDirectory("project", null);
    FileUtil.copyDir(testData, tempDir);
    ProjectConversionTestUtil.convert(tempDir.getAbsolutePath());
    final File expectedDataDir = new File(testDataPath, "after");
    PlatformTestUtil.assertDirectoriesEqual(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(expectedDataDir), LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDir), new VirtualFileFilter() {

        @Override
        public boolean accept(VirtualFile file) {
            return !file.getName().startsWith(ProjectConversionUtil.PROJECT_FILES_BACKUP);
        }
    });
}
Example 29
Project: milton2-master  File: UploadTask.java View source code
@Override
protected Object doInBackground() throws Exception {
    System.out.println("doInBackground");
    int numFiles = files.length;
    int currentFile = 1;
    for (java.io.File f : files) {
        System.out.println("Upload::" + f.getName());
        if (f.getName().startsWith(".") || f.getParentFile().getName().startsWith(".")) {
            System.out.println("not uploading: " + f.getName());
        } else {
            try {
                folder.upload(f, this, new Throttle() {

                    public void onRead(int len) {
                    }
                });
                currentFile++;
            } catch (Throwable e) {
                e.printStackTrace();
                String msg = "Failed to upload: " + f.getAbsolutePath() + ". Error: " + e.getMessage();
                if (currentFile >= numFiles) {
                    JOptionPane.showMessageDialog(parent, msg, "Upload Failed", JOptionPane.WARNING_MESSAGE);
                } else {
                    int res = JOptionPane.showConfirmDialog(parent, msg + ". Would you like to continue?", "Upload failed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (res != JOptionPane.YES_OPTION) {
                        return null;
                    }
                }
            }
        }
    }
    App.current().view.status("Completed uploading file(s)");
    return null;
}
Example 30
Project: picard-tools-master  File: SamFiles.java View source code
/**
     * Finds the index file associated with the provided SAM file.  The index file must exist and be reachable to be found. 
     *
     * @return The index for the provided SAM, or null if one was not found.
     */
public static File findIndex(final File samFile) {
    // If input is foo.bam, look for foo.bai
    File indexFile;
    final String fileName = samFile.getName();
    if (fileName.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) {
        final String bai = fileName.substring(0, fileName.length() - BamFileIoUtils.BAM_FILE_EXTENSION.length()) + BAMIndex.BAMIndexSuffix;
        indexFile = new File(samFile.getParent(), bai);
        if (indexFile.isFile()) {
            return indexFile;
        }
    }
    // If foo.bai doesn't exist look for foo.bam.bai
    indexFile = new File(samFile.getParent(), samFile.getName() + BAMIndex.BAMIndexSuffix);
    if (indexFile.isFile()) {
        return indexFile;
    } else {
        return null;
    }
}
Example 31
Project: blogracy-master  File: FileUpload.java View source code
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    File attachment = (File) req.getAttribute("userfile");
    String text = req.getParameter("usertext").trim();
    FileSharing sharing = FileSharing.getSingleton();
    // String id = sharing.hash("mic");
    String id = Configurations.getUserConfig().getUser().getHash().toString();
    // TODO recipient of message/files? the publishing user or the profile's
    // user?
    // String dest = req.getParameter("user");
    ActivitiesController activities = ActivitiesController.getSingleton();
    activities.addFeedEntry(id, text, attachment);
    PrintWriter outp = resp.getWriter();
    outp.write("<html>");
    outp.write("<head><title>FileUpload page</title></head>");
    outp.write("<body>");
    outp.write("<h2>" + text + "</h2>");
    outp.write("</body>");
    outp.write("</html>");
}
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: CurrentDirJava.java View source code
public static void main(String[] args) throws FileNotFoundException {
    TermDocumentMatrix tdm = new TermDocumentMatrix();
    CorpusBuilderHelper importer = new CorpusBuilderHelper(tdm);
    importer.importAllFiles(new File("../ch.deif.meander"), ".java");
    importer.importAllFiles(new File("."), ".java");
    Out.puts(tdm);
    Out.puts(Get.head(tdm.documents()));
    Out.puts(tdm.getDocument(Get.head(tdm.documents())));
    Out.puts(tdm);
    Out.puts(tdm.density());
    tdm = tdm.rejectAndWeight();
    Out.puts(tdm);
    Out.puts(tdm.density());
    Out.puts(tdm.terms().sortedCounts());
    LatentSemanticIndex lsi = tdm.createIndex();
    Out.puts(first(10, lsi.rankDocumentsByTerm("bag")));
    Out.puts(first(10, lsi.rankTermsByTerm("bag")));
    Out.puts(first(10, lsi.rankDocumentsByTerm("codemap")));
    Out.puts(first(10, lsi.rankDocumentsByQuery("split string by lower- and upper-case")));
}
Example 34
Project: virgo.kernel-master  File: TestOutputComparator.java View source code
public static void assertOutputEquals(File expectedFile, List<String> experimental) {
    BufferedReader in = null;
    Iterator<String> it = experimental.iterator();
    try {
        in = new BufferedReader(new FileReader(expectedFile));
        String line;
        while ((line = in.readLine()) != null) {
            assertEquals(line, it.next());
        }
    } catch (FileNotFoundException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        IOUtils.closeQuietly(in);
    }
}
Example 35
Project: schemacrawler-master  File: TestBundledDistributions.java View source code
@Test
public void testHsqldbMain() throws Exception {
    final OutputFormat outputFormat = OutputFormat.text;
    final String referenceFile = "hsqldb.main" + "." + outputFormat.name();
    final File testOutputFile = File.createTempFile("schemacrawler." + referenceFile + ".", ".test");
    testOutputFile.delete();
    schemacrawler.tools.hsqldb.Main.main(new String[] { "-database=schemacrawler", "-user=sa", "-password=", "-command=details,dump,count", "-infolevel=standard", "-outputfile=" + testOutputFile });
    final List<String> failures = TestUtility.compareOutput(referenceFile, testOutputFile, outputFormat);
    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: SettingsBasic.java View source code
// BEGIN manual code section
// SettingsBasic.classBody
/**
	 * init the basic settings for all constructors.
	 */
private void init() {
    final File settingsFolder = new File(SettingsAll.getDirname());
    if (!settingsFolder.exists()) {
        FileHelper.mkdirs(settingsFolder);
    }
    final Application app = ApplicationManager.getApplication();
    if (app != null) {
        if (app.getConfiguration().getGuitype() == ApplicationGuiType.swing) {
            this.setGui(new SettingsBasicGuiSwing());
        } else {
            this.setGui(new SettingsBasicGui());
        }
    } else {
        this.setGui(new SettingsBasicGui());
    }
}
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());
    }
}
Example 52
Project: records-management-master  File: ContentCleanser522022M.java View source code
/**
     * @see org.alfresco.module.org_alfresco_module_rm.content.cleanser.ContentCleanser#cleanse(java.io.File)
     */
@Override
public void cleanse(File file) {
    // Double check
    if (!file.exists() || !file.canWrite()) {
        throw new ContentIOException("Unable to write to file: " + file);
    }
    // Overwite file
    overwrite(file, overwriteOnes);
    overwrite(file, overwriteZeros);
    overwrite(file, overwriteRandom);
}
Example 53
Project: researchzilla-master  File: PicCrop.java View source code
public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ImageInputStream imageInputStream = null;
    try {
        fileInputStream = new FileInputStream("/home/yumingzhe/a.jpg");
        Iterator iterator = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader imageReader = (ImageReader) iterator.next();
        imageInputStream = ImageIO.createImageInputStream(fileInputStream);
        imageReader.setInput(imageInputStream, true);
        ImageReadParam param = imageReader.getDefaultReadParam();
        Rectangle rect = new Rectangle(0, 0, 100, 100);
        param.setSourceRegion(rect);
        BufferedImage bi = imageReader.read(0, param);
        ImageIO.write(bi, "jpg", new File("/home/yumingzhe/b.jpg"));
        imageInputStream.close();
        fileInputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 54
Project: xapi-master  File: ResourceCollection.java View source code
static ResourceCollection fromUrl(URL url, String pkg) {
    String path = url.toExternalForm();
    File file;
    boolean jarUrl = path.startsWith("jar:");
    if (jarUrl)
        path = path.substring("jar:".length());
    boolean fileUrl = path.startsWith("file:");
    if (fileUrl)
        path = path.substring("file:".length());
    boolean jarFile = path.contains(".jar!");
    if (jarFile)
        path = path.substring(0, path.indexOf(".jar!") + ".jar".length());
    if (!(file = new java.io.File(path)).exists()) {
        path = path.replace("%20", " ");
        if (!(file = new java.io.File(path)).exists()) {
            throw X_Util.rethrow(new FileNotFoundException());
        }
    }
    try {
        if (url.getProtocol().equals("jar")) {
            return new ResourceCollection(pkg, ((JarURLConnection) url.openConnection()).getJarFile());
        }
        assert url.getProtocol().equals("file") : "ResourceCollection only handles url and file protocols";
        if (jarFile) {
            return new ResourceCollection(pkg, new JarFile(file));
        }
        return new ResourceCollection(file);
    } catch (IOException e) {
        throw X_Util.rethrow(e);
    }
}
Example 55
Project: j2objc-master  File: OkioTest.java View source code
@Test
public void appendFile() throws Exception {
    File file = temporaryFolder.newFile();
    BufferedSink sink = Okio.buffer(Okio.appendingSink(file));
    sink.writeUtf8("Hello, ");
    sink.close();
    assertTrue(file.exists());
    assertEquals(7, file.length());
    sink = Okio.buffer(Okio.appendingSink(file));
    sink.writeUtf8("java.io file!");
    sink.close();
    assertEquals(20, file.length());
    BufferedSource source = Okio.buffer(Okio.source(file));
    assertEquals("Hello, java.io file!", source.readUtf8());
    source.close();
}
Example 56
Project: eclipse.jdt.core-master  File: ModelTestsUtil.java View source code
private static void collectAllFiles(File root, ArrayList collector, FileFilter fileFilter) {
    File[] files = root.listFiles(fileFilter);
    for (int i = 0; i < files.length; i++) {
        final File currentFile = files[i];
        if (currentFile.isDirectory()) {
            collectAllFiles(currentFile, collector, fileFilter);
        } else {
            collector.add(currentFile);
        }
    }
}
Example 57
Project: Valkyrie-RCP-master  File: FileChooserBinding.java View source code
protected JComponent doBindControl() {
    if (!useFile && getValue() != null) {
        field.setText((String) getValue());
    } else if (useFile && getValue() != null) {
        field.setText(((java.io.File) getValue()).getAbsolutePath());
    } else {
        field.setText("");
    }
    FormLayout layout = new FormLayout(new ColumnSpec[] { ColumnSpec.decode("fill:10dlu:grow"), FormFactory.LABEL_COMPONENT_GAP_COLSPEC, ColumnSpec.decode("fill:10dlu:nogrow") }, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC });
    JPanel panel = new JPanel(layout);
    panel.add(field, new CellConstraints(1, 1));
    panel.add(openChooserButton, new CellConstraints(3, 1));
    return panel;
}
Example 58
Project: jena-master  File: LocatorFile.java View source code
@Override
public TypedStream open(String filenameOrURI) {
    // Worry about %20.
    // toFile calls FileUtils.toFilename(filenameOrURI) ;
    File f = toFile(filenameOrURI);
    try {
        if (f == null || !f.exists()) {
            if (FileManager.logAllLookups && log.isTraceEnabled())
                log.trace("Not found: " + filenameOrURI + thisDirLogStr);
            return null;
        }
    } catch (AccessControlException e) {
        log.warn("Security problem testing for file", e);
        return null;
    }
    try {
        InputStream in = new FileInputStream(f);
        if (FileManager.logAllLookups && log.isTraceEnabled())
            log.trace("Found: " + filenameOrURI + thisDirLogStr);
        //base = base.replaceFirst("^file:/([^/])", "file:///$1") ;
        return new TypedStream(in);
    } catch (IOException ioEx) {
        log.warn("File unreadable (but exists): " + f.getPath() + " Exception: " + ioEx.getMessage());
        return null;
    }
}
Example 59
Project: eclipselink.runtime-master  File: XMLSchemaFileReferenceTests.java View source code
public void testInvalidFile() throws Exception {
    XMLSchemaFileReference schemaReference = new XMLSchemaFileReference();
    File file = new File("");
    schemaReference.setFile(file);
    InputStream stream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/oxm/schemareference/employee_warn.xml");
    try {
        Document doc = parser.parse(stream);
        boolean isValid = schemaReference.isValid(doc, null);
    } catch (XMLMarshalException e) {
        assertTrue("An unexpected XMLMarshalException was caught", e.getErrorCode() == XMLMarshalException.ERROR_RESOLVING_XML_SCHEMA);
        return;
    }
    assertTrue("An XMLValidation should have been caught but wasn't.", false);
}
Example 60
Project: shrinkwrap-master  File: ExplodedExporterImpl.java View source code
/**
     * [email protected]}
     *
     * @see org.jboss.shrinkwrap.api.exporter.ExplodedExporter#exportExploded(java.io.File, java.lang.String)
     */
@Override
public File exportExploded(File baseDirectory, String directoryName) {
    final Archive<?> archive = this.getArchive();
    Validate.notNull(archive, "No archive provided");
    Validate.notNull(baseDirectory, "No baseDirectory provided");
    // Directory must exist
    if (!baseDirectory.exists()) {
        throw new IllegalArgumentException("Parent directory does not exist");
    }
    // Must be a directory
    if (!baseDirectory.isDirectory()) {
        throw new IllegalArgumentException("Provided parent directory is not a valid directory");
    }
    return export(archive, new File(baseDirectory, directoryName));
}
Example 61
Project: jadira-master  File: JdkBaseClasspathUrlLocator.java View source code
@Override
public List<URL> locate() {
    List<URL> classpaths = new ArrayList<URL>();
    String[] endorsedDirs = System.getProperty("java.endorsed.dirs").split(System.getProperty("path.separator"));
    processClasspathDefinition(classpaths, endorsedDirs);
    try {
        // Can't resolve using sun.boot.class.path - vendor specific
        if (includeRtJar) {
            URL javaClasspath = new java.io.File(System.getProperty("java.home") + System.getProperty("file.separator") + "lib" + System.getProperty("file.separator") + "rt.jar").toURI().toURL();
            classpaths.add(javaClasspath);
        }
    } catch (MalformedURLException e) {
        throw new ClasspathAccessException("Problem constructing Java classpath: " + e.getMessage(), e);
    }
    String[] extensionDirs = System.getProperty("java.ext.dirs").split(System.getProperty("path.separator"));
    processClasspathDefinition(classpaths, extensionDirs);
    return classpaths;
}
Example 62
Project: java-thumbnailer-master  File: TemporaryFilesManagerTest.java View source code
@Test
public void test() throws Exception {
    File input = File.createTempFile("test-input", ".txt");
    File output = tfm.createTempfileCopy(input, "bla");
    assertEquals("bla", FilenameUtils.getExtension(output.getName()));
    assertFalse("Copy didn't work", input.equals(output));
    assertFalse("Copy/Rename didn't work", FilenameUtils.getBaseName(input.getName()).equals(FilenameUtils.getBaseName(output.getName())));
    File output2 = tfm.createTempfileCopy(input, "bla");
    assertEquals(output, output2);
    File output3 = tfm.createTempfileCopy(input, "blub");
    assertEquals(FilenameUtils.getBaseName(output.getName()) + ".blub", output3.getName());
    File output4 = tfm.createTempfileCopy(input, "blub");
    assertEquals(output3, output4);
}
Example 63
Project: sysart-itext-master  File: DocumentFontTest.java View source code
@Test
public void testConstructionForType0WithoutToUnicodeMap() throws Exception {
    int pageNum = 2;
    PdfName fontIdName = new PdfName("TT9");
    File testFile = TestResourceUtils.getResourceAsTempFile(this, "type0FontWithoutToUnicodeMap.pdf");
    RandomAccessFileOrArray f = new RandomAccessFileOrArray(testFile.getAbsolutePath());
    PdfReader reader = new PdfReader(f, null);
    PdfDictionary fontsDic = reader.getPageN(pageNum).getAsDict(PdfName.RESOURCES).getAsDict(PdfName.FONT);
    PdfDictionary fontDicDirect = fontsDic.getAsDict(fontIdName);
    PRIndirectReference fontDicIndirect = (PRIndirectReference) fontsDic.get(fontIdName);
    Assert.assertEquals(PdfName.TYPE0, fontDicDirect.getAsName(PdfName.SUBTYPE));
    Assert.assertEquals("/Identity-H", fontDicDirect.getAsName(PdfName.ENCODING).toString());
    Assert.assertNull("This font should not have a ToUnicode map", fontDicDirect.get(PdfName.TOUNICODE));
    // this used to throw an NPE
    new DocumentFont(fontDicIndirect);
}
Example 64
Project: SRE-RoboCode-master  File: FileWriteSize.java View source code
public void run() {
    out.println("Data directory: " + getDataDirectory());
    out.println("Data quota: " + getDataQuotaAvailable());
    byte[] buf = new byte[100000];
    File file = null;
    RobocodeFileOutputStream rfos = null;
    try {
        file = getDataFile("test");
        out.println("Data file: " + file.getCanonicalPath());
        file.delete();
        rfos = new RobocodeFileOutputStream(file);
        for (int i = 0; i < 3; i++) {
            rfos.write(buf);
        }
    } catch (IOException e) {
        e.printStackTrace(out);
    } finally {
        if (rfos != null) {
            try {
                rfos.close();
            } catch (IOException e) {
                e.printStackTrace(out);
            }
        }
        if (file != null) {
            if (!file.delete()) {
                out.println("Could not delete the file: " + file);
            }
        }
    }
}
Example 65
Project: dlna-master  File: FileFilterUtil.java View source code
public static List<File> getFiles(String path, String[] postfix) {
    File file = new File(path);
    File[] files = file.listFiles();
    List<File> lists = new ArrayList();
    if (files == null || files.length == 0) {
        return null;
    }
    for (int i = 0; i < files.length; i++) {
        File childFile = files[i];
        System.out.println("" + childFile.getPath());
        if (childFile.isFile()) {
            childFile.getName();
            int index = childFile.getName().lastIndexOf(".");
            index++;
            String name = childFile.getName().substring(index, childFile.getName().length());
            for (int j = 0; j < postfix.length; j++) {
                if (name.equalsIgnoreCase(postfix[j])) {
                    lists.add(childFile);
                }
            }
        } else if (childFile.isDirectory() && formateToDepth(childFile.getAbsolutePath())) {
            List<File> lsts = getFiles(childFile.getAbsolutePath(), postfix);
            if (lsts != null && lsts.size() != 0) {
                lists.addAll(lsts);
            }
        }
    }
    return lists;
}
Example 66
Project: MyFramework-master  File: FreeMarkerConfig.java View source code
/***�1�7
     * @param templateDirPath
     * @throws ConfigureException
     */
public void configureFreeMarker(String templateDirPath) throws Exception {
    if (null == templateDirPath || "".equals(templateDirPath)) {
        throw new Exception("FreeMarker template directory not exist:" + templateDirPath);
    }
    File templateDir = new File(templateDirPath);
    if (null == templateDir || !templateDir.exists() || !templateDir.isDirectory()) {
        throw new Exception("FreeMarker template directory not exist:" + templateDirPath);
    }
    // Configure the template engine
    Configuration templateCfg = new Configuration();
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        wrapper.setSimpleMapWrapper(true);
        wrapper.setExposureLevel(BeansWrapper.EXPOSE_ALL);
        templateCfg.setEncoding(Locale.CHINA, "utf-8");
        templateCfg.setObjectWrapper(wrapper);
        templateCfg.setDirectoryForTemplateLoading(templateDir);
        templateCfg.setNumberFormat("######################.##");
    } catch (IOException e) {
        throw new Exception("IOException occured when loading freemarker template:" + templateDirPath);
    }
    templateCfg.setTemplateUpdateDelay(2);
    Configuration.setDefaultConfiguration(templateCfg);
}
Example 67
Project: teiid-designer-master  File: TestModelEditor.java View source code
public void testCloneProject() throws Exception {
    //$NON-NLS-1$
    String testDataPath = SmartTestDesignerSuite.getTestDataPath(getClass()) + File.separator + "cloneProject";
    ModelEditorImpl editor = new ModelEditorImpl();
    //$NON-NLS-1$ //$NON-NLS-2$
    System.err.println("\n\n\n**********************************\n\n\nPath=" + testDataPath + "\n\n\n");
    File[] files = new File(testDataPath).listFiles();
    //$NON-NLS-1$
    File tmpProject = new File(System.getProperty("java.io.tmpdir"));
    tmpProject.deleteOnExit();
    for (int ndx = files.length; --ndx >= 0; ) {
        File file = files[ndx];
        if (file.isDirectory() && file.getName().charAt(0) != '.') {
            String origProjectPath = file.getAbsolutePath();
            String clonedProjectPath = new File(tmpProject, file.getName()).getAbsolutePath();
            editor.cloneProject(origProjectPath, clonedProjectPath);
        }
    }
}
Example 68
Project: breakout-master  File: EditSurveyScanPathsAction.java View source code
@Override
public void actionPerformed(ActionEvent e) {
    QArrayList<File> surveyScanPaths = mainView.getProjectModel().get(ProjectModel.surveyScanPaths);
    if (surveyScanPaths == null) {
        surveyScanPaths = new QArrayList<>();
        mainView.getProjectModel().set(ProjectModel.surveyScanPaths, surveyScanPaths);
    }
    QFileListEditor editor = new QFileListEditor();
    editor.setModel(surveyScanPaths);
    editor.setPreferredSize(new Dimension(600, 400));
    JOptionPane.showMessageDialog(mainView.getMainPanel(), editor, "Survey Scan Search Directories", JOptionPane.PLAIN_MESSAGE);
    editor.setModel(null);
}
Example 69
Project: liferay-ide-master  File: CompareFileHandler.java View source code
protected File getTemplateFile(IFile currentFile) throws Exception {
    final IProject currentProject = currentFile.getProject();
    final IFile bndfile = currentProject.getFile("bnd.bnd");
    File templateFile = null;
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(bndfile.getContents()))) {
        String fragment;
        while ((fragment = reader.readLine()) != null) {
            if (fragment.startsWith("Fragment-Host:")) {
                fragment = fragment.substring(fragment.indexOf(":") + 1, fragment.indexOf(";")).trim();
                break;
            }
        }
        final String hookfolder = currentFile.getFullPath().toOSString().substring(currentFile.getFullPath().toOSString().lastIndexOf("META-INF"));
        final IPath templateLocation = GradleCore.getDefault().getStateLocation().append(fragment).append(hookfolder);
        templateFile = new File(templateLocation.toOSString());
        if (!templateFile.exists()) {
            throw new FileNotFoundException("Template not found.");
        }
    }
    return templateFile;
}
Example 70
Project: bigtable-sql-master  File: RecentFilesTreeCellRenderer.java View source code
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    JLabel treeCellRendererComponent = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) value;
    if (false == dmtn.getUserObject() instanceof File) {
        return treeCellRendererComponent;
    }
    File file = (File) dmtn.getUserObject();
    if (file.isDirectory()) {
        treeCellRendererComponent.setIcon(_app.getResources().getIcon(SquirrelResources.IImageNames.DIR_GIF));
    } else {
        treeCellRendererComponent.setIcon(_app.getResources().getIcon(SquirrelResources.IImageNames.FILE_GIF));
    }
    return treeCellRendererComponent;
}
Example 71
Project: AndroidBinding-master  File: RegisterApplicationTask.java View source code
@Override
public void execute() throws BuildException {
    try {
        File file = new File(mDir, "AndroidManifest.xml");
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(mDir, "AndroidManifest.xml"));
        Element appNode = (Element) doc.getElementsByTagName("application").item(0);
        appNode.setAttribute("android:name", mAppClassName);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
        log("Manifest <application> modified");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 72
Project: iswc2012metadata-master  File: TaskCopyPdf.java View source code
public static void main(String[] args) throws Sw4jException {
    DataKeyKeyValue<String, String, String> mapPv = new DataKeyKeyValue<String, String, String>();
    File fRootTex = new File("local/iswc2012full");
    File fRootPdf = new File("local/iswc2012pdf");
    for (File fPaper : fRootTex.listFiles()) {
        for (File f : fPaper.listFiles()) {
            if (!f.getAbsolutePath().endsWith(".pdf")) {
                continue;
            }
            String idFolder = f.getParentFile().getName();
            String fileName = f.getName();
            if (!fileName.startsWith("76")) {
                continue;
            }
            File fNew = new File(fRootPdf, idFolder + ".pdf");
            ToolIO.pipeFileToFile(f, fNew);
            mapPv.set(idFolder, fileName, fileName);
            System.out.println(String.format("copied from %s to %s.pdf", fileName, idFolder));
        }
    }
//print(mapPv.report(false));		
}
Example 73
Project: android-15-master  File: CarouselViewUtilities.java View source code
/**
     * Debug utility to write the given bitmap to a file.
     *
     * @param context calling context
     * @param bitmap the bitmap to write
     * @param filename the name of the file to write
     * @return
     */
public static boolean writeBitmapToFile(Context context, Bitmap bitmap, String filename) {
    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File file = new File(path, filename);
    boolean result = false;
    try {
        path.mkdirs();
        OutputStream os = new FileOutputStream(file);
        MediaScannerConnection.scanFile(context, new String[] { file.toString() }, null, null);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
        result = true;
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
    return result;
}
Example 74
Project: cloudtm-data-platform-master  File: ConverterClassAwareDmlCompiler.java View source code
public static void main(String[] args) throws Exception {
    final int c = args.length;
    final int offset = c - 3;
    final File dir = new File(args[offset]);
    final String[] baseArgs;
    if (dir.exists() && dir.isDirectory()) {
        final List<String> dmlFilenames = new ArrayList<String>();
        for (final File file : dir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".dml")) {
                dmlFilenames.add(file.getCanonicalPath());
            }
        }
        Collections.sort(dmlFilenames);
        List<URL> pluginDmlUrlList = PluginDmlUrlLoader.getPluginDmlUrlList();
        baseArgs = new String[c - 3 + dmlFilenames.size() + pluginDmlUrlList.size()];
        System.arraycopy(args, 0, baseArgs, 0, offset);
        int i = offset;
        for (URL pluginDmlUrl : pluginDmlUrlList) {
            baseArgs[i++] = pluginDmlUrl.toExternalForm();
        }
        for (final String dmlFilename : dmlFilenames) {
            baseArgs[i++] = dmlFilename;
        }
    } else {
        baseArgs = Arrays.copyOfRange(args, 0, c - 2);
    }
    DmlCompiler.main(baseArgs);
}
Example 75
Project: Eclipse-Postfix-Code-Completion-master  File: FileFinder.java View source code
private static void find0(File f, String pattern, ArrayList collector) {
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files == null)
            return;
        for (int i = 0, max = files.length; i < max; i++) {
            File current = new File(f, files[i]);
            if (current.isDirectory()) {
                find0(current, pattern, collector);
            } else {
                if (current.getName().toUpperCase().endsWith(pattern)) {
                    collector.add(current.getAbsolutePath());
                }
            }
        }
    }
}
Example 76
Project: geoserver-enterprise-master  File: GetStatus.java View source code
public Object run(GetExecutionStatusType request) {
    // see if the process is still in-flight
    ExecuteResponseType status = executionManager.getStatus(request.getExecutionId());
    if (status != null) {
        return status;
    }
    // otherwise check for a stored response
    File storedResponse = executionManager.getStoredResponse(request.getExecutionId());
    if (storedResponse == null || !storedResponse.exists()) {
        throw new WPSException("Unknown execution id " + request.getExecutionId() + ", either the execution was never submitted or too much time " + "elapsed since the process completed");
    }
    return storedResponse;
}
Example 77
Project: btpka3.github.com-master  File: FontTest.java View source code
/**
     * TODO 方法的作用是?
     *
     * @author zhangliangliang
     * @date 2013-12-25下午5:07:05
     *
     * @param args
     * @throws IOException
     */
public static void main(String[] args) throws IOException {
    Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
    attributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_TIGHT);
    Font font = new Font("Arial", Font.BOLD, 40);
    font = font.deriveFont(attributes);
    BufferedImage img = new BufferedImage(500, 200, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    // set background
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, img.getWidth(), img.getHeight());
    g.setFont(font);
    g.setColor(Color.BLACK);
    FontMetrics metrics = g.getFontMetrics(font);
    g.drawString("HELLO testing", 0, metrics.getHeight());
    ImageIO.write(img, "jpg", new File("/test.jpg"));
}
Example 78
Project: Payara-master  File: FileProtectionUtility.java View source code
/**
     * Set permissions on the specified file equivalent to file mode 0600.
     *
     * NOTE: This method will only set permissions on files that exist on filesystems which support POSIX file
     * permissions.  Manipulation of permissions is silently skipped for filesystems that do not support POSIX file
     * permissions (such as Windows NTFS).
     *
     * @param file The file to set permissions on
     * @throws IOException if an I/O error occurs
     */
public static void chmod0600(File file) throws IOException {
    Path filePath = file.toPath();
    PosixFileAttributeView posixFileAttributeView = Files.getFileAttributeView(filePath, PosixFileAttributeView.class);
    if (posixFileAttributeView != null) {
        Files.setPosixFilePermissions(filePath, EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));
    }
}
Example 79
Project: aceim-master  File: Checksum.java View source code
public static long getCRC32Checksum(File file) throws IOException {
    CheckedInputStream cis = new CheckedInputStream(new FileInputStream(file), new java.util.zip.CRC32());
    byte[] buf = new byte[128];
    while (cis.read(buf) >= 0) {
    }
    long val = cis.getChecksum().getValue();
    cis.close();
    return val;
}
Example 80
Project: RoboBuggy-master  File: SystemExitTest.java View source code
@Test
public void failureCausesExitCodeOf1() throws Exception {
    String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    String classPath = getClass().getClassLoader().getResource(".").getFile() + File.pathSeparator + System.getProperty("java.class.path");
    String[] cmd = { java, "-cp", classPath, getClass().getName() + "$Exit" };
    Process process = Runtime.getRuntime().exec(cmd);
    InputStream input = process.getInputStream();
    while ((input.read()) != -1) ;
    assertEquals(EXIT_CODE, process.waitFor());
}
Example 81
Project: ecologylabFundamental-master  File: BinarySerializer.java View source code
@Override
public void serialize(Object object, File outputFile, TranslationContext translationContext) throws SIMPLTranslationException {
    try {
        XMLTools.createParentDirs(outputFile);
        if (outputFile.getParentFile() != null)
            translationContext.setBaseDirFile(outputFile.getParentFile());
        FileOutputStream fStream = new FileOutputStream(outputFile);
        serialize(object, fStream, translationContext);
        fStream.close();
    } catch (IOException e) {
        throw new SIMPLTranslationException("IO Exception: ", e);
    }
}
Example 82
Project: expenditures-master  File: FenixJasperCompiler.java View source code
@Override
public String compileClasses(File[] sourceFiles, String classpath) throws JRException {
    // Retrieve files from the standard location
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFiles));
    CompilationTask task = compiler.getTask(new StringWriter(), fileManager, null, Arrays.asList("-classpath", classpath), null, sources);
    if (!task.call()) {
        throw new JRException("Error compiling report java source files");
    }
    return null;
}
Example 83
Project: keycloak-master  File: KeycloakDependenciesResolver.java View source code
public static File[] resolveDependencies(String canonicalForm) {
    if (dependencies.containsKey(canonicalForm)) {
        return dependencies.get(canonicalForm);
    }
    log.info("Resolving " + canonicalForm + "'s dependencies");
    PomEquippedResolveStage resolver = Maven.configureResolverViaPlugin();
    File[] files = resolver.addDependency(MavenDependencies.createDependency(canonicalForm, ScopeType.COMPILE, false)).resolve().withTransitivity().asFile();
    dependencies.put(canonicalForm, files);
    log.info("Resolving dependencies is finished with " + files.length + " files");
    return dependencies.get(canonicalForm);
}
Example 84
Project: android-platform-tools-base-master  File: FakeServer.java View source code
@Override
public void uploadApks(@NonNull String variantName, @NonNull File testApk, @Nullable File testedApk) {
    System.out.println("uploadApks CALLED");
    if (testApk == null) {
        throw new NullPointerException("Null testApk");
    }
    if (!testApk.isFile()) {
        throw new RuntimeException("Missing file: " + testApk.getAbsolutePath());
    }
    if (!testApk.getAbsolutePath().endsWith(".apk")) {
        throw new RuntimeException("Wrong extension: " + testApk.getAbsolutePath());
    }
    System.out.println("\ttestApk: " + testApk.getAbsolutePath());
    if (testedApk != null) {
        if (!testedApk.isFile()) {
            throw new RuntimeException("Missing file: " + testedApk.getAbsolutePath());
        }
        if (!testedApk.getAbsolutePath().endsWith(".apk")) {
            throw new RuntimeException("Wrong extension: " + testedApk.getAbsolutePath());
        }
        System.out.println("\ttestedApk: " + testedApk.getAbsolutePath());
        if (testApk.equals(testedApk)) {
            throw new RuntimeException("Both APKs are the same!");
        }
    }
    uploadCalled = true;
}
Example 85
Project: FTL-Hyperion-master  File: ResourceExtractor.java View source code
public static void extract() {
    String ftlPath = (String) JOptionPane.showInputDialog(null, "What is your FTL install directory:\n", "Extracting Resources", JOptionPane.PLAIN_MESSAGE, null, null, "C:/Program Files (x86)/Steam/SteamApps/common/FTL Faster Than Light");
    datLib dat = new datLib(ftlPath + "/resources/resource.dat");
    int[] ids = dat.List();
    ProgressMonitor progressMonitor = new ProgressMonitor(null, "Extracting Resources", "", 0, ids.length);
    for (int i = 0; i < ids.length; i++) {
        String path = dat.Filename(ids[i]);
        File file = new File("resources/" + path);
        if (!file.exists()) {
            dat.Extract(ids[i], "resources/" + path);
        }
        progressMonitor.setProgress(i);
    }
    progressMonitor.close();
}
Example 86
Project: geotools-old-master  File: QuickstartNotes.java View source code
public void snipetDataStoreFinder() throws Exception {
    // start datastore
    File file = JFileDataStoreChooser.showOpenFile("shp", null);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("url", file.toURI().toURL());
    params.put("create spatial index", false);
    params.put("memory mapped buffer", false);
    params.put("charset", "ISO-8859-1");
    DataStore store = DataStoreFinder.getDataStore(params);
    SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
// end datastore
}
Example 87
Project: hdt-java-master  File: TarTest.java View source code
public static void main(String[] args) throws Throwable {
    InputStream input = new ExternalDecompressStream(new File("/Users/mck/rdf/dataset/tgztest.tar.gz"), ExternalDecompressStream.GZIP);
    //		InputStream input = new CountInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream("/Users/mck/rdf/dataset/tgztest.tar.gz"))));
    //		InputStream input = new CountInputStream(new BufferedInputStream(new FileInputStream("/Users/mck/rdf/dataset/tgztest.tar")));
    final TarArchiveInputStream debInputStream = new TarArchiveInputStream(input);
    TarArchiveEntry entry = null;
    NonCloseInputStream nonCloseIn = new NonCloseInputStream(debInputStream);
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        System.out.println(entry.getName());
    }
    debInputStream.close();
}
Example 88
Project: cdt-tests-runner-master  File: ProjectConverter.java View source code
public IBuildObject convert(IBuildObject buildObj, String fromId, String toId, boolean isConfirmed) {
    String tmpDir = System.getProperty("java.io.tmpdir");
    File outputFile = new File(tmpDir + "/converterOutput.txt");
    try {
        FileWriter out = new FileWriter(outputFile);
        out.write("---------- Start-------");
        out.write("Converter for the build object : '" + buildObj.getName() + "' is invoked.");
        out.write("From Id : " + fromId);
        out.write("To Id : " + toId);
        out.write("---------- End-------");
    } catch (IOException e) {
        System.out.println("Exception raised.");
    }
    return buildObj;
}
Example 89
Project: dcache-master  File: Adler32.java View source code
public static final void main(String[] args) throws Exception {
    if (args == null || args.length != 1 || args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("-help") || args[0].equalsIgnoreCase("--h") || args[0].equalsIgnoreCase("--help")) {
        System.err.println(" Usage: adler32 file");
        System.exit(1);
        return;
    }
    File f = new File(args[0]);
    if (!f.exists()) {
        System.err.println("file " + args[0] + " does not exist");
        System.exit(2);
    }
    if (!f.canRead()) {
        System.err.println("file " + args[0] + " can not be read ");
        System.exit(2);
    }
    FileChannel fc = new RandomAccessFile(f, "r").getChannel();
    String adler32 = GridftpClient.long32bitToHexString(GridftpClient.getAdler32(fc));
    System.out.println(adler32);
}
Example 90
Project: Android_Paint-master  File: SaveGalleryImageAction.java View source code
@Override
public void doAction(Context context, PaintAreaActivity.PaintView paintView) {
    Boolean isOk = FileUtils.saveLocalImage(context, paintView.getDrawableBitmapCopy(), FileUtils.SHARE_TEMP_FILE_NAME, false);
    if (isOk) {
        try {
            Uri tmpFileUri = FileUtils.getLocalImagePath(context, FileUtils.SHARE_TEMP_FILE_NAME);
            if (tmpFileUri != null) {
                File file = new File(tmpFileUri.getPath());
                String appName = context.getString(R.string.app_name);
                String imageUrl = MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), null, "Image from " + appName);
                if (imageUrl == null) {
                    WarningAlert.show(context, "Cannot insert image to gallery.");
                } else {
                    Toast.makeText(context, "Image was successfully saved to gallery.", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception ex) {
            WarningAlert.show(context, "Cannot share image on facebook: " + ex.getMessage());
            ex.printStackTrace();
        }
    }
}
Example 91
Project: SecurePhoto-master  File: SPImageHandler.java View source code
@Override
public SPIWrapper saveFile(byte[] bytes) {
    File pictureFile;
    try {
        pictureFile = FileHandling.getOutputFile(SPImage.DEFAULT_EXTENSION);
    } catch (IOException e) {
        throw new RuntimeException("Cannot create output file");
    }
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(pictureFile);
        SPImage image = SPImage.getInstance(bytes, verifierProvider.getVerifiers());
        fileOutputStream.write(image.toByteArray());
        fileOutputStream.close();
        return new SPIWrapper(pictureFile, image.getHeader(), image.getFrameHash());
    } catch (FileNotFoundException e) {
        throw new RuntimeException(String.format("Cannot write to file %s", pictureFile.getAbsolutePath()));
    } catch (IOException e) {
        throw new RuntimeException("IOException: " + e.toString());
    }
}
Example 92
Project: ehour-master  File: DatabasePopulator.java View source code
public static void setUpDatabase(DataSource dataSource, List<String> dataSetFileNames, String dbVersion) throws Exception {
    DerbyDbValidator validator = new DerbyDbValidator(dbVersion, dataSource);
    validator.checkDatabaseState();
    Connection con = DataSourceUtils.getConnection(dataSource);
    con.setAutoCommit(false);
    IDatabaseConnection connection = new DatabaseConnection(con);
    for (String dataSetFileName : dataSetFileNames) {
        FlatXmlDataSet additionalDataSet = new FlatXmlDataSetBuilder().build(new File("src/test/resources/datasets/" + dataSetFileName));
        DatabaseOperation.CLEAN_INSERT.execute(connection, additionalDataSet);
    }
}
Example 93
Project: EE3Helper-master  File: CommandForceRegen.java View source code
@Override
public void processCommand(ICommandSender cs, String[] args) {
    File staticValues = new File(Files.STATIC_ENERGY_VALUES_JSON);
    if (staticValues.exists())
        staticValues.delete();
    WorldEventHandler.hasInitilialized = false;
    DynamicEnergyValueInitThread d = new DynamicEnergyValueInitThread();
    Thread t = new Thread(d, "EE3H_DYNEMCTHREAD");
    if (!CommandRemove.nogenRemoval)
        Helper.toChat(cs, EnumChatFormatting.AQUA + "Waiting for Dynamic EMC.");
    t.start();
    long start = System.currentTimeMillis();
    try {
        while (t.isAlive()) {
            Thread.sleep(100);
        }
    } catch (InterruptedException e) {
    }
    if (!CommandRemove.nogenRemoval)
        Helper.toChat(cs, EnumChatFormatting.GREEN + "Dynamic EMC complete: " + (System.currentTimeMillis() - start - 100) / 1000 + "s");
    WorldEventHandler.hasInitilialized = true;
    EnergyValueRegistry.getInstance().setShouldRegenNextRestart(true);
    EnergyValueRegistry.getInstance().save();
}
Example 94
Project: word2vec-query-expansion-master  File: Word2VecFilterTest.java View source code
@Test
public void testIncrementToken() throws Exception {
    // no vector expansion, for documents
    SearchFiles.main(new String[] { //
    "-index", //
    new File("./target/index").getAbsolutePath(), "-query", "tourism" });
    assertEquals(4, SearchFiles.cachedHits.size());
    assertEquals("Rimouski.txt", SearchFiles.cachedHits.get(0).replaceAll("^.*/", ""));
    SearchFiles.main(new String[] { "-index", //
    new File("./target/index").getAbsolutePath(), "-vectors", new File("./src/test/resources/com/radialpoint/word2vec/lucene/quebec.vectors.ser").getAbsolutePath(), "-query", "tourism" });
    assertEquals(SearchFiles.cachedHits.size(), 9);
    assertEquals("Montreal.txt", SearchFiles.cachedHits.get(0).replaceAll("^.*/", ""));
}
Example 95
Project: aws-toolkit-eclipse-master  File: ZipUtils.java View source code
public static void createZipFileOfDirectory(File srcDir, File zipOutput) throws IOException {
    if (!srcDir.isDirectory()) {
        throw new IllegalArgumentException(srcDir.getAbsolutePath() + " is not a directory!");
    }
    ZipOutputStream zipOutputStream = null;
    String baseName = srcDir.getAbsolutePath() + File.pathSeparator;
    try {
        zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutput));
        addDirToZip(srcDir, zipOutputStream, baseName);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}
Example 96
Project: WordPress-Android-master  File: GravatarApiTest.java View source code
public void testGravatarUploadRequest() throws IOException {
    final String fileContent = "abcdefg";
    File tempFile = new File(getInstrumentation().getTargetContext().getCacheDir(), "tempFile.jpg");
    FileOutputStream fos = new FileOutputStream(tempFile);
    fos.write(fileContent.getBytes());
    fos.flush();
    fos.close();
    final String email = "[email protected]";
    Request uploadRequest = GravatarApi.prepareGravatarUpload(email, tempFile);
    assertEquals("POST", uploadRequest.method());
    RequestBody requestBody = uploadRequest.body();
    assertTrue(requestBody.contentType().toString().startsWith("multipart/form-data"));
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    final String body = buffer.readUtf8();
    assertTrue(body.contains("Content-Disposition: form-data; name=\"account\""));
    assertTrue(body.contains("Content-Length: " + email.length()));
    assertTrue(body.contains(email));
    assertTrue(body.contains("Content-Disposition: form-data; name=\"filedata\"; filename=\"" + tempFile.getName() + "\""));
    assertTrue(body.contains("Content-Type: multipart/form-data"));
    assertTrue(body.contains(fileContent));
}
Example 97
Project: Archimulator-master  File: CSVHelper.java View source code
/**
     * To CSV.
     *
     * @param outputCSVFileName the output CSV file name
     * @param results the list of results
     * @param fields the list of fields
     * @param <ResultT> the result type
     */
public static <ResultT> void toCsv(String outputCSVFileName, List<ResultT> results, List<CSVField<ResultT>> fields) {
    File resultDirFile = new File(outputCSVFileName).getParentFile();
    if (!resultDirFile.exists()) {
        if (!resultDirFile.mkdirs()) {
            throw new RuntimeException();
        }
    }
    CSVFormat format = CSVFormat.RFC4180.withHeader().withDelimiter(',').withQuoteMode(QuoteMode.ALL).withQuote('"');
    try {
        FileWriter writer = new FileWriter(outputCSVFileName);
        CSVPrinter printer = new CSVPrinter(writer, format);
        printer.printRecord(fields);
        for (ResultT result : results) {
            List<String> record = new ArrayList<>();
            for (CSVField<ResultT> field : fields) {
                record.add(field.getFunc().apply(result));
            }
            printer.printRecord(record);
        }
        printer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 98
Project: openwayback-master  File: MonitoredFileSetTest.java View source code
public void testIsChanged() throws IOException, InterruptedException {
    File f1 = new File(System.getProperty("java.io.tmpdir"), "file-set-1.tmp");
    File f2 = new File(System.getProperty("java.io.tmpdir"), "file-set-2.tmp");
    writeFile(f1, "one");
    writeFile(f2, "two");
    ArrayList<String> l = new ArrayList<String>();
    l.add(f1.getAbsolutePath());
    l.add(f2.getAbsolutePath());
    MonitoredFileSet fs = new MonitoredFileSet(l);
    MonitoredFileSet.FileState s1 = fs.getFileState();
    MonitoredFileSet.FileState s2 = fs.getFileState();
    assertFalse(fs.isChanged(s1));
    assertFalse(fs.isChanged(s2));
    Thread.sleep(1001);
    writeFile(f2, "two2");
    MonitoredFileSet.FileState s3 = fs.getFileState();
    assertTrue(fs.isChanged(s2));
    assertTrue(s3.isChanged(s2));
    Thread.sleep(1001);
    assertTrue(fs.isChanged(s2));
    assertFalse(fs.isChanged(s3));
}
Example 99
Project: Nimingban-master  File: LogCat.java View source code
public static boolean save(File file) {
    if (!FileUtils.ensureFile(file)) {
        return false;
    }
    try {
        Process p = Runtime.getRuntime().exec("logcat -d");
        IOUtils.copy(p.getInputStream(), new FileOutputStream(file));
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
Example 100
Project: park-alert-master  File: Debug.java View source code
public static void commit(HttpServlet servlet) {
    BufferedWriter out = null;
    try {
        FileWriter fileWritter = new FileWriter(new File("/root/apache-tomcat-5.5.34/webapps/backend/log-file.out").getName(), true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = new Date();
        String data = "[" + dateFormat.format(date) + "] " + buffer + "\n";
        bufferWritter.write(data);
        bufferWritter.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        buffer = null;
    }
}
Example 101
Project: Yhb-2.0-master  File: Bimp.java View source code
public static Bitmap revitionImageSize(String path) throws IOException {
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(path)));
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, options);
    in.close();
    int i = 0;
    Bitmap bitmap = null;
    while (true) {
        if ((options.outWidth >> i <= 1000) && (options.outHeight >> i <= 1000)) {
            in = new BufferedInputStream(new FileInputStream(new File(path)));
            options.inSampleSize = (int) Math.pow(2.0D, i);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeStream(in, null, options);
            break;
        }
        i += 1;
    }
    return bitmap;
}