Example usage for java.io File getParent

List of usage examples for java.io File getParent

Introduction

In this page you can find the example usage for java.io File getParent.

Prototype

public String getParent() 

Source Link

Document

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

From source file:com.ibm.rpe.web.service.docgen.impl.TemplateBuilderImpl.java

public void generateDocspec(String templatePath, String dataSourceUrl, String schemaName) throws Exception {
    System.out.println("###### Generating document specification"); //$NON-NLS-1$
    String specificationContent = readTemplatsFile(TemplateConstants.BASE_DOCSPEC_PATH);

    // Convert any '&' characters in the query URL to "&" or else RPE
    // launcher will not load the DSX file.

    // Substitute the schema name and query URL in the specification content
    Map<String, String> params = new HashMap<String, String>();
    params.put(TemplateConstants.TEMPLATE_NAME_PATH, templatePath);
    params.put(TemplateConstants.DATA_SOURCE_URL, dataSourceUrl);
    params.put(TemplateConstants.SCHEMA_LABEL, schemaName);
    for (Entry<String, String> entry : params.entrySet()) {
        specificationContent = specificationContent.replace(entry.getKey(), entry.getValue());
    }//w ww  .ja  va 2  s .  c o  m

    File temlateFile = new File(templatePath);
    String docSpecName = temlateFile.getName().replace(".dta", ".dsx"); //$NON-NLS-1$ //$NON-NLS-2$
    String docSpec = temlateFile.getParent() + File.separator + docSpecName;

    new File(docSpec).createNewFile();
    FileUtils.writeFile(docSpec, specificationContent);
    System.out.println("Doc spec: " + docSpec);
}

From source file:in.raster.oviyam.servlet.StudyInfoServlet.java

/** 
 * Handles the HTTP <code>GET</code> method.
 * @param request servlet request//from   w w  w  .j a  va 2s  .  c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String patID = request.getParameter("patientID");
    String studyUID = request.getParameter("studyUID");
    String serverName = request.getParameter("serverName");

    //File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");

    if (LanguageHandler.source == null) {
        File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
        LanguageHandler.source = new File(new XMLFileHandler().getXMLFilePath(tempDir.getParent()));

        /*String warName = request.getContextPath().substring(1);
        String tmpDirPath = tempDir.getAbsolutePath();
        tmpDirPath = tmpDirPath.substring(0, tmpDirPath.indexOf(warName));
        LanguageHandler.source = new File(new XMLFileHandler().getXMLFilePath(tmpDirPath));*/
    }

    ServerHandler sh = new ServerHandler();
    Server server = null;
    if (serverName != null && !serverName.isEmpty()) {
        server = sh.findServerByName(serverName);
    } else {
        server = sh.findServerByName("");
    }

    PrintWriter out = response.getWriter();
    JSONObject jsonObj = new JSONObject();

    if (server != null) {
        //Get calling aet
        ListenerHandler lh = new ListenerHandler();
        String callingAET = lh.getListener().getAetitle();
        if (!(callingAET != null && callingAET.length() > 0)) {
            callingAET = "OVIYAM2";
        }
        String dcmURL = "DICOM://" + server.getAetitle() + ":" + callingAET + "@" + server.getHostname() + ":"
                + server.getPort();
        String serverURL = null;

        if (server.getRetrieve().equals("WADO")) {
            serverURL = "http://" + server.getHostname() + ":" + server.getWadoport() + "/"
                    + server.getWadocontext();
        } else {
            serverURL = server.getRetrieve();
        }

        PatientInfo patientInfo = new PatientInfo();
        patientInfo.callFindWithQuery(patID, studyUID, dcmURL);
        //patientInfo.callFindWithQuery(patID, "", "", "", "", "", "","","", dcmURL);
        ArrayList<StudyModel> studyList = patientInfo.getStudyList();

        try {
            for (StudyModel sm : studyList) {
                //if(sm.getStudyInstanceUID().equals(studyUID)) {
                jsonObj.put("pat_ID", patID);
                jsonObj.put("pat_Name", sm.getPatientName());
                jsonObj.put("pat_Birthdate", sm.getPatientBirthDate());
                jsonObj.put("accNumber", sm.getAccessionNumber());
                jsonObj.put("studyDate", sm.getStudyDate());
                jsonObj.put("studyDesc", sm.getStudyDescription());
                jsonObj.put("modality", sm.getModalitiesInStudy());
                jsonObj.put("totalIns", sm.getStudyRelatedInstances());
                jsonObj.put("studyUID", sm.getStudyInstanceUID());
                jsonObj.put("refPhysician", sm.getPhysicianName());
                jsonObj.put("totalSeries", sm.getStudyRelatedSeries());
                jsonObj.put("pat_gender", sm.getPatientGender());
                jsonObj.put("serverURL", serverURL);
                jsonObj.put("dicomURL", dcmURL);
                jsonObj.put("bgColor", "rgb(0, 0, 0)");
                //break;
                //}
            }
        } catch (Exception e) {
            log.error(e);
        }
    } else {
        try {
            jsonObj.put("error", "Server not found");
        } catch (JSONException ex) {
            log.error(ex);
        }
    }

    out.print(jsonObj);
}

