Example usage for org.apache.commons.io FilenameUtils getFullPath

List of usage examples for org.apache.commons.io FilenameUtils getFullPath

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils getFullPath.

Prototype

public static String getFullPath(String filename) 

Source Link

Document

Gets the full path from a full filename, which is the prefix + path.

Usage

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

@Nullable
protected String getLocalizedTemplateContent(Resources resources, String defaultTemplateName, String locale) {
    String localizedTemplate = FilenameUtils.getFullPath(defaultTemplateName)
            + FilenameUtils.getBaseName(defaultTemplateName) + "_" + locale + "."
            + FilenameUtils.getExtension(defaultTemplateName);

    return resources.getResourceAsString(localizedTemplate);
}

From source file:ching.icecreaming.action.ViewAction.java

@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"),
        @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"),
        @Result(name = "error", location = "error.jsp") })
public String execute() throws Exception {
    Enumeration enumerator = null;
    String[] array1 = null, array2 = null;
    int int1 = -1, int2 = -1, int3 = -1;
    InputStream inputStream1 = null;
    OutputStream outputStream1 = null;
    java.io.File file1 = null, file2 = null, dir1 = null;
    List<File> files = null;
    HttpHost httpHost1 = null;/*from  w  ww  .  jav a 2s.c o m*/
    HttpGet httpGet1 = null, httpGet2 = null;
    HttpPut httpPut1 = null;
    URI uri1 = null;
    URL url1 = null;
    DefaultHttpClient httpClient1 = null;
    URIBuilder uriBuilder1 = null, uriBuilder2 = null;
    HttpResponse httpResponse1 = null, httpResponse2 = null;
    HttpEntity httpEntity1 = null, httpEntity2 = null;
    List<NameValuePair> nameValuePair1 = null;
    String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN;
    XMLConfiguration xmlConfiguration = null;
    List<HierarchicalConfiguration> list1 = null, list2 = null;
    HierarchicalConfiguration hierarchicalConfiguration2 = null;
    DataModel1 dataModel1 = null;
    DataModel2 dataModel2 = null;
    List<DataModel1> listObject1 = null, listObject3 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    org.joda.time.Period period1 = null;
    PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears()
            .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years")))
            .appendSeparator(" ").appendMonths()
            .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months")))
            .appendSeparator(" ").appendWeeks()
            .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks")))
            .appendSeparator(" ").appendDays()
            .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days")))
            .appendSeparator(" ").appendHours()
            .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours")))
            .appendSeparator(" ").appendMinutes()
            .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes")))
            .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2)
            .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds")))
            .printZeroNever().toFormatter();
    if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) {
        urlString = portletPreferences.getValue("urlString", "/");
        wsType = portletPreferences.getValue("wsType", "folder");
    }
    Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties");
    timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID());
    enumerator = portletPreferences.getNames();
    if (enumerator.hasMoreElements()) {
        array1 = portletPreferences.getValues("server", null);
        if (array1 != null) {
            if (ArrayUtils.isNotEmpty(array1)) {
                for (int1 = 0; int1 < array1.length; int1++) {
                    switch (int1) {
                    case 0:
                        sid = array1[int1];
                        break;
                    case 1:
                        uid = array1[int1];
                        break;
                    case 2:
                        pid = array1[int1];
                        break;
                    case 3:
                        alias1 = array1[int1];
                        break;
                    default:
                        break;
                    }
                }
                sid = new String(Base64.decodeBase64(sid.getBytes()));
                uid = new String(Base64.decodeBase64(uid.getBytes()));
                pid = new String(Base64.decodeBase64(pid.getBytes()));
            }
            return1 = INPUT;
        } else {
            return1 = LOGIN;
        }
    } else {
        return1 = LOGIN;
    }

    if (StringUtils.equals(urlString, "/")) {

        if (listObject1 != null) {
            listObject1.clear();
        }
        if (session.containsKey("breadcrumbs")) {
            session.remove("breadcrumbs");
        }
    } else {
        array2 = StringUtils.split(urlString, "/");
        listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs")
                : new ArrayList<DataModel1>();
        int2 = array2.length - listObject1.size();
        if (int2 > 0) {
            listObject1.add(new DataModel1(urlString, label1));
        } else {
            int2 += listObject1.size();
            for (int1 = listObject1.size() - 1; int1 >= int2; int1--) {
                listObject1.remove(int1);
            }
        }
        session.put("breadcrumbs", listObject1);
    }
    switch (wsType) {
    case "folder":
        break;
    case "reportUnit":
        try {
            dateTime1 = new org.joda.time.DateTime();
            return1 = INPUT;
            httpClient1 = new DefaultHttpClient();
            if (StringUtils.equals(button1, getText("Print"))) {
                nameValuePair1 = new ArrayList<NameValuePair>();
                if (listObject2 != null) {
                    if (listObject2.size() > 0) {
                        for (DataModel2 dataObject2 : listObject2) {
                            listObject3 = dataObject2.getOptions();
                            if (listObject3 == null) {
                                string2 = dataObject2.getValue1();
                                if (StringUtils.isNotBlank(string2))
                                    nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2));
                            } else {
                                for (int1 = listObject3.size() - 1; int1 >= 0; int1--) {
                                    dataModel1 = (DataModel1) listObject3.get(int1);
                                    string2 = dataModel1.getString2();
                                    if (StringUtils.isNotBlank(string2))
                                        nameValuePair1
                                                .add(new BasicNameValuePair(dataObject2.getId(), string2));
                                }
                            }
                        }
                    }
                }
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                if (StringUtils.isBlank(format1))
                    format1 = "pdf";
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1);
                if (StringUtils.isNotBlank(locale2)) {
                    nameValuePair1.add(new BasicNameValuePair("userLocale", locale2));
                }
                if (StringUtils.isNotBlank(page1)) {
                    if (NumberUtils.isNumber(page1)) {
                        nameValuePair1.add(new BasicNameValuePair("page", page1));
                    }
                }
                if (nameValuePair1.size() > 0) {
                    uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8"));
                }
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                if (int1 == HttpStatus.SC_OK) {
                    string3 = System.getProperty("java.io.tmpdir") + File.separator
                            + httpServletRequest.getSession().getId();
                    dir1 = new File(string3);
                    if (!dir1.exists()) {
                        dir1.mkdir();
                    }
                    httpEntity1 = httpResponse1.getEntity();
                    file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1);
                    if (StringUtils.equalsIgnoreCase(format1, "html")) {
                        result1 = EntityUtils.toString(httpEntity1);
                        FileUtils.writeStringToFile(file1, result1);
                        array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\"");
                        if (ArrayUtils.isNotEmpty(array1)) {
                            dir1 = new File(
                                    string3 + File.separator + FilenameUtils.getBaseName(file1.getName()));
                            if (dir1.exists()) {
                                FileUtils.deleteDirectory(dir1);
                            }
                            file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            if (file2.exists()) {
                                if (FileUtils.deleteQuietly(file2)) {
                                }
                            }
                            for (int2 = 0; int2 < array1.length; int2++) {
                                try {
                                    string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/"
                                            + StringUtils.substringAfter(array1[int2], "/");
                                    uriBuilder1.setPath(string2);
                                    uri1 = uriBuilder1.build();
                                    httpGet1 = new HttpGet(uri1);
                                    httpResponse1 = httpClient1.execute(httpGet1);
                                    int1 = httpResponse1.getStatusLine().getStatusCode();
                                } finally {
                                    if (int1 == HttpStatus.SC_OK) {
                                        try {
                                            string2 = StringUtils.substringBeforeLast(array1[int2], "/");
                                            dir1 = new File(string3 + File.separator + string2);
                                            if (!dir1.exists()) {
                                                dir1.mkdirs();
                                            }
                                            httpEntity1 = httpResponse1.getEntity();
                                            inputStream1 = httpEntity1.getContent();
                                        } finally {
                                            string1 = StringUtils.substringAfterLast(array1[int2], "/");
                                            file2 = new File(string3 + File.separator + string2, string1);
                                            outputStream1 = new FileOutputStream(file2);
                                            IOUtils.copy(inputStream1, outputStream1);
                                        }
                                    }
                                }
                            }
                            outputStream1 = new FileOutputStream(
                                    FilenameUtils.getFullPath(file1.getAbsolutePath())
                                            + FilenameUtils.getBaseName(file1.getName()) + ".zip");
                            ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory()
                                    .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1);
                            archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName()));
                            IOUtils.copy(new FileInputStream(file1), archiveOutputStream1);
                            archiveOutputStream1.closeArchiveEntry();
                            dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath())
                                    + FilenameUtils.getBaseName(file1.getName()));
                            files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE,
                                    TrueFileFilter.INSTANCE);
                            for (File file3 : files) {
                                archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils
                                        .substringAfter(file3.getCanonicalPath(), string3 + File.separator)));
                                IOUtils.copy(new FileInputStream(file3), archiveOutputStream1);
                                archiveOutputStream1.closeArchiveEntry();
                            }
                            archiveOutputStream1.close();
                        }
                        bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false);
                        string4 = bugfixGateIn
                                ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=",
                                        portletRequest.getContextPath(),
                                        httpServletRequest.getSession().getId())
                                : String.format("<img src=\"%s/namespace1/file-link?fileName=",
                                        portletRequest.getContextPath());
                        result1 = StringUtils.replace(result1, "<img src=\"", string4);
                    } else {
                        inputStream1 = httpEntity1.getContent();
                        outputStream1 = new FileOutputStream(file1);
                        IOUtils.copy(inputStream1, outputStream1);
                        result1 = file1.getAbsolutePath();
                    }
                    return1 = SUCCESS;
                } else {
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                }
                dateTime2 = new org.joda.time.DateTime();
                period1 = new Period(dateTime1, dateTime2.plusSeconds(1));
                message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1);
            } else {
                url1 = new URL(sid);
                uriBuilder1 = new URIBuilder(sid);
                uriBuilder1.setUserInfo(uid, pid);
                uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls");
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int1 = httpResponse1.getStatusLine().getStatusCode();
                switch (int1) {
                case HttpStatus.SC_NO_CONTENT:
                    break;
                case HttpStatus.SC_OK:
                    httpEntity1 = httpResponse1.getEntity();
                    if (httpEntity1 != null) {
                        inputStream1 = httpEntity1.getContent();
                        if (inputStream1 != null) {
                            xmlConfiguration = new XMLConfiguration();
                            xmlConfiguration.load(inputStream1);
                            list1 = xmlConfiguration.configurationsAt("inputControl");
                            if (list1.size() > 0) {
                                listObject2 = new ArrayList<DataModel2>();
                                for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) {
                                    string2 = hierarchicalConfiguration1.getString("type");
                                    dataModel2 = new DataModel2();
                                    dataModel2.setId(hierarchicalConfiguration1.getString("id"));
                                    dataModel2.setLabel1(hierarchicalConfiguration1.getString("label"));
                                    dataModel2.setType1(string2);
                                    dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory"));
                                    dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly"));
                                    dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible"));
                                    switch (string2) {
                                    case "bool":
                                    case "singleValueText":
                                    case "singleValueNumber":
                                    case "singleValueDate":
                                    case "singleValueDatetime":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        dataModel2.setValue1(hierarchicalConfiguration2.getString("value"));
                                        break;
                                    case "singleSelect":
                                    case "singleSelectRadio":
                                    case "multiSelect":
                                    case "multiSelectCheckbox":
                                        hierarchicalConfiguration2 = hierarchicalConfiguration1
                                                .configurationAt("state");
                                        list2 = hierarchicalConfiguration2.configurationsAt("options.option");
                                        if (list2.size() > 0) {
                                            listObject3 = new ArrayList<DataModel1>();
                                            for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) {
                                                dataModel1 = new DataModel1(
                                                        hierarchicalConfiguration3.getString("label"),
                                                        hierarchicalConfiguration3.getString("value"));
                                                if (hierarchicalConfiguration3.getBoolean("selected")) {
                                                    dataModel2.setValue1(
                                                            hierarchicalConfiguration3.getString("value"));
                                                }
                                                listObject3.add(dataModel1);
                                            }
                                            dataModel2.setOptions(listObject3);
                                        }
                                        break;
                                    default:
                                        break;
                                    }
                                    listObject2.add(dataModel2);
                                }
                            }
                        }
                    }
                    break;
                default:
                    addActionError(String.format("%s %d: %s", getText("Error"), int1,
                            getText(Integer.toString(int1))));
                    break;
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
                uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString);
                uri1 = uriBuilder1.build();
                httpGet1 = new HttpGet(uri1);
                httpResponse1 = httpClient1.execute(httpGet1);
                int2 = httpResponse1.getStatusLine().getStatusCode();
                if (int2 == HttpStatus.SC_OK) {
                    httpEntity1 = httpResponse1.getEntity();
                    inputStream1 = httpEntity1.getContent();
                    xmlConfiguration = new XMLConfiguration();
                    xmlConfiguration.load(inputStream1);
                    list1 = xmlConfiguration.configurationsAt("resourceDescriptor");
                    for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) {
                        if (StringUtils.equalsIgnoreCase(
                                StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) {
                            if (map1 == null)
                                map1 = new HashMap<String, String>();
                            string2 = StringUtils.substringBetween(
                                    StringUtils.substringAfter(
                                            hierarchicalConfiguration4.getString("[@uriString]"), "_files/"),
                                    "_", ".properties");
                            map1.put(string2,
                                    StringUtils.isBlank(string2) ? getText("Default") : getText(string2));
                        }
                    }
                }
                if (httpEntity1 != null) {
                    EntityUtils.consume(httpEntity1);
                }
            }
        } catch (IOException | ConfigurationException | URISyntaxException exception1) {
            exception1.printStackTrace();
            addActionError(exception1.getLocalizedMessage());
            httpGet1.abort();
            return ERROR;
        } finally {
            httpClient1.getConnectionManager().shutdown();
            IOUtils.closeQuietly(inputStream1);
        }
        break;
    default:
        addActionError(getText("This.file.type.is.not.supported"));
        break;
    }
    if (return1 != LOGIN) {
        sid = new String(Base64.encodeBase64(sid.getBytes()));
        uid = new String(Base64.encodeBase64(uid.getBytes()));
        pid = new String(Base64.encodeBase64(pid.getBytes()));
    }
    return return1;
}

