Example usage for org.apache.commons.lang3 StringUtils substringsBetween

List of usage examples for org.apache.commons.lang3 StringUtils substringsBetween

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringsBetween.

Prototype

public static String[] substringsBetween(final String str, final String open, final String close) 

Source Link

Document

Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

A null input String returns null .

Usage

From source file:com.ln.methods.Parser.java

public static void parse() {
    Timeconversion.convert();//from  w w  w  .  j  a  va  2s  . c om
    Month = StringUtils.substringsBetween(source, "<month", "</month>");
}

From source file:com.ln.methods.Betaparser.java

public static void parse() {
    Timeconversion.convert();/*www.  ja v  a  2s.  c o  m*/
    source = source.replaceAll("\\s+\\n", " ").replaceAll("\\s+", " ");
    source = StringUtils.substringBetween(source, "<calendar>", "</calendar>");
    source = source.replace("hour=\"", "<H>").replace("\" minute=\"", "</H><M>").replace("\" ov", "</M>")
            .replace("er=\"1\"", "<O>1</O").replace("er=\"0\"", "<O>0</O");
    Monthnumbers = StringUtils.substringsBetween(source, "<month year=\"2012\" num=\"", "\">");
    Temp = StringUtils.substringsBetween(source, "<event", "</event>");
    for (int i = 0; i != Temp.length; i++) {
        source = source.replace("<month year=\"2012\" num=\"" + Monthnumbers[0] + "\">",
                "<mo>" + Monthnumbers[0] + "</mo>");
        if (Monthnumbers.length > 1) {
            source = source
                    .replace("<month year=\"2012\" num=\"" + Monthnumbers[1] + "\">",
                            "<mo>" + Monthnumbers[1] + "</mo>")
                    .replace("<day num=\"" + Integer.toString(i) + "\"><event ",
                            "<D>" + Integer.toString(i) + "</D>");
        } else if (Monthnumbers.length == 1) {
            source = source.replace("<day num=\"" + Integer.toString(i) + "\"><event ",
                    "<D>" + Integer.toString(i) + "</D>");
        }
    }
    Month1 = StringUtils.substringBetween(source, "<mo>" + Monthnumbers[0] + "</mo>", "</month>");
    Month1 = Month1.replace("<D>", "@<D>");
    Temp = StringUtils.substringsBetween(Month1, "@", "</day>");
    if (Monthnumbers.length > 1) {
        Month2 = StringUtils.substringBetween(source, "<mo>" + Monthnumbers[1] + "</mo>", "</month>");
        Month2 = Month2.replace("<D>", "@<D>");
        Temp2 = StringUtils.substringsBetween(Month2, "@", "</day>");
    }
    for (int i = 0; i != Temp.length; i++) {
        Temp[i] = Temp[i].replace("<H>", "<mo>" + Monthnumbers[0] + "</mo><D>"
                + StringUtils.substringBetween(Temp[i], "<D>", "</D>") + "</D><H>");
        //Remove extra day tags
        Temp[i] = Temp[i].replace("<D>" + StringUtils.substringBetween(Temp[i], "<D>", "</D>") + "</D><D>",
                "<D>");
    }
    Month1 = ArrayUtils.toString(Temp);
    if (Monthnumbers.length > 1) {
        for (int i = 0; i != Temp2.length; i++) {
            Temp2[i] = Temp2[i].replace("<H>", "<mo>" + Monthnumbers[1] + "</mo><D>"
                    + StringUtils.substringBetween(Temp2[i], "<D>", "</D>") + "</D><H>");
            //Remove extra day tags
            Temp2[i] = Temp2[i]
                    .replace("<D>" + StringUtils.substringBetween(Temp2[i], "<D>", "</D>") + "</D><D>", "<D>");
        }
        Month2 = ArrayUtils.toString(Temp2);
        source = StringUtils.join(Month1, Month2);
    } else {
        source = Month1;
    }
    for (int i = 0; i != 31; i++) {
        source = source.replace("<D>" + Integer.toString(i) + "</D><mo>", "<mo>");
    }

    Days = StringUtils.substringsBetween(source, "<D>", "</D>");
    Months = StringUtils.substringsBetween(source, "<mo>", "</mo>");
    Hours = StringUtils.substringsBetween(source, "<H>", "</H>");
    Minutes = StringUtils.substringsBetween(source, "<M>", "</M>");
    Over = StringUtils.substringsBetween(source, "<O>", "</O>");
    Title = StringUtils.substringsBetween(source, "<title>", "</title>");
    STitle = StringUtils.substringsBetween(source, "<short-title>", "</short-title>");
    Description = StringUtils.substringsBetween(source, "<description", "</description>");
    ID = StringUtils.substringsBetween(source, "<event-id>", "</event-id>");
    /*if (success(Months.length, Hours.length, Minutes.length, Over.length, Title.length, STitle.length, Description.length, ID.length))
    {
       System.out.println("SUCCESS"); 
    }else System.out.println("Something went wrong :(");
    */
    int diff = Parser.hourd;
    for (int i = 0; i != Hours.length; i++) {
        Hours[i] = Integer.toString(Integer.parseInt(Hours[i]) - diff);
    }
    for (int i = 0; i != Hours.length; i++) {
        if (Integer.parseInt(Hours[i]) < 0) {
            Hours[i] = Integer.toString(Integer.parseInt(Hours[i]) + 24);
            Days[i] = Integer.toString(Integer.parseInt(Days[i]) - 1);
        }
        if (Integer.parseInt(Hours[i]) > 24) {
            Hours[i] = Integer.toString(Integer.parseInt(Hours[i]) - 24);
            Days[i] = Integer.toString(Integer.parseInt(Days[i]) + 1);
        }
    }
    for (int i = 0; i != Days.length; i++) {
        Daysint[i] = Integer.parseInt(Days[i]);
    }
    for (int i = 0; i != Daysint.length; i++) {
        if (Daysint[i] == i) {
            DD[i]++;
        }
    }
    for (int i = 0; i != Title.length; i++) {
        if (Integer.parseInt(Days[i]) <= 0) {
            Months[i] = Integer.toString(Integer.parseInt(Months[i]) - 1);
            Days[i] = Integer.toString(Integer.parseInt(Days[i] + 31));
        }
    }
    for (int i = 0; i != Title.length; i++) {
        Events[i] = Months[i] + "|" + Days[i] + "|" + Hours[i] + "|" + Title[i] + "|" + STitle[i] + "|"
                + Description[i];
    }

}