From source file:org.shareok.data.lawlibrary.LawLibDataHandlerImpl.java

/**
 * Many pdf files end with .pdf.pdf; in addition, the uppercase and lowercase are messy
 *//*from  www  .j a v a  2 s.  c o m*/
public void getPdfFileListFromCleanedOutputPathFiles() {
    File pdfFolder = new File(outputFilePath);
    File[] pdfFlist = pdfFolder.listFiles();
    for (File file : pdfFlist) {
        String name = file.getName();
        String parent = file.getParent();
        if (file.getPath().toLowerCase().endsWith(".pdf")) {
            String nameWithoutExtension = DocumentProcessorUtil.getFileNameWithoutExtension(name);
            if (nameWithoutExtension.toLowerCase().endsWith(".pdf")) {
                nameWithoutExtension = nameWithoutExtension.replaceAll(".pdf", "");
                nameWithoutExtension = nameWithoutExtension.replaceAll(".PDF", "");
            }
            pdfFileList.add(nameWithoutExtension + ".pdf");
            file.renameTo(new File(parent + File.separator + nameWithoutExtension + ".pdf"));
            //file.renameTo(new File(".PDF"));
        }
    }
}

From source file:com.elasticgrid.examples.video.MencoderEncoder.java

public File convertVideo(File original, String destName, String format, int width, int height, Integer start,
        Integer end, int vbr, int abr, int fps) throws VideoConversionException, InterruptedException {
    File videoConverted = new File(original.getParent(), destName);

    logger.log(Level.FINE, "Converting video {0} into {1} as {2} format...",
            new Object[] { original, videoConverted, format });

    String command = String.format("%s %s -ofps %d -of lavf"
            + " -ovc lavc -lavcopts vcodec=%s:vbitrate=%d:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=%d:%d"
            + " -oac mp3lame -lameopts cbr:br=%d -srate 22050 -o %s", encoderLocation,
            original.getAbsolutePath(), fps, format, vbr, width, height, abr, videoConverted.getAbsolutePath());
    if (start != null && end != null)
        command = String.format("%s -ss %d -endpos %d", command, start, end);

    logger.info("Command is: " + command);

    // run the external conversion program
    File log = new File(videoConverted.getParent(), videoConverted.getName().replace(format, "log"));
    logger.info("Writing output into " + log.getAbsolutePath());
    FileWriter fileWriter = null;
    try {/* ww w . ja v a 2  s .  c o m*/
        fileWriter = enableLog ? new FileWriter(log) : null;
        logger.log(Level.FINEST, "Created log file in {0}", log);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Can't open log file. Skipping...", e);
        fileWriter = null;
    }
    try {
        logger.finest(command);
        final Writer logWriter = enableLog ? new BufferedWriter(fileWriter) : null;
        final Process process = Runtime.getRuntime().exec(command);
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        process.waitFor();
        return videoConverted;
    } catch (IOException e) {
        throw new VideoConversionException("Can't run video conversion software", e);
    } finally {
        if (enableLog)
            IOUtils.closeQuietly(fileWriter);
    }
}

From source file:com.all.downloader.p2p.phexcore.helper.ShareHelper.java

void addFileDirectory(ShareFile shareFile) {
    File systemFile = shareFile.getSystemFile();
    String directoryName = systemFile.getParent();

    Setting<Set<String>> sharedDirectories = getSharedDirectories();
    Set<String> sharedDirs = sharedDirectories.get();

    if (sharedDirs.contains(directoryName)) {
        log.debug(//from  w ww.java2 s.c  om
                "The directory for file: " + shareFile.getFileName() + " is already set on : " + directoryName);
        return;
    }

    File directory = createDirectoryToShare(directoryName);
    boolean success = shareDirRecursive(directory);
    if (success) {
        LibraryPrefs.save(true);
    }
}

From source file:isl.FIMS.utils.Utils.java

/**
 * Unzip it (This implementation works only when zip contains files-folders
 * with ASCII filenames Greek characters break the code!
 *
 * @param zipFile input zip file/*from  w w w. j  a v  a  2s  .c  o m*/
 * @param output zip file output folder
 */