From source file:MSUmpire.PSMDataStructure.LCMSID.java

private void ExportPepIonCSV(String folder) throws IOException {
    if (folder == null | "".equals(folder)) {
        folder = FilenameUtils.getFullPath(mzXMLFileName);
    }// w  w w  . java 2  s  . co m

    Logger.getRootLogger().info("Writing PepIon result to file:" + folder
            + FilenameUtils.getBaseName(mzXMLFileName) + "_PepIonIDs.csv...");
    FileWriter writer = new FileWriter(folder + FilenameUtils.getBaseName(mzXMLFileName) + "_PepIonIDs.csv");
    writer.write(
            "PepIndex,Sequence,ModSeq,TPPModSeq,IsNonDegenerate,Charge,mz,IDRT,PeakRT,NoPSMs,MS1ClusIndex,MS2ClusIndex,PeakScore,PeakHeight1,PeakHeight2,PeakHeight3,PeakArea1,PeakArea2,PeakArea3\n");
    for (PepIonID pepion : PepIonList.values()) {
        writer.write(pepion.Index + "," + pepion.Sequence + "," + pepion.ModSequence + "," + pepion.TPPModSeq
                + "," + (pepion.Is_NonDegenerate ? 1 : 0) + "," + pepion.Charge + ","
                + pepion.NeutralPrecursorMz() + "," + pepion.GetIDRT() + "," + pepion.PeakRT + ","
                + pepion.GetSpectralCount() + "," + pepion.GetMS1ClusIndex() + "," + pepion.GetMS2ClusIndex()
                + "," + pepion.PeakClusterScore + "," + pepion.PeakHeight[0] + "," + pepion.PeakHeight[1] + ","
                + pepion.PeakHeight[2] + "," + pepion.PeakArea[0] + "," + pepion.PeakArea[1] + ","
                + pepion.PeakArea[2] + "\n");
    }
    writer.close();
}

