Example usage for java.util.regex Pattern quote

List of usage examples for java.util.regex Pattern quote

Introduction

In this page you can find the example usage for java.util.regex Pattern quote.

Prototype

public static String quote(String s) 

Source Link

Document

Returns a literal pattern String for the specified String .

Usage

From source file:com.dattasmoon.pebble.plugin.NotificationService.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // handle the prefs changing, because of how accessibility services
    // work, sharedprefsonchange listeners don't work
    if (watchFile.lastModified() > lastChange) {
        loadPrefs();// ww w.j a  v a  2s.c o m
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal()));
    }
    // if we are off, don't do anything.
    if (mode == Mode.OFF) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications");
        }
        return;
    }

    //handle quiet hours
    if (quiet_hours) {

        Calendar c = Calendar.getInstance();
        Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                    + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
        }

        if (quiet_hours_before.after(quiet_hours_after)) {
            if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning.");
                }
                return;
            }

        } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
            }
            return;
        }

    }

    // handle if they only want notifications
    if (notifications_only) {
        if (event != null) {
            Parcelable parcelable = event.getParcelableData();
            if (!(parcelable instanceof Notification)) {

                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is not a notification and notifications only is enabled. Returning.");
                }
                return;
            }
        }
    }
    if (no_ongoing_notifs) {
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            Notification notif = (Notification) parcelable;
            if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning.");
                }
                return;
            }
        } else {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Event is not a notification.");
            }
        }
    }

    // Handle the do not disturb screen on settings
    PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn
                + "  screen=" + powMan.isScreenOn());
    }
    if (!notifScreenOn && powMan.isScreenOn()) {
        return;
    }

    if (event == null) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Event is null. Returning.");
        }
        return;
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Event: " + event.toString());
    }

    // main logic
    PackageManager pm = getPackageManager();

    String eventPackageName;
    if (event.getPackageName() != null) {
        eventPackageName = event.getPackageName().toString();
    } else {
        eventPackageName = "";
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service package list is: ");
        for (String strPackage : packages) {
            Log.i(Constants.LOG_TAG, strPackage);
        }
        Log.i(Constants.LOG_TAG, "End Service package list");
    }

    switch (mode) {
    case EXCLUDE:
        // exclude functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to exclude");
        }

        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName
                            + " which is on the exclude list. Returning.");
                }
                return;
            }
        }
        break;
    case INCLUDE:
        // include only functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to include only");
        }
        boolean found = false;
        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
            return;
        }
        break;
    }

    // get the title
    String title = "";
    try {
        boolean renamed = false;
        for (int i = 0; i < pkg_renames.length(); i++) {
            if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) {
                renamed = true;
                title = pkg_renames.getJSONObject(i).getString("to");
            }
        }
        if (!renamed) {
            title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString();
        }
    } catch (NameNotFoundException e) {
        title = eventPackageName;
    } catch (JSONException e) {
        title = eventPackageName;
    }

    // get the notification text
    String notificationText = event.getText().toString();
    // strip the first and last characters which are [ and ]
    notificationText = notificationText.substring(1, notificationText.length() - 1);

    if (notification_extras) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Fetching extras from notification");
        }
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim());
            } else {
                notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim());
            }

        }
    }

    // Check ignore lists
    for (int i = 0; i < ignores.length(); i++) {
        try {
            JSONObject ignore = ignores.getJSONObject(i);
            String app = ignore.getString("app");
            boolean exclude = ignore.optBoolean("exclude", true);
            boolean case_insensitive = ignore.optBoolean("insensitive", true);
            if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) {
                //this rule doesn't apply to all apps and this isn't the app we're looking for.
                continue;
            }
            String regex = "";
            if (case_insensitive) {
                regex += "(?i)";
            }
            if (!ignore.getBoolean("raw")) {
                regex += Pattern.quote(ignore.getString("match"));
            } else {
                regex += ignore.getString("match");
            }
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(notificationText);
            if (m.find()) {
                if (exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '"
                                + regex + "' and exclude is on. Returning");
                    }
                    return;
                }
            } else {
                if (!exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText
                                + "' does not match: '" + regex + "' and include is on. Returning");
                    }
                    return;
                }

            }
        } catch (JSONException e) {
            continue;
        }
    }

    // Send the alert to Pebble

    sendToPebble(title, notificationText);

    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, event.toString());
        Log.i(Constants.LOG_TAG, event.getPackageName().toString());
    }
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createFailureMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException, InterruptedException {
    MimeMessage msg = createEmptyMail(build, listener);

    msg.setSubject(getSubject(build, Messages.MailSender_FailureMail_Subject()), charset);

    StringBuilder buf = new StringBuilder();
    appendBuildUrl(build, buf);/*from   w w w  . j  a va  2s  .c om*/

    boolean firstChange = true;
    for (ChangeLogSet.Entry entry : build.getChangeSet()) {
        if (firstChange) {
            firstChange = false;
            buf.append(Messages.MailSender_FailureMail_Changes()).append("\n\n");
        }
        buf.append('[');
        buf.append(entry.getAuthor().getFullName());
        buf.append("] ");
        String m = entry.getMsg();
        if (m != null) {
            buf.append(m);
            if (!m.endsWith("\n")) {
                buf.append('\n');
            }
        }
        buf.append('\n');
    }

    buf.append("------------------------------------------\n");

    try {
        // Restrict max log size to avoid sending enormous logs over email.
        // Interested users can always look at the log on the web server.
        List<String> lines = build.getLog(MAX_LOG_LINES);

        String workspaceUrl = null, artifactUrl = null;
        Pattern wsPattern = null;
        String baseUrl = Mailer.descriptor().getUrl();
        if (baseUrl != null) {
            // Hyperlink local file paths to the repository workspace or build artifacts.
            // Note that it is possible for a failure mail to refer to a file using a workspace
            // URL which has already been corrected in a subsequent build. To fix, archive.
            workspaceUrl = baseUrl + Util.encode(build.getProject().getUrl()) + "ws/";
            artifactUrl = baseUrl + Util.encode(build.getUrl()) + "artifact/";
            FilePath ws = build.getWorkspace();
            // Match either file or URL patterns, i.e. either
            // c:\hudson\workdir\jobs\foo\workspace\src\Foo.java
            // file:/c:/hudson/workdir/jobs/foo/workspace/src/Foo.java
            // will be mapped to one of:
            // http://host/hudson/job/foo/ws/src/Foo.java
            // http://host/hudson/job/foo/123/artifact/src/Foo.java
            // Careful with path separator between $1 and $2:
            // workspaceDir will not normally end with one;
            // workspaceDir.toURI() will end with '/' if and only if workspaceDir.exists() at time of call
            wsPattern = Pattern.compile("(" + Pattern.quote(ws.getRemote()) + "|"
                    + Pattern.quote(ws.toURI().toString()) + ")[/\\\\]?([^:#\\s]*)");
        }
        for (String line : lines) {
            line = line.replace('\0', ' '); // shall we replace other control code? This one is motivated by http://www.nabble.com/Problems-with-NULL-characters-in-generated-output-td25005177.html
            if (wsPattern != null) {
                // Perl: $line =~ s{$rx}{$path = $2; $path =~ s!\\\\!/!g; $workspaceUrl . $path}eg;
                Matcher m = wsPattern.matcher(line);
                int pos = 0;
                while (m.find(pos)) {
                    String path = m.group(2).replace(File.separatorChar, '/');
                    String linkUrl = artifactMatches(path, build) ? artifactUrl : workspaceUrl;
                    String prefix = line.substring(0, m.start()) + '<' + linkUrl + Util.encode(path) + '>';
                    pos = prefix.length();
                    line = prefix + line.substring(m.end());
                    // XXX better style to reuse Matcher and fix offsets, but more work
                    m = wsPattern.matcher(line);
                }
            }
            buf.append(line);
            buf.append('\n');
        }
    } catch (IOException e) {
        // somehow failed to read the contents of the log
        buf.append(Messages.MailSender_FailureMail_FailedToAccessBuildLog()).append("\n\n")
                .append(Functions.printThrowable(e));
    }

    msg.setText(buf.toString(), charset);

    return msg;
}