From source file:com.ln.methods.Descparser.java

public static void parsedesc() {
    String Desc = "";
    String Title = "";
    String Hour = "";
    String Minute = "";
    String formatted[] = new String[Betaparser.Description.length];
    int selectedindex = Main.Titlebox.getSelectedIndex();
    for (int i1 = 0; i1 != Betaparser.Hours.length; i1++) {
        if (Betaparser.Events[i1].startsWith(Main.monthday)) {
            Desc = Desc + "" + Betaparser.Description[i1] + "~";
            Title = Title + "" + Betaparser.Title[i1] + "~";
            Hour = Hour + "" + Betaparser.Hours[i1] + "~";
            Minute = Minute + "" + Betaparser.Minutes[i1] + "~";
        }/*from  ww  w . j a  va  2 s .com*/
    }
    String[] Desc2 = StringUtils.substringsBetween(Desc, "", "~");
    String[] Title2 = StringUtils.substringsBetween(Title, "", "~");
    String[] Hour2 = StringUtils.substringsBetween(Hour, "", "~");
    String[] Minute2 = StringUtils.substringsBetween(Minute, "", "~");
    String[] Full = new String[Desc2.length];
    TTT = "";
    DDD = 0;
    HHH = 0;
    MMM = 0;
    for (int i = 0; i != Title2.length; i++) {
        int h = Integer.parseInt(Hour2[i]);
        int m = Integer.parseInt(Minute2[i]);
        DateFormat df = new SimpleDateFormat("dd");
        DateFormat dm = new SimpleDateFormat("MM");
        Date month = new Date();
        Date today = new Date();
        int mon = Integer.parseInt(dm.format(month));
        int d = Integer.parseInt(df.format(today));
        int dif = 0;
        int ds = 0;
        int pastd = 0;
        int pasth = 0;
        int pastm = 0;
        d = Main.sdate - d;
        h = h - Parser.hour;
        m = m - Parser.minute;
        if (d > 0) {
            ds = 1;
        }
        if (mon > Main.globmonth) {
            dif = dif + 1;
        }
        if (Main.sdate > d) {
            dif = dif + 1;
        }
        if (h < 0) {
            pasth = Math.abs(h);
        }
        if (m < 0) {
            pastm = Math.abs(m);
            h = h - 1;
            m = m + 60;
        }
        if (d < 0) {
            pastd = d;
        }
        if (d > 0 && h < 0) {
            d = d - 1;
            h = h + 24;
        }
        if (d == 0) {
            formatted[i] = "<font size=\"4\" color=\"lime\"><br><b>Starts in: "
                    + String.format("%01d Hours %01d Minutes", h, m) + "</b></font>";
        }
        if (d >= 1) {
            formatted[i] = "<font size=\"4\" color=\"lime\"><br><b>Starts in: "
                    + String.format("%01d Days %01d Hours %01d Minutes", d, h, m) + "</b></font>";
        }
        if (pastd == 0 && h < 0) {
            formatted[i] = "<font size=\"4\" color=\"#B00000\"><br><b>Event is finished/going on. Started "
                    + String.format("%01d Hours %01d Minutes", pasth, pastm) + " Ago</b></font>";
        }
        if (pastd < 0 && h < 0) {
            formatted[i] = "<font size=\"4\" color=\"#B00000\"><br><b>Event is finished/going on. Started "
                    + String.format("%01d Days %01d Hours %01d Minutes", pastd, pasth, pastm)
                    + " Ago</b></font>";
        }

    }

    for (int i = 0; i != Title2.length; i++) {
        Full[i] = Title2[i];

    }

    try {
        if (Desc2[selectedindex] != null) {
            StringBuilder sb = new StringBuilder(Desc2[selectedindex]);
            int i = 0;
            while ((i = sb.indexOf(" ", i + 50)) != -1) {
                //   sb.replace(i, i + 1, "<br>");
                String formatteddesc = sb.toString();
                formatteddesc = formatteddesc.replace("/forum/", "http://www.teamliquid.net/forum/");
                TextProcessor processor = BBProcessorFactory.getInstance().create();
                formatteddesc = processor.process(formatteddesc);
                formatteddesc = formatteddesc.replace("#T#", "").replace("#P#", "").replace("#Z#", "");
                formatteddesc = formatteddesc.replace("[tlpd#players", "[tlpd][cat]players[/cat]");
                formatteddesc = formatteddesc.replace("[/cat]#", "[ID]");
                formatteddesc = formatteddesc.replace("sc2-korean]", "[/ID][region]sc2-korean[/region][name]")
                        .replace("sc2-international", "[/ID][region]sc2-international[/region][name]");
                formatteddesc = formatteddesc.replace("[/tlpd]", "[/name][/tlpd]");
                String[] tlpd = StringUtils.substringsBetween(formatteddesc, "[tlpd]", "[/tlpd]");
                String[] cat = StringUtils.substringsBetween(formatteddesc, "[cat]", "[ID]");
                String[] ids = StringUtils.substringsBetween(formatteddesc, "[ID]", "[/ID]");
                String[] names = StringUtils.substringsBetween(formatteddesc, "[name]", "[/name]");
                String[] region = StringUtils.substringsBetween(formatteddesc, "[region]", "[/region]");

                try {
                    if (formatteddesc.contains("tlpd")) {
                        formatteddesc = formatteddesc.replace("[tlpd]", "").replace("[/tlpd]", "");
                        for (int i1 = 0; i1 != tlpd.length; i1++) {
                            formatteddesc = formatteddesc.replace(tlpd[i1],
                                    "<a href=\"http://www.teamliquid.net/tlpd/" + cat[i1] + "/" + region[i1]
                                            + "/" + ids[i1] + "\">" + names[i1] + "</a>");

                            //   formatteddesc = formatteddesc.replace("[tlpd]", "").replace("[/tlpd]", "");      
                        }
                    }

                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                formatteddesc = formatteddesc.replace("&lt;", "").replace("gt;", "");
                Main.Description
                        .setText((Full[selectedindex] + formatted[selectedindex] + "<br>" + formatteddesc));
                try {
                    if (formatted[selectedindex].contains("lime")) {
                        String[] notfytime = new String[formatted.length];
                        String[] form = new String[formatted.length];
                        form[selectedindex] = formatted[selectedindex].replace("Starts in: ", "$");
                        notfytime[selectedindex] = StringUtils.substringBetween(form[selectedindex], "$",
                                "</b>");
                        if (formatted[selectedindex].contains("Days")) {
                            String DD = StringUtils.substringBetween(notfytime[selectedindex], "", " Days");
                            String HH = StringUtils.substringBetween(notfytime[selectedindex], "Days ",
                                    " Hours");
                            String MM = StringUtils.substringBetween(notfytime[selectedindex], "Hours ",
                                    " Minutes");
                            DDD = Integer.parseInt(DD);
                            HHH = Integer.parseInt(HH);
                            MMM = Integer.parseInt(MM);
                            TTT = Full[selectedindex];
                        }
                        if (!formatted[selectedindex].contains("Days")) {
                            String HH = StringUtils.substringBetween(notfytime[selectedindex], "", " Hours");
                            String MM = StringUtils.substringBetween(notfytime[selectedindex], "Hours ",
                                    " Minutes");
                            HHH = Integer.parseInt(HH);
                            MMM = Integer.parseInt(MM);
                            TTT = Full[selectedindex];
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Main.Description.setCaretPosition(0);

            }
        }

    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
    }

}

From source file:edu.illinois.cs.cogcomp.wikifier.wiki.importing.WikipediaRedirectExtractor.java

public String run(File inputFile, File outputFile) throws Exception {
    int invalidCount = 0;
    long t0 = System.currentTimeMillis();
    InputStream fis = new FileInputStream(inputFile);
    if (inputFile.getName().endsWith(".bz2"))
        fis = new BZip2InputStream(fis, false);

    BufferedReader dumpReader = new BufferedReader(new InputStreamReader(fis, "utf-8"));

    BufferedWriter redirectWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(outputFile), "utf-8"));

    String titleIdFile = outputFile + "-title-id.txt";
    BufferedWriter titleIdWriter = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(titleIdFile), "utf-8"));

    int count = 0;
    String title = null;//from  w  w  w . j a va  2  s  .  c  om
    String line = null;
    while ((line = dumpReader.readLine()) != null) {
        if (line.startsWith(titlePattern)) {
            title = cleanupTitle(line);
            continue;
        }
        if (line.startsWith(redirectPattern)) {
            String[] splits = StringUtils.substringsBetween(line, "<redirect title=\"", "\" />");
            if (splits == null || splits.length != 1) {
                invalidCount++;
                continue;
            }
            String redirectedTitle = splits[0];
            redirectedTitle = cleanupTitle(redirectedTitle);
            if (isValidAlias(title, redirectedTitle)) {
                redirectWriter.write(title + "\t" + redirectedTitle);
                redirectWriter.newLine();
                count++;
            } else {
                invalidCount++;
                System.out.println("Discarded redirect from " + title + " to " + redirectedTitle);
            }
            if (count % 100000 == 0)
                System.out.println("Processed " + (count + invalidCount) + " titles ");
        }

        if (SAVE_COMPLETE_TITLE_LIST && line.startsWith(idPattern)) {
            String[] splits = StringUtils.substringsBetween(line, "<id>", "</id>");
            if (splits == null || splits.length != 1) {
                invalidCount++;
                continue;
            }
            titleIdWriter.write(splits[0] + '\t' + title);
            titleIdWriter.newLine();
        }

    }

    dumpReader.close();
    fis.close();

    redirectWriter.close();
    titleIdWriter.close();

    System.out.println("---- Wikipedia redirect extraction done ----");
    long t1 = System.currentTimeMillis();
    // IOUtil.save( map );
    System.out.println("Discarded " + invalidCount + " redirects to wikipedia meta articles.");
    System.out.println("Extracted " + count + " redirects.");
    System.out.println("Saved output: " + outputFile.getAbsolutePath());
    System.out.println("Done in " + ((t1 - t0) / 1000) + " sec.");
    return titleIdFile;
}