public static void unzip(String zipFile, String outputFolder) {

    String rootFolderName = "";
    String rootFlashFilename = "";
    byte[] buffer = new byte[1024];

    try {

        //get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(outputFolder + File.separator + zipFile));
        //get the zipped file list entry

        ZipEntry ze = zis.getNextEntry();

        boolean rootDirFound = false;
        boolean flashFileFound = false;
        while (ze != null) {

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            if (!ze.getName().contains("__MACOSX")) {
                if (ze.isDirectory()) {
                    if (rootDirFound == false) {
                        rootFolderName = newFile.getName();
                        rootDirFound = true;
                    }
                    new File(newFile.getParent()).mkdirs();
                } else {
                    FileOutputStream fos = null;

                    new File(newFile.getParent()).mkdirs();

                    if (flashFileFound == false && newFile.getName().endsWith(".swf")
                            && !newFile.getName().startsWith(".")) {
                        rootFlashFilename = newFile.getName();
                        flashFileFound = true;
                    }

                    fos = new FileOutputStream(newFile);

                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }

                    fos.close();
                }
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:net.sf.jabref.exporter.SaveSession.java

public void commit(File file) throws SaveException {
    if (file == null) {
        return;/*from w  w  w  .j a v a 2 s .com*/
    }
    if (file.exists() && backup) {
        String name = file.getName();
        String path = file.getParent();
        File backupFile = new File(path, name + GUIGlobals.BACKUP_EXTENSION);
        try {
            FileUtil.copyFile(file, backupFile, true);
        } catch (IOException ex) {
            LOGGER.error("Problem copying file", ex);
            throw SaveException.BACKUP_CREATION;
        }
    }
    try {
        if (useLockFile) {
            try {
                if (createLockFile(file)) {
                    // Oops, the lock file already existed. Try to wait it out:
                    if (!FileBasedLock.waitForFileLock(file, 10)) {
                        throw SaveException.FILE_LOCKED;
                    }

                }
            } catch (IOException ex) {
                LOGGER.error("Error when creating lock file.", ex);
            }
        }

        FileUtil.copyFile(tmp, file, true);
    } catch (IOException ex2) {
        // If something happens here, what can we do to correct the problem? The file is corrupted, but we still
        // have a clean copy in tmp. However, we just failed to copy tmp to file, so it's not likely that
        // repeating the action will have a different result.
        // On the other hand, our temporary file should still be clean, and won't be deleted.
        throw new SaveException("Save failed while committing changes: " + ex2.getMessage(),
                Localization.lang("Save failed while committing changes: %0", ex2.getMessage()));
    } finally {
        if (useLockFile) {
            deleteLockFile(file);
        }
    }
    if (!tmp.delete()) {
        LOGGER.info("Cannot delete temporary file");
    }
}

From source file:dkpro.similarity.uima.io.CloughCorpusReader.java

@Override
public List<CombinationPair> getAlignedPairs() throws ResourceInitializationException {
    List<CombinationPair> pairs = new ArrayList<CombinationPair>();

    List<File> answerFiles = listFiles(inputDir, "g", false);
    for (File answerFile : answerFiles) {
        try {//from   w w  w. ja  v a 2  s .  c o  m
            String answer = FileUtils.readFileToString(answerFile);

            String task = answerFile.getName().substring(answerFile.getName().length() - 5,
                    answerFile.getName().length() - 4);

            File originalFile = new File(answerFile.getParent() + "/orig_task" + task + ".txt");
            String original = FileUtils.readFileToString(originalFile);

            CombinationPair pair = new CombinationPair(inputDir.getAbsolutePath());
            pair.setID1(answerFile.getName().substring(0, answerFile.getName().length() - 4));
            pair.setID2(originalFile.getName().substring(0, originalFile.getName().length() - 4));
            pair.setText1(answer);
            pair.setText2(original);

            pairs.add(pair);
        } catch (IOException e) {
            throw new ResourceInitializationException(e);
        }
    }

    return pairs;
}

From source file:net.lightbody.bmp.proxy.jetty.util.RolloverFileOutputStream.java

private synchronized void setFile() throws IOException {
    // Check directory
    File file = new File(_filename);
    _filename = file.getCanonicalPath();
    file = new File(_filename);
    File dir = new File(file.getParent());
    if (!dir.isDirectory() || !dir.canWrite())
        throw new IOException("Cannot write log directory " + dir);

    Date now = new Date();

    // Is this a rollover file?
    String filename = file.getName();
    int i = filename.toLowerCase().indexOf(YYYY_MM_DD);
    if (i >= 0) {
        file = new File(dir, filename.substring(0, i) + _fileDateFormat.format(now)
                + filename.substring(i + YYYY_MM_DD.length()));
    }/*from  w w  w  .  j  a  va2  s  . c  o m*/

    if (file.exists() && !file.canWrite())
        throw new IOException("Cannot write log file " + file);

    // Do we need to change the output stream?
    if (out == null || !file.equals(_file)) {
        // Yep
        _file = file;
        if (!_append && file.exists())
            file.renameTo(new File(file.toString() + "." + _fileBackupFormat.format(now)));
        OutputStream oldOut = out;
        out = new FileOutputStream(file.toString(), _append);
        if (oldOut != null)
            oldOut.close();
        if (log.isDebugEnabled())
            log.debug("Opened " + _file);
    }
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

private File getFile(boolean write) throws IOException {
    String path = getPath();//from  ww w .j ava 2  s.  c o  m
    boolean reset = !seen.contains(path);
    seen.add(path);

    File file = new File(path);
    File parentFolder = new File(file.getParent());
    parentFolder.mkdirs();
    if (write && reset && file.exists())
        file.delete();
    if (!file.exists()) {
        file.createNewFile();
        FileOutputStream st = new FileOutputStream(file);
        st.write("<?xml version=\"1.0\"?>\n<responses>\n</responses>".getBytes("UTF-8"));
        st.flush();
        st.close();
    }
    return file;
}