From source file:unalcol.termites.boxplots.BestAgentsRoundInfoCollected.java

private void AddDataFailingExperiments(String sDirectorio, ArrayList<Double> Pf, Hashtable<String, List> info) {
    File f = new File(sDirectorio);
    String extension;/*  w  w  w.j a  v a  2s  . c o  m*/
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    for (File file : files) {
        List list = new ArrayList();
        extension = "";
        int i = file.getName().lastIndexOf('.');
        int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
        if (i > p) {
            extension = file.getName().substring(i + 1);
        }

        // System.out.println(file.getName() + "extension" + extension);
        if (file.isFile() && extension.equals("csv") && file.getName().startsWith("failInfo")
                && file.getName().contains(mazeMode)) {
            //System.out.println(file.getName());
            //System.out.println("get: " + file.getName());
            String[] filenamep = file.getName().split(Pattern.quote("+"));

            //System.out.println("file" + filenamep[8]);
            int popsizef = Integer.valueOf(filenamep[3]);
            double pff = Double.valueOf(filenamep[5]);
            String modef = filenamep[7];

            int worldSize = Integer.valueOf(filenamep[11]) * Integer.valueOf(filenamep[13]);
            /*System.out.println("psizef:" + popsizef);
             System.out.println("pff:" + pff);
             System.out.println("modef:" + modef);
             */
            //                String[] aMode = {"turnoncontact", "lwsandc2", "lwsandc", "lwphevap2", "lwphevap"};
            try {
                sc = new Scanner(file);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                        .log(Level.SEVERE, null, ex);
            }

            int agentId = -1;
            int countLines = 0;
            int roundNumber = -1;
            int infoCollected = -1;

            String[] data = null;
            while (sc.hasNext()) {
                String line = sc.nextLine();
                //System.out.println("line:" + line);
                data = line.split(",");
                agentId = Integer.valueOf(data[0]);
                ///roundNumber = Integer.valueOf(data[1]);

                if (infoCollected < Integer.valueOf(data[2])) {
                    infoCollected = Integer.valueOf(data[2]);
                    roundNumber = Integer.valueOf(data[1]);
                }
                countLines++;
            }

            // System.out.println("lines" + countLines);
            if (countLines == popsizef && infoCollected != -1 && roundNumber != -1 && Pf.contains(pff)) {
                int datas = roundNumber;
                //list.add(datas);
                if (info.get(modef + "+" + popsizef) == null) {
                    info.put((modef + "+" + popsizef), new ArrayList<Integer>());
                }
                info.get(modef + "+" + popsizef).add(datas);
            }

            LOGGER.debug("Adding series " + i);
            LOGGER.debug(list.toString());

            /*if (Pf.contains(pff)) {
             /*pf == 1.0E-4 || pf == 3.0E-4*/
            /*  if (Pf.size() == 1) {
             dataset.add(list, popsizef, getTechniqueName(modef));
             } else {
             dataset.add(list, String.valueOf(popsizef) + "-" + pff, getTechniqueName(modef));
             }
             }*/
        }

        //if (Pf.contains(pff)) { 
        /*pf == 1.0E-4 || pf == 3.0E-4*/
    }

}