From source file:net.pms.util.SubtitleUtils.java

/**
 * Converts ASS/SSA subtitles to 3D ASS/SSA subtitles.
 * Based on https://bitbucket.org/r3pek/srt2ass3d
 *
 * @param tempSubs Subtitles file to convert
 * @param media Information about video/* w w w . j  av a 2 s  .com*/
 * @return Converted subtitles file
 * @throws IOException
 */
public static File convertASSToASS3D(File tempSubs, DLNAMediaInfo media, OutputParams params)
        throws IOException, NullPointerException {
    File outputSubs = new File(FilenameUtils.getFullPath(tempSubs.getPath()),
            FilenameUtils.getBaseName(tempSubs.getName()) + "_3D.ass");
    StringBuilder outputString = new StringBuilder();
    Charset subsFileCharset = FileUtil.getFileCharset(tempSubs);
    if (subsFileCharset == null) {
        subsFileCharset = StandardCharsets.UTF_8;
    }
    BufferedWriter output;
    Mode3D mode3D = media.get3DLayout();
    boolean isOU = mode3D == Mode3D.OUL || mode3D == Mode3D.OUR || mode3D == Mode3D.HOUL;
    boolean isSBS = mode3D == Mode3D.SBSL || mode3D == Mode3D.SBSR || mode3D == Mode3D.HSBSL;
    if (mode3D == null) {
        LOGGER.debug("The 3D layout not recognized for the 3D video");
        throw new NullPointerException("The 3D layout not recognized for the 3D video");
    }

    int depth3D = configuration.getDepth3D();
    Pattern timePattern = Pattern.compile("[0-9]:[0-9]{2}:[0-9]{2}.[0-9]{2},[0-9]:[0-9]{2}:[0-9]{2}.[0-9]{2},");
    try (BufferedReader input = new BufferedReader(
            new InputStreamReader(new FileInputStream(tempSubs), subsFileCharset))) {
        output = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputSubs), Charset.forName(CHARSET_UTF_8)));
        String line;
        outputString.append("[Script Info]\n");
        outputString.append("ScriptType: v4.00+\n");
        outputString.append("Collisions: Normal\n");
        outputString.append("PlayResX: ").append("384\n");
        outputString.append("PlayResY: ").append("288\n");
        outputString.append("ScaledBorderAndShadow: yes\n");
        outputString.append("PlayDepth: 0\n");
        outputString.append("Timer: 100.0\n");
        outputString.append("WrapStyle: 0\n\n");
        outputString.append("[V4+ Styles]\n");
        outputString.append(
                "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n");
        String fontScaleX = "1";
        String fontScaleY = "1";
        if (isOU) {
            fontScaleX = Double.toString(100 * Double.parseDouble(configuration.getAssScale()));
            fontScaleY = Double.toString((100 * Double.parseDouble(configuration.getAssScale())) / 2);
        } else if (isSBS) {
            fontScaleX = Double.toString((100 * Double.parseDouble(configuration.getAssScale())) / 2);
            fontScaleY = Double.toString(100 * Double.parseDouble(configuration.getAssScale()));
        }

        String primaryColour = convertColourToASSColourString(configuration.getSubsColor());
        String outline = configuration.getAssOutline();
        String shadow = configuration.getAssShadow();
        outputString.append("Style: Default,Arial,").append("15").append(",").append(primaryColour)
                .append(",&H000000FF,&H00000000,&H00000000,0,0,0,0,").append(fontScaleX).append(",")
                .append(fontScaleY).append(",0,0,1,").append(outline).append(",").append(shadow);
        if (isOU) {
            outputString.append(",2,15,15,15,0\n\n");
        } else if (isSBS) {
            outputString.append(",2,0,0,15,0\n\n");
        }

        outputString.append("[Events]\n");
        outputString
                .append("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\n");
        output.write(outputString.toString());
        int textPosition = 0;
        while ((line = input.readLine()) != null) {
            if (line.startsWith("[Events]")) {
                line = input.readLine();
                if (line != null && line.startsWith("Format:")) {
                    String[] formatPattern = line.split(",");
                    int i = 0;
                    for (String component : formatPattern) {
                        if (component.trim().equals("Text")) {
                            textPosition = i;
                        }
                        i++;
                    }
                }
            }

            outputString.setLength(0);
            if (line != null && line.startsWith("Dialogue:") && line.contains("Default")) { // TODO: For now convert only Default style. For other styles must be position and font size recalculated
                String[] dialogPattern = line.split(",");
                String text = StringUtils.join(dialogPattern, ",", textPosition, dialogPattern.length);
                Matcher timeMatcher = timePattern.matcher(line);
                if (timeMatcher.find()) {
                    if (isOU) {
                        outputString.append("Dialogue: 0,").append(timeMatcher.group()).append("Default,,");
                        if (depth3D > 0) {
                            outputString.append("0000,").append(String.format("%04d,", depth3D));
                        } else if (depth3D < 0) {
                            outputString.append(String.format("%04d,", -depth3D)).append("0000,");
                        } else {
                            outputString.append("0000,0000,");
                        }

                        outputString.append(String.format("%04d,,", 159)).append(text).append("\n")
                                .append("Dialogue: 0,").append(timeMatcher.group())
                                .append("Default,,0000,0000,0000,,").append(text).append("\n");
                    } else if (isSBS) {
                        outputString.append("Dialogue: 0,").append(timeMatcher.group()).append("Default,,")
                                .append("0000,").append(String.format("%04d,", 192 - depth3D)).append("0000,")
                                .append(text).append("\n").append("Dialogue: 0,").append(timeMatcher.group())
                                .append("Default,,").append(String.format("%04d,", 192 - depth3D))
                                .append("0000,0000,").append(text).append("\n");
                    }
                }

                output.write(outputString.toString());
            }
        }
    }

    LOGGER.debug("Subtitles converted to 3DASS format and stored in the file: " + outputSubs.getName());
    output.flush();
    output.close();
    tempSubs.deleteOnExit();
    return outputSubs;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.io.ResourceCollectionReaderBase.java