From source file:mfi.staticresources.ProcessResources.java

private String deleteBetween(String content, String start, String end, String exclusionContent) {

    try {/*w  w  w  .j a v  a 2s. com*/
        String[] subs = StringUtils.substringsBetween(content, start, end);
        if (subs == null || subs.length == 0) {
            // noop
        } else {
            for (String sub : subs) {
                if (StringUtils.isNotBlank(exclusionContent)
                        && StringUtils.containsIgnoreCase(sub, exclusionContent)) {
                    // noop
                } else {
                    sub = start + sub + end;
                    content = StringUtils.replace(content, sub, "");
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return content;
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * This method is used to save the line ranges being modified in a given file to a list and add that list to the root list of
 *
 * @param fileNames   Arraylist of files names that are being affected by the relevant commit
 * @param patchString Array list having the patch string value for each of the file being changed
 *//* w w w  .  j av a  2  s  . c  o m*/

public void saveRelaventEditLineNumbers(ArrayList<String> fileNames, ArrayList<String> patchString) {
    //filtering only the line ranges that are modified and saving to a string array

    // cannot ues parallel streams here as the order of the line changes must be preserved
    patchString.stream().map(patch -> StringUtils.substringsBetween(patch, "@@ ", " @@"))
            .forEach(lineChanges -> {
                //filtering the lines ranges that existed in the previous file, that exists in the new file and saving them in to the same array
                IntStream.range(0, lineChanges.length).forEach(j -> {
                    //@@ -22,7 +22,7 @@ => -22,7 +22,7 => 22,28/22,28
                    String tempString = lineChanges[j];
                    String lineRangeInTheOldFileBeingModified = StringUtils.substringBetween(tempString, "-",
                            " +"); // for taking the authors and commit hashes of the previous lines
                    String lineRangeInTheNewFileResultedFromModification = StringUtils
                            .substringAfter(tempString, "+"); // for taking the parent commit

                    int intialLineNoInOldFile = Integer
                            .parseInt(StringUtils.substringBefore(lineRangeInTheOldFileBeingModified, ","));
                    int tempEndLineNoInOldFile = Integer
                            .parseInt(StringUtils.substringAfter(lineRangeInTheOldFileBeingModified, ","));
                    int endLineNoOfOldFile;
                    if (intialLineNoInOldFile != 0) {
                        // to filterout the newly created files
                        endLineNoOfOldFile = intialLineNoInOldFile + (tempEndLineNoInOldFile - 1);
                    } else {
                        endLineNoOfOldFile = tempEndLineNoInOldFile;
                    }
                    int intialLineNoInNewFile = Integer.parseInt(
                            StringUtils.substringBefore(lineRangeInTheNewFileResultedFromModification, ","));
                    int tempEndLineNoInNewFile = Integer.parseInt(
                            StringUtils.substringAfter(lineRangeInTheNewFileResultedFromModification, ","));
                    int endLineNoOfNewFile = intialLineNoInNewFile + (tempEndLineNoInNewFile - 1);
                    // storing the line ranges that are being modified in the same array by replacing values
                    lineChanges[j] = intialLineNoInOldFile + "," + endLineNoOfOldFile + "/"
                            + intialLineNoInNewFile + "," + endLineNoOfNewFile;
                });
                ArrayList<String> tempArrayList = new ArrayList<>(Arrays.asList(lineChanges));
                //adding to the array list which keep track of the line ranges being changed
                lineRangesChanged.add(tempArrayList);
            });
    System.out.println("done saving file names and their relevant modification line ranges");
    System.out.println(fileNames);
    System.out.println(lineRangesChanged + "\n");
}

From source file:net.launchpad.jabref.plugins.ZentralSearch.java

private Set<String> retrieveIndexIds(String page) {
    Set<String> res = new HashSet<String>();
    String[] inx = StringUtils.substringsBetween(page, "href=\"?index_=", "&amp;type_=");
    if (null != inx && inx.length > 0) {
        res.addAll(Arrays.asList(inx));
    } else {/*from www.  j  a v a  2  s .c  o m*/
        throw new RuntimeException("No resulting docs received.");
    }
    return res;
}

From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java

@Override
public String startServiceForSimultion(String serviceId, String runtimeOptions,
        Map<String, Object> simulationContext) {

    String instanceId = serviceId + "-" + new Date().getTime();
    // get execution path
    ServiceInfo serviceInfo = services.get(serviceId);
    if (serviceInfo == null) {
        //TODO: publish error on status topic
        throw new RuntimeException("Service not found: " + serviceId);
    }/* w  w w  .  j av  a 2s.c o  m*/

    // are multiple allowed? if not check to see if it is already running, if it is then fail
    if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) {
        throw new RuntimeException(
                "Service is already running and multiple instances are not allowed: " + serviceId);
    }

    File serviceDirectory = new File(
            getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId);

    ProcessBuilder processServiceBuilder = new ProcessBuilder();
    Process process = null;
    List<String> commands = new ArrayList<String>();
    Map<String, String> envVars = processServiceBuilder.environment();

    //set environment variables
    List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables();
    for (EnvironmentVariable envVar : envVarList) {
        String value = envVar.getEnvValue();
        //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null
        if (simulationContext != null) {
            if (value.contains("(")) {
                String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")");
                for (String args : replaceValue) {
                    value = value.replace("(" + args + ")", simulationContext.get(args).toString());
                }
            }
        }
        envVars.put(envVar.getEnvName(), value);
    }

    //add executation command           
    commands.add(serviceInfo.getExecution_path());

    //Check if static args contain any replacement values
    List<String> staticArgsList = serviceInfo.getStatic_args();
    for (String staticArg : staticArgsList) {
        if (staticArg != null) {
            //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null
            if (simulationContext != null) {
                if (staticArg.contains("(")) {
                    String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")");
                    for (String args : replaceArgs) {
                        staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString());
                    }
                }
            }
            commands.add(staticArg);
        }
    }

    if (runtimeOptions != null) {
        commands.add(runtimeOptions);
    }

    try {
        if (serviceInfo.getType().equals(ServiceType.PYTHON)) {

            commands.add(0, "python");
            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();

            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.EXE)) {

            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();
            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.JAVA)) {

            commands.add(0, "java -jar");
            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();
            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.WEB)) {

        } else {
            throw new RuntimeException("Type not recognized " + serviceInfo.getType());
        }
    } catch (IOException e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String sStackTrace = sw.toString(); // stack trace as a string
        System.out.println(sStackTrace);

        StringBuilder commandString = new StringBuilder();
        for (String s : commands) {
            commandString.append(s);
            commandString.append(" ");
        }

        logManager.log(
                new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                        "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true),
                GridAppsDConstants.topic_simulationLog + simulationId);
        logManager.log(
                new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace,
                        LogLevel.ERROR, ProcessStatus.ERROR, true),
                GridAppsDConstants.topic_simulationLog + simulationId);
    }

    //create serviceinstance object
    ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId,
            process);
    serviceInstance.setService_info(serviceInfo);

    //add to service instances map
    serviceInstances.put(instanceId, serviceInstance);

    return instanceId;

}

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 .j a v  a2 s  .  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:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public String startAppForSimultion(String appId, String runtimeOptions, Map simulationContext) {

    String simulationId = simulationContext.get("simulationId").toString();

    appId = appId.trim();/*w ww . j a v a 2 s. c o  m*/
    String instanceId = appId + "-" + new Date().getTime();
    // get execution path
    AppInfo appInfo = apps.get(appId);
    if (appInfo == null) {
        throw new RuntimeException("App not found: " + appId);
    }

    // are multiple allowed? if not check to see if it is already running,
    // if it is then fail
    if (!appInfo.isMultiple_instances() && listRunningApps(appId).size() > 0) {
        throw new RuntimeException("App is already running and multiple instances are not allowed: " + appId);
    }

    // build options
    // might need a standard method for replacing things like SIMULATION_ID
    // in the input/output options
    /*String optionsString = appInfo.getOptions();
    if (simulationId != null) {
       if (optionsString.contains("SIMULATION_ID")) {
    optionsString = optionsString.replace("SIMULATION_ID",
          simulationId);
       }
       if (runtimeOptions.contains("SIMULATION_ID")) {
    runtimeOptions = runtimeOptions.replace("SIMULATION_ID",
          simulationId);
       }
    }*/

    File appDirectory = new File(getAppConfigDirectory().getAbsolutePath() + File.separator + appId);

    Process process = null;
    // something like
    if (AppType.PYTHON.equals(appInfo.getType())) {
        List<String> commands = new ArrayList<String>();
        commands.add("python");
        commands.add(appInfo.getExecution_path());

        //Check if static args contain any replacement values
        List<String> staticArgsList = appInfo.getOptions();
        for (String staticArg : staticArgsList) {
            if (staticArg != null) {
                if (staticArg.contains("(")) {
                    String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")");
                    for (String args : replaceArgs) {
                        staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString());
                    }
                }
                commands.add(staticArg);
            }
        }

        if (runtimeOptions != null && !runtimeOptions.isEmpty()) {
            String runTimeString = runtimeOptions.replace(" ", "").replace("\n", "");
            commands.add(runTimeString);
        }

        ProcessBuilder processAppBuilder = new ProcessBuilder(commands);
        processAppBuilder.redirectErrorStream(true);
        processAppBuilder.redirectOutput();
        processAppBuilder.directory(appDirectory);
        logManager.log(new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                "Starting app with command " + String.join(" ", commands), LogLevel.DEBUG,
                ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId);
        try {
            process = processAppBuilder.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else if (AppType.JAVA.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else if (AppType.WEB.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else {
        throw new RuntimeException("Type not recognized " + appInfo.getType());
    }

    // create appinstance object
    AppInstance appInstance = new AppInstance(instanceId, appInfo, runtimeOptions, simulationId, simulationId,
            process);
    appInstance.setApp_info(appInfo);
    watch(appInstance);
    // add to app instances map
    appInstances.put(instanceId, appInstance);

    return instanceId;
}