From source file:br.com.diegosilva.jsfcomponents.util.Utils.java

public static String decimalBr(Object valor) {
    if (valor == null || valor.toString().trim().equals("")) {
        return "0,00";
    } else {/*  www .  j  ava 2  s.com*/
        String retorno = valor.toString();
        return retorno.replaceAll(Pattern.quote("."), ",");
    }
}

From source file:de.tarent.maven.plugins.pkg.AbstractMvnPkgPluginTestCase.java

protected boolean debContainsMainArtifact() throws MojoExecutionException, IOException {
    final Pattern p = Pattern
            .compile(".*" + Pattern.quote(packagingPlugin.project.getArtifact().getFile().getName()) + ".*");
    return debContains(p, "-c");
}

From source file:de.da_sense.moses.client.abstraction.apks.ExternalApplication.java

/**
 * Replaces all LINEBREAK_SUBST with "\n"
 * /*from ww  w .  j  a  v  a  2  s.  com*/
 * @param s
 *            The original String
 * @return The String with replacements
 */
private static String fromLinebreakSubst(String s) {
    return s.replaceAll(Pattern.quote(LINEBREAK_SUBST), "\n");
}

From source file:com.genentech.chemistry.openEye.apps.SDFStructureTagger.java

private void run(String inFile) {
    oemolithread ifs = new oemolithread(inFile);
    long start = System.currentTimeMillis();
    int iCounter = 0; //Structures in the SD file.

    OEMolBase mol = new OEGraphMol();
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;/*from ww w. j  av a2  s .c om*/

        boolean isMatch = false;
        if ((requestedOutFields.size() == 0 && !outputOccurrence && !outputExists)
                || requestedOutFields.size() > 0)
            isMatch |= addTaggingInfoToOutput(mol);
        if (outputOccurrence)
            isMatch |= addOccurrenceToOutput(mol);
        if (outputExists)
            isMatch |= addExistsToOutput(mol);

        if ((!onlyMatches || isMatch) && !noMatches)
            oechem.OEWriteMolecule(outputOEThread, mol);

        if (noMatches && !isMatch && !onlyMatches)
            oechem.OEWriteMolecule(outputOEThread, mol);

        //Output "." to show that the program is running.
        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %dsec\n", iCounter, (System.currentTimeMillis() - start) / 1000);
        }
    }
    mol.delete();
    ifs.close();
    ifs.delete();
    inFile = inFile.replaceAll(".*" + Pattern.quote(File.separator), "");
    System.err.printf("%s: Read %d structures from %s. %d sec\n", MY_NAME, iCounter, inFile,
            (System.currentTimeMillis() - start) / 1000);
}