/**
 * Initialize the {@link DocumentMetaData}. This must be called before setting the document
 * text, otherwise the end feature of this annotation will not be set correctly.
 *//* w w w. j a v a  2s .  c o m*/
protected void initCas(CAS aCas, Resource aResource, String aQualifier) {
    boolean singleLocation = patterns == null;

    String qualifier = aQualifier != null ? "#" + aQualifier : "";
    try {
        // Set the document metadata
        DocumentMetaData docMetaData = DocumentMetaData.create(aCas);
        docMetaData.setDocumentTitle(new File(aResource.getPath()).getName());
        docMetaData.setDocumentUri(aResource.getResolvedUri().toString() + qualifier);
        docMetaData.setDocumentId(aResource.getPath() + qualifier);
        if (aResource.getBase() != null) {
            if (singleLocation) {
                // If it was a single location, then use the parent folder as base
                String base = FilenameUtils.getFullPath(aResource.getResolvedBase());
                docMetaData.setDocumentBaseUri(base);
                docMetaData.setCollectionId(base);
            } else {
                docMetaData.setDocumentBaseUri(aResource.getResolvedBase());
                docMetaData.setCollectionId(aResource.getResolvedBase());
            }
        }

        // Set the document language
        aCas.setDocumentLanguage(language);
    } catch (CASException e) {
        // This should not happen.
        throw new RuntimeException(e);
    }
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakBase.java

public void ExportPeakClusterRegionTXT() throws IOException {
    FileWriter writer = new FileWriter(FilenameUtils.getFullPath(ScanCollectionName)
            + FilenameUtils.getBaseName(ScanCollectionName) + "_PeakClusterRange.txt");
    for (PeakCluster cluster : PeakClusters) {
        writer.write(cluster.startRT + "\t" + cluster.endRT + "\t" + (cluster.mz[0] + 1f) + "\t"
                + (cluster.mz[0]) + "\n");
    }//from   w  ww.  j av  a  2 s . co  m
    writer.close();
}

From source file:net.sourceforge.jencrypt.FileEncrypter.java

/**
 * Cipher the file or folder [sourceFileOrFolder] with the key [keyFile] and
 * store the ciphered files in the optional [targetFolder].
 *///  www.  j  a v a 2 s .  c  o  m
public boolean cipherFileOrFolder() throws Exception {

    final String sourceFileOrFolder = commandline.getSourceFileOrFolder();
    long fileCounter = 0;

    File sourcePath = new File(sourceFileOrFolder);

    String targetFileOrFolder = commandline.getTargetFolder();
    OutputStream os = null;

    System.out.println();

    try {

        if (commandline.getCipherMode() == Cipher.ENCRYPT_MODE) {
            /*
             * Create one wrapper for file names, sizes and permissions, and
             * one wrapper for the file contents. If no IV and salt are
             * given they will be generated using the SecureRandom class.
             */
            createCryptoWrappers(null /* initializationVector */, null /* salt */);

            if (sourcePath.isDirectory()) {

                // Get complete tree of all files and folders in sourcePath
                FolderList folderList = new FolderList(sourcePath.getPath());
                Collection<String> fileTree = folderList.getFilesAsString();
                Collection<String> folderTree = folderList.getFoldersAsString();

                if (fileTree.isEmpty()) {
                    logger.severe("Directory '" + sourcePath.getName() + "' is empty", true);
                    return false;
                }

                os = openArchiveFileAndWriteHeader(targetFileOrFolder);

                // Walk through all directories and store directory
                // structure in archive.
                for (String relativePath : folderTree) {
                    // Encrypt file and add to archive
                    encryptAndArchivePath(folderList.getArchiveTopFolder(), relativePath + File.separator, os);
                }

                // Walk through all files
                for (String relativePath : fileTree) {
                    // Encrypt file and add to archive
                    encryptAndArchivePath(folderList.getArchiveTopFolder(), relativePath, os);
                    System.out.println();
                    ++fileCounter;
                }
            } else {
                os = openArchiveFileAndWriteHeader(targetFileOrFolder);
                String fullPath = FilenameUtils.getFullPath(sourcePath.getAbsolutePath());
                encryptAndArchivePath(fullPath, sourcePath.getName(), os);
                System.out.println();
                ++fileCounter;
            }
            os.close();

        } else if (sourcePath.isFile()) {
            fileCounter = decryptArchive(sourcePath.getAbsolutePath(), targetFileOrFolder);
        }

    } catch (Exception e) {
        logger.warning("File ciphering operation failed: " + e.getMessage(), true);
        e.printStackTrace();
        return false;
    } finally {
        if (os != null)
            os.close();
    }

    System.out.println();

    String endText = (commandline.getCipherMode() == Cipher.ENCRYPT_MODE) ? "encrypted" : "decrypted";
    logger.info(fileCounter + " file(s) " + endText, true);

    return true;
}

From source file:MSUmpire.PSMDataStructure.LCMSID.java

private void ExportProtIDCSV(String folder) throws IOException {
    if (folder == null | "".equals(folder)) {
        folder = FilenameUtils.getFullPath(mzXMLFileName);
    }//  w  ww.j av a  2  s . c  om
    Logger.getRootLogger().info("Writing ProteinID result to file:" + folder
            + FilenameUtils.getBaseName(mzXMLFileName) + "_ProtIDs.csv...");
    FileWriter writer = new FileWriter(folder + FilenameUtils.getBaseName(mzXMLFileName) + "_ProtIDs.csv");
    writer.write(
            "AccNo,UniProtID,ProteinLength,ProteinGroup,IndisProt,Description,Mass,Score,Peptides,Sequence\n");
    for (ProtID protein : ProteinList.values()) {
        String pepstring = "";
        for (PepIonID pep : protein.PeptideID.values()) {
            pepstring += pep.GetKey() + ";";
        }
        String IndisProt = "";
        for (String indisprot : protein.IndisProteins) {
            IndisProt += indisprot + ";";
        }
        writer.write(protein.getAccNo() + "," + protein.UniProtID + "," + protein.ProteinLength + ","
                + protein.ProteinGroup + "," + IndisProt + "," + protein.Description + "," + protein.Mass + ","
                + protein.Probability + "," + pepstring + "," + protein.Sequence + "\n");
    }
    writer.close();
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

private void resolveMerge() throws NoWorkTreeException, GitAPIException, IOException {
    assert this.username != null;
    assert this.email != null;

    Status status = this.git.status().call();
    Map<String, StageState> conflicting = status.getConflictingStageState();

    for (String path : conflicting.keySet()) {
        StageState stageState = conflicting.get(path);
        switch (stageState) {
        case BOTH_MODIFIED: // UU
        case BOTH_ADDED: // AA
        case ADDED_BY_US: // AU
        case ADDED_BY_THEM: // UA
            // Both the local and server version have been modified
            File conflictingFile = new File(this.repoDir, path);
            String fullPath = conflictingFile.getAbsolutePath();

            // Since the local copy was modified it probably makes sense to leave it
            // since that's the copy the user has been working on. Here's my assumption...
            // a sync didn't happen, so the user opens their project and sees it's not their
            // latest changes, they accept the failure and start to fix it... finally a sync
            // happens... at this point they are probably editing this world, so when they save
            // they wouldn't even load the new file, so we should just keep the old file.

            // TODO: we should really prompt the user to resolve this conflict.
            // but that's kinda hard with the singletons... because you probably just want
            // to open both files in two different windows (editors) but we can't do that. :(

            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();

            // Append a timestamp
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-mm-dd+HH'h'MM'm'");
            String timestamp = date.format(formatter);
            File theirFile = new File(FilenameUtils.getFullPath(fullPath), FilenameUtils.getBaseName(path)
                    + " (" + timestamp + ")." + FilenameUtils.getExtension(path));

            if (conflictingFile.exists() && !theirFile.exists()) {
                Files.move(conflictingFile.toPath(), theirFile.toPath());

                String relativePath = this.repoDir.toURI().relativize(theirFile.toURI()).getPath();
                this.git.add().addFilepattern(relativePath).call();
            }/*w ww .  j av  a  2  s  . c  o  m*/

            // Recover local version
            this.git.checkout().setStage(Stage.OURS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;

        case DELETED_BY_US: // DU
            // The modified local version is already in the checkout, so it just needs to be added.
            // We need to specifically mention the file, so we can't reuse the Add () method
            this.git.add().addFilepattern(path).call();
            break;
        case DELETED_BY_THEM: // UD
            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;
        case BOTH_DELETED: // DD
            break;
        default:
            throw new IllegalArgumentException("Unknown StageState: " + stageState);
        }
    }

    RepositoryState resolvedState = this.git.getRepository().getRepositoryState();
    assert resolvedState == RepositoryState.MERGING_RESOLVED;

    // we are done resolving the merge!
    this.git.commit().setAuthor(this.username, this.email).call();

    RepositoryState safeState = this.git.getRepository().getRepositoryState();
    assert safeState == RepositoryState.SAFE;
}

From source file:MSUmpire.PSMDataStructure.LCMSID.java

private void ExportMappedPepFragmentCSV() throws IOException {
    Logger.getRootLogger().info("Writing PepFragment result to file:" + FilenameUtils.getFullPath(mzXMLFileName)
            + FilenameUtils.getBaseName(mzXMLFileName) + "_MappedPepFragments.csv...");
    FileWriter writer = new FileWriter(FilenameUtils.getFullPath(mzXMLFileName)
            + FilenameUtils.getBaseName(mzXMLFileName) + "_MappedPepFragments.csv");
    writer.write("PepIndex,IonType,fragMZ,ObservedMZ,Charge,Intensity,Correlation,PPM,ApexDelta,RTOverlapP\n");
    for (PepIonID pepion : MappedPepIonList.values()) {
        for (FragmentPeak frag : pepion.FragmentPeaks) {
            writer.write(pepion.Index + "," + frag.IonType + "," + frag.FragMZ + "," + frag.ObservedMZ + ","
                    + frag.Charge + "," + frag.intensity + "," + frag.corr + "," + frag.ppm + ","
                    + frag.ApexDelta + "," + frag.RTOverlapP + "\n");
        }//from  ww  w.  ja v  a 2s  .  c o m
    }
    writer.close();
}