Example usage for java.lang String subSequence

List of usage examples for java.lang String subSequence

Introduction

In this page you can find the example usage for java.lang String subSequence.

Prototype

public CharSequence subSequence(int beginIndex, int endIndex) 

Source Link

Document

Returns a character sequence that is a subsequence of this sequence.

Usage

From source file:com.hpcloud.util.Duration.java

@JsonCreator
public static Duration of(String duration) {
    Preconditions.checkArgument(PATTERN.matcher(duration).matches(), "Invalid duration: %s", duration);
    int i = 0;//from   w w w  .  ja va2 s .c  o m
    for (; i < duration.length(); i++)
        if (Character.isLetter(duration.charAt(i)))
            break;
    String unit = duration.subSequence(0, i).toString().trim();
    String dur = duration.subSequence(i, duration.length()).toString();
    return new Duration(Long.parseLong(unit), SUFFIXES.get(dur));
}

From source file:org.sparqlbuilder.www.SPServlet.java

private static List<String> convertJ2Path2(String jpath) throws JSONException {
    List<String> list = null;
    String temp = (String) jpath.subSequence(2, jpath.length() - 2);
    //  if (temp.contains(","")) 
    list = Arrays.asList(temp.split("\",\""));
    return list;/* w ww .  j  av a2  s  .  c om*/

    /*  JSONArray classLinks=new JSONArray(jpath); 
      String string;
              
      for (int i=0;i<classLinks.length();i++) 
      {
    string = classLinks.getJSONObject(i).toString(); 
    if (string.contains(",")) {
     list =Arrays.asList(string.split(","));
              
      } else 
         throw new IllegalArgumentException("path error");
               
        }*/

    //   return list;    
}

From source file:las.DBConnector.java

/**
 * Load CSV test data into SQL Table// w w  w  .j  a  v a  2s. c  o  m
 *
 * example for clearFirst: boolean check =
 * DBConnector.checkDataExistedInTable("MEMBERS");
 *
 * if (check) { DBConnector.loadCSVIntoTable("src/resources/members.csv",
 * "MEMBERS", true); System.out.println("Test data inserted into MEMBERS
 * table"); }
 *
 * ignore createNewReader, since it uses for loadCSVIntoTable, don't modify
 * it
 *
 * Getter and Setter provided for Separator to set your own separator inside
 * your CSV File
 *
 * @param csvFile : src/resources/xxx.csv (put your csv file under this
 * path)
 * @param tableName: TABLENAME (All in capital letters)
 * @param clearFirst true = if data not existed in SQL Table, write test
 * data inside false = if data exisited in SQL Table, don't write again.
 * @throws java.lang.Exception
 */