From source file:br.ufal.cideei.soot.instrument.FeatureModelInstrumentorTransformer.java

private void preTransform(Body body) {
    SootClass sootClass = body.getMethod().getDeclaringClass();
    if (!sootClass.hasTag("SourceFileTag")) {
        throw new IllegalArgumentException("the body cannot be traced to its source file");
    }//from w ww  .j av  a 2  s . com
    /*
     * XXX: WARNING! tag.getAbsolutePath() returns an INCORRECT value for the absolute path AFTER the first body
     * transformation. In this workaround, since this method depends on the classpath , it is injected on this class
     * constructor. We will use tag.getSourceFile() in order to resolve the file name.
     * 
     * Yes, this is ugly.
     */
    SourceFileTag sourceFileTag = (SourceFileTag) body.getMethod().getDeclaringClass().getTag("SourceFileTag");

    /*
     * The String absolutePath will be transformed to the absolute path to the Class which body belongs to. See the
     * XXX above for the explanation.
     */
    String absolutePath = sootClass.getName();
    int lastIndexOf = absolutePath.lastIndexOf(".");
    if (lastIndexOf != -1) {
        absolutePath = absolutePath.substring(0, lastIndexOf);
    } else {
        absolutePath = "";
    }

    /*
     * XXX String#replaceAll does not work properly when replacing "special" chars like File.separator. The Matcher
     * and Pattern composes a workaround for that.
     */
    absolutePath = absolutePath.replaceAll(Pattern.quote("."), Matcher.quoteReplacement(File.separator));
    absolutePath = classPath + File.separator + absolutePath + File.separator + sourceFileTag.getSourceFile();
    sourceFileTag.setAbsolutePath(absolutePath);

    IPath path = new Path(sourceFileTag.getAbsolutePath());
    this.file = org.eclipse.core.resources.ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);

    // #ifdef METRICS
    long startCompilationUnitParser = System.nanoTime();
    // #endif
    CompilationUnit compilationUnit = cachedParser.parse(file);
    // #ifdef METRICS
    long parsingDelta = System.nanoTime() - startCompilationUnitParser;
    if (sink != null)
        sink.flow(body, FeatureModelInstrumentorTransformer.PARSING, parsingDelta);
    FeatureModelInstrumentorTransformer.parsingTime += parsingDelta;

    long startBuilderColorLookUpTable = System.nanoTime();
    // #endif
    this.currentColorMap = cachedLineColorMapper.makeAccept(compilationUnit, file, extracter, compilationUnit);
    // #ifdef METRICS
    long builderColorLookUpTableDelta = System.nanoTime() - startBuilderColorLookUpTable;
    if (sink != null)
        sink.flow(body, FeatureModelInstrumentorTransformer.COLOR_LOOKUP, builderColorLookUpTableDelta);
    FeatureModelInstrumentorTransformer.colorLookupTableBuildingTime += builderColorLookUpTableDelta;
    // #endif
}

From source file:Game_DataS.java

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 *///  www.j  ava2s.  c  o m

void TXT_FILES_PROCESS(String GetString, String FieldName, PrintWriter Out, String HostTeam, String ForeignTeam,
        String datetime, String field, Integer Ivisitors) throws IOException, ClassNotFoundException,
        SQLException, InstantiationException, IllegalAccessException {
    BufferedReader bufferedReader = new BufferedReader(new StringReader(GetString));
    String line = null;
    boolean flag_before = false;
    Double DBL1_FG2, DBL2_FG3, DBL3_FT;
    int txt_Counter = 0;

    //Connect to DB
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String connectionURL = "jdbc:oracle:thin:@" + serverURL + ":" + serverPort + ":" + serverSID;
    conn = DriverManager.getConnection(connectionURL, username, password);
    // End connection DB

    //Array to calculate Points of each Team
    int HCounter = 0, FCounter = 0;

    //now search to txt and do Parsing
    while ((line = bufferedReader.readLine()) != null) {
        txt_Counter++;

        if (line.equals("")) {
            flag_before = true;
            continue;
            //dont check ifs, just skip line
        }

        //HostTeam
        if (flag_before == false) {
            String[] Strs = line.split(",");

            System.out.println("Line is  -> " + line);

            //first process Minutes
            String g = ".";
            String[] temp1 = Strs[1].split(":"); //split Minutes
            String MINUTES = temp1[0] + g + temp1[1];
            Double MIN = Double.parseDouble(MINUTES);

            //Split FG2
            //first if string contains \, or is 00
            if (Strs[3].contains("/")) {
                String[] temp2 = Strs[3].split("/"); //split FG2
                Integer x = Integer.parseInt(temp2[0]);
                Integer y = Integer.parseInt(temp2[1]);
                Double FG2 = 100 * ((double) x / (double) y);
                String stre = Double.toString(FG2);
                String Ar[] = stre.split(Pattern.quote("."));
                DBL1_FG2 = Double.parseDouble(Ar[0]);
            } else {
                //00
                DBL1_FG2 = Double.parseDouble(Strs[3]);
            }

            //Split FG3
            if (Strs[4].contains("/")) {
                String[] temp3 = Strs[4].split("/"); //split FG3
                Integer a = Integer.parseInt(temp3[0]);
                Integer b = Integer.parseInt(temp3[1]);
                Double FG3 = 100 * ((double) a / (double) b);
                String stri = Double.toString(FG3);
                String Arr[] = stri.split(Pattern.quote("."));
                DBL2_FG3 = Double.parseDouble(Arr[0]);
            } else {
                //00
                DBL2_FG3 = Double.parseDouble(Strs[4]);
            }

            //Split FT
            if (Strs[5].contains("/")) {
                String[] temp4 = Strs[5].split("/"); //split FT
                Integer c = Integer.parseInt(temp4[0]);
                Integer d = Integer.parseInt(temp4[1]);
                Double FT = 100 * ((double) c / (double) d);
                String stro = Double.toString(FT);
                String Arrr[] = stro.split(Pattern.quote("."));
                DBL3_FT = Double.parseDouble(Arrr[0]);
            } else {
                //00
                DBL3_FT = Double.parseDouble(Strs[5]);
            }

            String qString2 = "insert into DGame values( " + "'" + HostTeam + "','" + Strs[0] + "'," + MIN
                    + ", " + Integer.parseInt(Strs[2]) + ", " + DBL1_FG2 + ", " + DBL2_FG3 + ", " + DBL3_FT
                    + ", " + Integer.parseInt(Strs[6]) + ", " + Integer.parseInt(Strs[7]) + ", "
                    + Integer.parseInt(Strs[8]) + ", " + Integer.parseInt(Strs[9]) + ", "
                    + Integer.parseInt(Strs[10]) + ", " + Integer.parseInt(Strs[11]) + ", "
                    + Integer.parseInt(Strs[12]) + ", " + Integer.parseInt(Strs[13]) + ", "
                    + Integer.parseInt(Strs[14]) + ", " + Integer.parseInt(Strs[15]) + ", "
                    + Integer.parseInt(Strs[16]) + ", '" + (HostTeam + " " + Strs[0]) + "' )";
            System.out.println(" command DGame ->12 " + qString2);
            statement = conn.createStatement();
            statement.execute(qString2);
            statement.close();
            //
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();

            ListA.add(new ObjectA(HostTeam + " " + Strs[0]));

            //
            char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int t = 0; t < 20; t++) {
                char c = chars[random.nextInt(chars.length)];
                sb.append(c);
            }
            String output = sb.toString();

            ListPS.add(new Player_Statistics(HostTeam + " " + ForeignTeam, MIN, Integer.parseInt(Strs[2]),
                    DBL1_FG2, DBL2_FG3, DBL3_FT, Integer.parseInt(Strs[6]), Integer.parseInt(Strs[7]),
                    Integer.parseInt(Strs[8]), Integer.parseInt(Strs[9]), Integer.parseInt(Strs[10]),
                    Integer.parseInt(Strs[11]), Integer.parseInt(Strs[12]), Integer.parseInt(Strs[13]),
                    Integer.parseInt(Strs[14]), Integer.parseInt(Strs[15]), Integer.parseInt(Strs[16]),
                    dateFormat.format(date) + " " + HostTeam + output));

            //
            ListPN.add(new PlayerName(Strs[0], dateFormat.format(date) + " " + HostTeam + output));
            //

            HCounter = HCounter + Integer.parseInt(Strs[2]);
        }

        //ForeignTeam
        if (flag_before == true) {
            String[] Strs = line.split(",");
            System.out.println("Line is 0- -- =>> " + line);
            //first process Minutes
            String g = ".";
            String[] temp1 = Strs[1].split(":"); //split Minutes
            String MINUTES = temp1[0] + g + temp1[1];
            Double MIN = Double.parseDouble(MINUTES);

            //Split FG2
            //first if string contains \, or is 00
            if (Strs[3].contains("/")) {
                String[] temp2 = Strs[3].split("/"); //split FG2
                Integer x = Integer.parseInt(temp2[0]);
                Integer y = Integer.parseInt(temp2[1]);
                Double FG2 = 100 * ((double) x / (double) y);
                String stre = Double.toString(FG2);
                String Ar[] = stre.split(Pattern.quote("."));
                DBL1_FG2 = Double.parseDouble(Ar[0]);
            } else {
                //00
                DBL1_FG2 = Double.parseDouble(Strs[3]);
            }

            //Split FG3
            if (Strs[4].contains("/")) {
                String[] temp3 = Strs[4].split("/"); //split FG3
                Integer a = Integer.parseInt(temp3[0]);
                Integer b = Integer.parseInt(temp3[1]);
                Double FG3 = 100 * ((double) a / (double) b);
                String stri = Double.toString(FG3);
                String Arr[] = stri.split(Pattern.quote("."));
                DBL2_FG3 = Double.parseDouble(Arr[0]);
            } else {
                //00
                DBL2_FG3 = Double.parseDouble(Strs[4]);
            }

            //Split FT
            if (Strs[5].contains("/")) {
                String[] temp4 = Strs[5].split("/"); //split FT
                Integer c = Integer.parseInt(temp4[0]);
                Integer d = Integer.parseInt(temp4[1]);
                Double FT = 100 * ((double) c / (double) d);
                String stro = Double.toString(FT);
                String Arrr[] = stro.split(Pattern.quote("."));
                DBL3_FT = Double.parseDouble(Arrr[0]);
            } else {
                //00
                DBL3_FT = Double.parseDouble(Strs[5]);
            }

            String qString2 = "insert into DGame values( " + "'" + ForeignTeam + "','" + Strs[0] + "'," + MIN
                    + ", " + Integer.parseInt(Strs[2]) + ", " + DBL1_FG2 + ", " + DBL2_FG3 + ", " + DBL3_FT
                    + ", " + Integer.parseInt(Strs[6]) + ", " + Integer.parseInt(Strs[7]) + ", "
                    + Integer.parseInt(Strs[8]) + ", " + Integer.parseInt(Strs[9]) + ", "
                    + Integer.parseInt(Strs[10]) + ", " + Integer.parseInt(Strs[11]) + ", "
                    + Integer.parseInt(Strs[12]) + ", " + Integer.parseInt(Strs[13]) + ", "
                    + Integer.parseInt(Strs[14]) + ", " + Integer.parseInt(Strs[15]) + ", "
                    + Integer.parseInt(Strs[16]) + ", '" + (ForeignTeam + " " + Strs[0]) + "' )";
            System.out.println(" command DGame -> " + qString2);
            statement = conn.createStatement();
            statement.execute(qString2);
            statement.close();
            //
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();

            ListA.add(new ObjectA(ForeignTeam + " " + Strs[0]));

            //
            char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
            StringBuilder sb = new StringBuilder();
            Random random = new Random();
            for (int t = 0; t < 20; t++) {
                char c = chars[random.nextInt(chars.length)];
                sb.append(c);
            }
            String output = sb.toString();

            ListPS.add(new Player_Statistics(HostTeam + " " + ForeignTeam, MIN, Integer.parseInt(Strs[2]),
                    DBL1_FG2, DBL2_FG3, DBL3_FT, Integer.parseInt(Strs[6]), Integer.parseInt(Strs[7]),
                    Integer.parseInt(Strs[8]), Integer.parseInt(Strs[9]), Integer.parseInt(Strs[10]),
                    Integer.parseInt(Strs[11]), Integer.parseInt(Strs[12]), Integer.parseInt(Strs[13]),
                    Integer.parseInt(Strs[14]), Integer.parseInt(Strs[15]), Integer.parseInt(Strs[16]),
                    dateFormat.format(date) + " " + ForeignTeam + output));

            //
            ListPN.add(new PlayerName(Strs[0], dateFormat.format(date) + " " + ForeignTeam + output));
            //
            FCounter = FCounter + Integer.parseInt(Strs[2]);
        }
    } //LOOP END

    //NOW INSERT STATIC DATA OF THIS GAME INTO TABLE < SGAME >..
    String qString1 = "insert into SGame values( " + "'" + datetime + "','" + field + "', " + Ivisitors + " ,'"
            + HostTeam + "','" + ForeignTeam + "', '" + (HostTeam + " " + ForeignTeam) + "', "
            + Integer.valueOf(HCounter) + ", " + Integer.valueOf(FCounter) + ")";
    statement = conn.createStatement();
    statement.execute(qString1);
    statement.close();
    conn.close();

    //open conn again
    //Connect to DB
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String connectionURLe = "jdbc:oracle:thin:@" + serverURL + ":" + serverPort + ":" + serverSID;
    conn = DriverManager.getConnection(connectionURLe, username, password);
    // End connection DB

    //Now do the relationship between SGame and DGame. Insert JoinGame Table
    for (int i = 0; i < txt_Counter - 1; i++) {
        String qString2 = "insert into JoinGame values( " + "'" + (HostTeam + " " + ForeignTeam) + "', '"
                + ListA.get(i).Get_Name() + "', " + "'"
                + ((HostTeam + " " + ForeignTeam) + " " + ListA.get(i).Get_Name()) + "' )";
        statement = conn.createStatement();
        statement.execute(qString2);
        statement.close();
    }

    //Now go to SPlayer and save statitistical Data
    for (int i = 0; i < txt_Counter - 1; i++) {
        String qString2 = "insert into DPlayer values( " + "'" + ListPS.get(i).GetGameName() + "', "
                + ListPS.get(i).GetMinutes() + ", " + ListPS.get(i).GetPoints() + ", " + ListPS.get(i).GetFG2()
                + ", " + ListPS.get(i).GetFG3() + ", " + ListPS.get(i).GetFT() + ", "
                + ListPS.get(i).Getreboundso() + ", " + ListPS.get(i).Getreboundsd() + ", "
                + ListPS.get(i).Getreboundst() + ", " + ListPS.get(i).Getassists() + ", "
                + ListPS.get(i).Getsteals() + ", " + ListPS.get(i).Getwrongs() + ", " + ListPS.get(i).Getfv()
                + ", " + ListPS.get(i).Getag() + ", " + ListPS.get(i).Getcm() + ", " + ListPS.get(i).Getrv()
                + ", " + ListPS.get(i).Getrip() + ", '" + (ListPS.get(i).Get_id_dplayer()) + "' )";
        System.out.println("XAXA EINAI -> " + qString2);
        statement = conn.createStatement();
        statement.execute(qString2);
        statement.close();
    }

    //Find player name and their id to make the relationship between statistical player info and Each Player
    String qString = "select playername, id_splayer from SPlayer";
    statement = conn.createStatement();
    ResultSet result = statement.executeQuery(qString);

    //Now make relationship between SPlayer and DPlayer - every player has statistics in every game - Table JoinPlayer
    while (result.next()) {
        for (int i = 0; i < ListPN.size(); i++) {
            if (ListPN.get(i).GetPlayerName().equals(result.getString("playername"))) {
                //in this index, make the process
                String idSPLAYER = result.getString("id_splayer");
                String idDPLAYER = ListPN.get(i).Getid_dplayer();
                String idJP = idSPLAYER + " " + idDPLAYER;
                String qString2 = "insert into JoinPlayer values( " + "'" + idSPLAYER + "', '" + idDPLAYER
                        + "', '" + idJP + "' " + ")";
                statement = conn.createStatement();
                statement.execute(qString2);
                statement.close();
            }
        }
    }

    //Now last step. Make the Relationship between Static info Game and Team. Each Team has Games. Insert into JoinTeamGame
    //Host Team
    String qString4 = "insert into JoinTeamGame values( " + "'" + HostTeam + "', '"
            + (HostTeam + " " + ForeignTeam) + "', '" + (HostTeam + " " + HostTeam + "-" + ForeignTeam) + "' "
            + ")";
    statement = conn.createStatement();
    statement.execute(qString4);
    statement.close();

    //Foreing Team
    String qString5 = "insert into JoinTeamGame values( " + "'" + ForeignTeam + "', '"
            + (HostTeam + " " + ForeignTeam) + "', '" + (ForeignTeam + " " + HostTeam + "-" + ForeignTeam)
            + "' " + ")";
    statement = conn.createStatement();
    statement.execute(qString5);
    statement.close();
    conn.close();

}