public static void loadCSVIntoTable(String csvFile, String tableName, boolean clearFirst) throws Exception {

    CSVReader csvReader = null;
    if (null == DBConnector.conn) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = DBConnector.getInstance().createNewReader(csvFile);

    } catch (ClassNotFoundException | SQLException | FileNotFoundException e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    String[] nextLine;
    PreparedStatement ps = null;
    try {
        conn.setAutoCommit(false);
        ps = conn.prepareStatement(query);

        if (clearFirst) {
            //delete data from table before loading csv
            conn.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        Date date = null;
        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    date = DateUtil.convertToDate(string);
                    if (null != date) {
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                    } else {
                        ps.setString(index++, string);
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps) {
            ps.close();
        }

        csvReader.close();
    }
}

From source file:com.nextgis.mobile.map.LocalTMSLayer.java

public static void create(final MapBase map, Uri uri) {
    String sName = getFileNameByUri(map.getContext(), uri, "new layer.zip");
    sName = (String) sName.subSequence(0, sName.length() - 4);
    showPropertiesDialog(map, true, sName, TMSTYPE_OSM, uri, null);
}

From source file:com.tealeaf.plugin.PluginEvent.java

public static void init(Context context) {
    if (initialized) {
        return;/*  w  w  w .j a v a2 s  .c o  m*/
    }
    initialized = true;
    ArrayList<String> classNames = new ArrayList<String>();

    try {
        String apkName = null;

        try {
            apkName = context.getPackageManager()
                    .getApplicationInfo(context.getApplicationContext().getPackageName(), 0).sourceDir;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        DexFile dexFile = new DexFile(new File(apkName));
        Enumeration<String> enumeration = dexFile.entries();

        int pluginsPackageStrLen = PLUGINS_PACKAGE_NAME.length();

        while (enumeration.hasMoreElements()) {
            String className = enumeration.nextElement();

            if (className.length() < pluginsPackageStrLen)
                continue;

            if (!className.contains("$")) {
                if (className.subSequence(0, pluginsPackageStrLen).equals(PLUGINS_PACKAGE_NAME)) {
                    classNames.add(className);
                }
            }
        }
    } catch (IOException e) {
        logger.log(e);
    }

    if (classNames.size() > 0) {
        String[] classNamesArr = new String[classNames.size()];
        classNames.toArray(classNamesArr);

        for (String name : classNamesArr) {
            try {
                Class objcls = Class.forName(name);

                if (IPlugin.class.isAssignableFrom(objcls)) {
                    Object instance = objcls.newInstance();

                    if (instance != null) {
                        logger.log("{plugins} Instantiated:", name);
                        classMap.put(name, instance);
                    } else {
                        logger.log("{plugins} WARNING: Class not found:", name);
                    }
                } else {
                    logger.log("{plugins} Ignoring class that does not derive from IPlugin:", name);
                }
            } catch (ClassNotFoundException e) {
                logger.log("{plugins} WARNING: Class not found:", name);
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }
}

From source file:CB_Core.Api.PocketQuery.java

/**
 * Ruft die Liste der PQs ab.//from   w w w.j av a  2  s  .  co  m
 * 
 * @param Staging
 *            Config.settings.StagingAPI.getValue()
 * @param accessToken
 *            as String
 * @param list
 *            as ArrayList<String>
 * @param conectionTimeout
 *            Config.settings.conection_timeout.getValue()
 * @param socketTimeout
 *            Config.settings.socket_timeout.getValue()
 * @return
 */
public static int GetPocketQueryList(ArrayList<PQ> list) {
    HttpGet httpGet = new HttpGet(GroundspeakAPI.GS_LIVE_URL + "GetPocketQueryList?AccessToken="
            + GroundspeakAPI.GetAccessToken(true) + "&format=json");
    if (list == null)
        new NullArgumentException("PQ List");
    try {
        String result = HttpUtils.Execute(httpGet, null);

        try
        // Parse JSON Result
        {
            JSONTokener tokener = new JSONTokener(result);
            JSONObject json = (JSONObject) tokener.nextValue();
            JSONObject status = json.getJSONObject("Status");
            if (status.getInt("StatusCode") == 0) {
                GroundspeakAPI.LastAPIError = "";
                JSONArray jPQs = json.getJSONArray("PocketQueryList");

                for (int ii = 0; ii < jPQs.length(); ii++) {

                    JSONObject jPQ = (JSONObject) jPQs.get(ii);

                    if (jPQ.getBoolean("IsDownloadAvailable")) {
                        PQ pq = new PQ();
                        pq.Name = jPQ.getString("Name");
                        pq.GUID = jPQ.getString("GUID");
                        pq.DateLastGenerated = new Date();
                        try {
                            String dateCreated = jPQ.getString("DateLastGenerated");
                            int date1 = dateCreated.indexOf("/Date(");
                            int date2 = dateCreated.indexOf("-");
                            String date = (String) dateCreated.subSequence(date1 + 6, date2);
                            pq.DateLastGenerated = new Date(Long.valueOf(date));
                        } catch (Exception exc) {
                            Log.err(log, "API", "SearchForGeocaches_ParseDate", exc);
                        }
                        pq.PQCount = jPQ.getInt("PQCount");
                        int Byte = jPQ.getInt("FileSizeInBytes");
                        pq.SizeMB = Byte / 1048576.0;
                        list.add(pq);
                    }
                }
                return 0;
            } else {
                GroundspeakAPI.LastAPIError = "";
                GroundspeakAPI.LastAPIError = "StatusCode = " + status.getInt("StatusCode") + "\n";
                GroundspeakAPI.LastAPIError += status.getString("StatusMessage") + "\n";
                GroundspeakAPI.LastAPIError += status.getString("ExceptionDetails");

                return (-1);
            }

        } catch (JSONException e) {

            e.printStackTrace();
        }
    } catch (ClientProtocolException e) {
        System.out.println(e.getMessage());
        return (-1);
    } catch (IOException e) {
        System.out.println(e.getMessage());
        return (-1);
    }

    return 0;
}

From source file:ryerson.daspub.mobile.AssignmentPage.java

/**
 * Create a page number label from the submission object and file name.
 * @return//from  w w w  .ja  va  2s  . c o  m
 */
private static String getPageNumberLabel(Submission S, String Name) {
    // get page number of file
    int i = Name.lastIndexOf("-");
    int j = Name.lastIndexOf(".");
    CharSequence val = Name.subSequence(i + 1, j);
    Integer page = Integer.valueOf(val.toString());
    page += 1; // pages are enumerated on a zero based index
    // build label
    int total = S.getPageCount();
    StringBuilder sb = new StringBuilder();
    sb.append(". Page ");
    sb.append(String.valueOf(page));
    sb.append(" of ");
    sb.append(String.valueOf(total));
    return sb.toString();
}

From source file:com.simplexwork.mysql.tools.utils.DocumentUtils.java

public static String fixName(String name) {
    while (name.contains("_")) {
        int i = name.indexOf("_");
        name = name.substring(0, i) + name.substring(++i, ++i).toUpperCase()
                + name.subSequence(i, name.length());
    }/*from  ww w  . j a  v a  2  s .  co m*/

    return name;

}

From source file:org.apache.ambari.server.utils.ShellCommandUtil.java

public static String hideOpenSslPassword(String command) {
    int start;// www. j  a va 2s .c o m
    if (command.contains(PASS_TOKEN)) {
        start = command.indexOf(PASS_TOKEN) + PASS_TOKEN.length();
    } else if (command.contains(KEY_TOKEN)) {
        start = command.indexOf(KEY_TOKEN) + KEY_TOKEN.length();
    } else {
        return command;
    }
    CharSequence cs = command.subSequence(start, command.indexOf(" ", start));
    return command.replace(cs, "****");
}

From source file:aula1.Aula1.java

public static String conversor(String entrada, String info) throws Exception {
    Pilha<String> input = new Pilha<>();
    Pilha<String> simbolos = new Pilha<>();
    Stack<Op> operadores = new Stack<>();
    Pilha<String> saida = new Pilha<>();
    String[] operadoresSuportados = { "+", "-", "*", "/", "^", "(", ")", "sen" };

    for (int i = 0; i < entrada.length(); i++) {
        String s = "";
        try {//  ww  w.ja v  a2 s  . com
            if (Character.isDigit(entrada.charAt(i))) {
                s = String.valueOf(entrada.charAt(i));
                while (Character.isDigit(entrada.charAt(i + 1))) {
                    s += String.valueOf(entrada.charAt(i + 1));
                    i++;
                }
            } else {
                if (entrada.charAt(i) == 's' && entrada.contains("sen")) {
                    int ind = entrada.indexOf("sen");
                    String ent = entrada.substring(ind);
                    int ini = ent.indexOf("sen(") + 4;
                    int fim = ent.indexOf(")/");
                    CharSequence x = ent.subSequence(ini, fim);
                    if (entrada.contains("sen(" + x + ")/" + x)) {
                        entrada = entrada.replace("sen(" + x + ")/" + x, "1");
                        s = "1";
                    } else {
                        ind += 2;
                        i = -1;
                        entrada = entrada.substring(ind + 1);
                        if (entrada.charAt(0) != '(')
                            throw new Exception("Falta de '(' aps sen");
                        s = "sen";
                    }
                } else
                    s = String.valueOf(entrada.charAt(i));
            }
            simbolos.push(s);
            input.push(s);
        } catch (IndexOutOfBoundsException ex) {
            s = String.valueOf(entrada.charAt(i));
            simbolos.push(s);
            input.push(s);
        }
    }
    while (!simbolos.isEMpty()) {
        String simbolo = simbolos.pop();

        if (Character.isDigit(simbolo.charAt(0)) || simbolo.charAt(0) == 'x')
            saida.push(simbolo);
        else if (Arrays.asList(operadoresSuportados).contains(simbolo)) {
            Op operador = new Op(simbolo);
            Op topOperador;
            try {
                topOperador = operadores.peek();
            } catch (EmptyStackException e) {
                topOperador = null;
            }
            if (simbolo.equals(")")) {
                while (topOperador != null && !topOperador.op().equals("(")) {
                    saida.push(topOperador.op());
                    operadores.pop();
                    topOperador = operadores.peek();
                }
                operadores.pop();
            } else if (simbolo.equals("(")) {
                operadores.push(operador);
            } else {
                while (topOperador != null && topOperador.Precedencia() > operador.Precedencia()) {
                    saida.push(topOperador.op());
                    operadores.pop();
                    try {
                        topOperador = operadores.peek();
                    } catch (EmptyStackException e) {
                        topOperador = null;
                    }
                }
                operadores.push(operador);
            }
        }
    }
    while (!operadores.isEmpty()) {
        Op operador = operadores.pop();
        saida.push(operador.op());
    }
    String resultado = "";
    for (String s : saida) {
        System.out.println("saida: " + s);
        resultado += s + " ";
    }
    resultado = calculaPolonesaINversa(resultado, info);
    return resultado;

}