From source file:com.dtolabs.rundeck.plugin.resources.ec2.InstanceToNodeMapper.java

/**
 * Return the result of the selector applied to the instance, otherwise return the defaultValue. The selector can be
 * a comma-separated list of selectors./*from   ww w .  j  a va2s  .  c  o m*/
 * @param inst the instance
 * @param selector the selector string
 * @param defaultValue a default value to return if there is no result from the selector
 * @param tagMerge if true, allow | separator to merge multiple values
 */
public static String applySelector(final Instance inst, final String selector, final String defaultValue,
        final boolean tagMerge) throws GeneratorException {

    if (null != selector) {
        for (final String selPart : selector.split(",")) {
            if (tagMerge) {
                final StringBuilder sb = new StringBuilder();
                for (final String subPart : selPart.split(Pattern.quote("|"))) {
                    final String val = applyMultiSelector(inst, subPart.split(Pattern.quote("+")));
                    if (null != val) {
                        if (sb.length() > 0) {
                            sb.append(",");
                        }
                        sb.append(val);
                    }
                }
                if (sb.length() > 0) {
                    return sb.toString();
                }
            } else {
                final String val = applyMultiSelector(inst, selPart.split(Pattern.quote("+")));
                if (null != val) {
                    return val;
                }
            }
        }
    }
    return defaultValue;
}