Example usage for java.lang String startsWith

List of usage examples for java.lang String startsWith

Introduction

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

Prototype

public boolean startsWith(String prefix) 

Source Link

Document

Tests if this string starts with the specified prefix.

Usage

From source file:org.openplans.delayfeeder.LoadFeeds.java

public static void main(String args[]) throws HibernateException, IOException {
    if (args.length != 1) {
        System.out.println("expected one argument: the path to a csv of agency,route,url");
    }/*from  w  w  w . j  ava2s . co  m*/
    GenericApplicationContext context = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.loadBeanDefinitions("org/openplans/delayfeeder/application-context.xml");
    xmlReader.loadBeanDefinitions("data-sources.xml");

    SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");

    Session session = sessionFactory.getCurrentSession();
    Transaction tx = session.beginTransaction();

    FileReader fileReader = new FileReader(new File(args[0]));
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while (bufferedReader.ready()) {
        String line = bufferedReader.readLine().trim();
        if (line.startsWith("#")) {
            continue;
        }
        if (line.length() < 3) {
            //blank or otherwise broken line
            continue;
        }

        String[] parts = line.split(",");
        String agency = parts[0];
        String route = parts[1];
        String url = parts[2];
        Query query = session.createQuery("from RouteFeed where agency = :agency and route = :route");
        query.setParameter("agency", agency);
        query.setParameter("route", route);
        @SuppressWarnings("rawtypes")
        List list = query.list();
        RouteFeed feed;
        if (list.size() == 0) {
            feed = new RouteFeed();
            feed.agency = agency;
            feed.route = route;
            feed.lastEntry = new GregorianCalendar();
        } else {
            feed = (RouteFeed) list.get(0);
        }
        if (!url.equals(feed.url)) {
            feed.url = url;
            feed.lastEntry.setTimeInMillis(0);
        }
        session.saveOrUpdate(feed);
    }
    tx.commit();
}

From source file:edu.cuhk.hccl.TripRealRatingsApp.java

public static void main(String[] args) throws IOException {
    File dir = new File(args[0]);
    File outFile = new File(args[1]);
    outFile.delete();//ww  w  . j  a va2 s  .co m

    StringBuilder buffer = new StringBuilder();

    for (File file : dir.listFiles()) {
        List<String> lines = FileUtils.readLines(file, "UTF-8");
        String hotelID = file.getName().split("_")[1];
        String author = null;
        boolean noContent = false;
        for (String line : lines) {
            if (line.startsWith("<Author>")) {
                try {
                    author = line.split(">")[1].trim();
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("[ERROR] An error occured on this line:");
                    System.out.println(line);
                    continue;
                }
            } else if (line.startsWith("<Content>")) { // ignore records if they have no content
                String content = line.split(">")[1].trim();
                if (content == null || content.equals(""))
                    noContent = true;
            } else if (line.startsWith("<Rating>")) {
                String[] rates = line.split(">")[1].trim().split("\t");

                if (noContent || rates.length != 8)
                    continue;

                // Change missing rating from -1 to 0
                for (int i = 0; i < rates.length; i++) {
                    if (rates[i].equals("-1"))
                        rates[i] = "0";
                }

                buffer.append(author + "\t");
                buffer.append(hotelID + "\t");

                // overall
                buffer.append(rates[0] + "\t");
                // location
                buffer.append(rates[3] + "\t");
                // room
                buffer.append(rates[2] + "\t");
                // service
                buffer.append(rates[6] + "\t");
                // value
                buffer.append(rates[1] + "\t");
                // cleanliness
                buffer.append(rates[4] + "\t");

                buffer.append("\n");
            }
        }

        // Write once for each file
        FileUtils.writeStringToFile(outFile, buffer.toString(), true);

        // Clear buffer
        buffer.setLength(0);
        System.out.printf("[INFO] Finished processing %s\n", file.getName());
    }
    System.out.println("[INFO] All processinig are finished!");
}

From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java

public static final void main(String[] as_1RqdTxtFilePath) {
    Iterator<String> lineItr = null;
    try {/*from   ww w.ja  v  a  2  s. c om*/
        lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null
    } catch (IOException iox) {
        throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox);
    } catch (RuntimeException rx) {
        throw new RuntimeException("One required parameter: The path to the text file.", rx);
    }

    String LINE_SEP = System.getProperty("line.separator", "\n");

    ArrayList<String> alsItems = new ArrayList<String>();
    boolean bStartMark = false;
    boolean bLine1Skipped = false;
    StringBuilder sdCurrentItem = new StringBuilder();
    while (lineItr.hasNext()) {
        String sLine = lineItr.next().trim();
        if (!bStartMark) {
            if (sLine.startsWith(".START_SEQUENCE")) {
                bStartMark = true;
                continue;
            }
            throw new IllegalStateException("Start mark not found.");
        }
        if (!bLine1Skipped) {
            bLine1Skipped = true;
            continue;
        } else if (!sLine.equals(".END_SEQUENCE")) {
            sdCurrentItem.append(sLine).append(LINE_SEP);
        } else {
            alsItems.add(sdCurrentItem.toString());
            sdCurrentItem.setLength(0);
            bStartMark = false;
            bLine1Skipped = false;
            continue;
        }
    }

    for (String s : alsItems) {
        System.out.println("----------");
        System.out.print(s);
    }
}

From source file:postenergy.PostHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://iplant.dk/addData.php?n=mindass");

    try {/*from   w ww  .  j  a  v  a2  s.co m*/

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("?n", "=mindass"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Input:")) {
                String key = line.substring(6);
                // do something with the key
                System.out.println("key:" + key);
            }

        }
    } catch (IOException e) {
        System.out.println("There was an error: " + e);
    }
}

From source file:ListAlgorithms.java

public static void main(String[] args) {
    Provider[] providers = Security.getProviders();
    Set<String> ciphers = new HashSet<String>();
    Set<String> keyAgreements = new HashSet<String>();
    Set<String> macs = new HashSet<String>();
    Set<String> messageDigests = new HashSet<String>();
    Set<String> signatures = new HashSet<String>();

    for (int i = 0; i != providers.length; i++) {
        Iterator it = providers[i].keySet().iterator();

        while (it.hasNext()) {
            String entry = (String) it.next();

            if (entry.startsWith("Alg.Alias.")) {
                entry = entry.substring("Alg.Alias.".length());
            }/*  ww w  .  ja v a2  s  . c  om*/

            if (entry.startsWith("Cipher.")) {
                ciphers.add(entry.substring("Cipher.".length()));
            } else if (entry.startsWith("KeyAgreement.")) {
                keyAgreements.add(entry.substring("KeyAgreement.".length()));
            } else if (entry.startsWith("Mac.")) {
                macs.add(entry.substring("Mac.".length()));
            } else if (entry.startsWith("MessageDigest.")) {
                messageDigests.add(entry.substring("MessageDigest.".length()));
            } else if (entry.startsWith("Signature.")) {
                signatures.add(entry.substring("Signature.".length()));
            }
        }
    }

    printSet("Ciphers", ciphers);
    printSet("KeyAgreeents", keyAgreements);
    printSet("Macs", macs);
    printSet("MessageDigests", messageDigests);
    printSet("Signatures", signatures);
}

From source file:com.rvantwisk.cnctools.Main.java

public static void main(String[] args) {

    // Detect OS/X and set AWT to that we can use OPenGL, this might not be needed fro Java 8
    final String osName = System.getProperty("os.name");
    final String javaVersion = System.getProperty("java.version");
    if (osName.contains("OS X")) {
        if (javaVersion.startsWith("1.7")) {
            System.setProperty("javafx.macosx.embedded", "true");
        }//from  ww  w  .java2  s  .  com
        java.awt.Toolkit.getDefaultToolkit();
    }

    launch(args);
}

From source file:postenergy.TestHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {//from   ww  w  .jav  a 2  s .  c o  m

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
        nameValuePairs.add(new BasicNameValuePair("Passwd", "yourpassword"));
        nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
        nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
                // do something with the key
            }

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

From source file:com.projity.pm.graphic.gantt.Main.java

public static void main(String[] args) {
    System.setProperty("com.apple.mrj.application.apple.menu.about.name",
            Environment.getStandAlone() ? "OpenProj" : "Project-ON-Demand");
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    Locale.setDefault(ConfigurationFile.getLocale());
    HashMap opts = ApplicationStartupFactory.extractOpts(args);
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.startsWith("linux")) {
        String javaExec = ConfigurationFile.getRunProperty("JAVA_EXE");
        //check jvm
        String javaVersion = System.getProperty("java.version");
        if (Environment.compareJavaVersion(javaVersion, "1.5") < 0) {
            String message = Messages.getStringWithParam("Text.badJavaVersion", javaVersion);
            if (javaExec != null && javaExec.length() > 0)
                message += "\n" + Messages.getStringWithParam("Text.javaExecutable",
                        new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" });
            if (!opts.containsKey("silentlyFail"))
                JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"),
                        JOptionPane.ERROR_MESSAGE);
            System.exit(64);/*ww w  .  j av a 2s  .c  om*/
        }
        String javaVendor = System.getProperty("java.vendor");
        if (javaVendor == null || !(javaVendor.startsWith("Sun") || javaVendor.startsWith("IBM"))) {
            String message = Messages.getStringWithParam("Text.badJavaVendor", javaVendor);
            if (javaExec != null && javaExec.length() > 0)
                message += "\n" + Messages.getStringWithParam("Text.javaExecutable",
                        new Object[] { javaExec, "JAVA_EXE", "$HOME/.openproj/run.conf" });
            if (!opts.containsKey("silentlyFail"))
                JOptionPane.showMessageDialog(null, message, Messages.getContextString("Title.ProjityError"),
                        JOptionPane.ERROR_MESSAGE);
            System.exit(64);
        }
    }

    boolean newLook = false;
    //      HashMap opts = ApplicationStartupFactory.extractOpts(args); // allow setting menu look on command line - primarily for testing or webstart args
    log.info(opts);
    //      newLook = opts.get("menu") == null;

    Environment.setNewLook(newLook);
    //      if (!Environment.isNewLaf()) {
    //         try {
    //            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    //         } catch (Exception e) {
    //         }
    //      }
    ApplicationStartupFactory startupFactory = new ApplicationStartupFactory(opts); //put before to initialize standalone flag
    mainFrame = new MainFrame(Messages.getContextString("Text.ApplicationTitle"), null, null);
    boolean doWelcome = true; // to do see if project param exists in args
    startupFactory.instanceFromNewSession(mainFrame, doWelcome);
}

From source file:com.sebuilder.interpreter.SeInterpreter.java

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println(/* w ww  .  j av  a 2 s .  c  o  m*/
                "Usage: [--driver=<drivername] [--driver.<configkey>=<configvalue>...] [--implicitlyWait=<ms>] [--pageLoadTimeout=<ms>] [--stepTypePackage=<package name>] <script path>...");
        System.exit(0);
    }

    Log log = LogFactory.getFactory().getInstance(SeInterpreter.class);

    WebDriverFactory wdf = DEFAULT_DRIVER_FACTORY;
    ScriptFactory sf = new ScriptFactory();
    StepTypeFactory stf = new StepTypeFactory();
    sf.setStepTypeFactory(stf);
    TestRunFactory trf = new TestRunFactory();
    sf.setTestRunFactory(trf);

    ArrayList<String> paths = new ArrayList<String>();
    HashMap<String, String> driverConfig = new HashMap<String, String>();
    for (String s : args) {
        if (s.startsWith("--")) {
            String[] kv = s.split("=", 2);
            if (kv.length < 2) {
                log.fatal("Driver configuration option \"" + s
                        + "\" is not of the form \"--driver=<name>\" or \"--driver.<key>=<value\".");
                System.exit(1);
            }
            if (s.startsWith("--implicitlyWait")) {
                trf.setImplicitlyWaitDriverTimeout(Integer.parseInt(kv[1]));
            } else if (s.startsWith("--pageLoadTimeout")) {
                trf.setPageLoadDriverTimeout(Integer.parseInt(kv[1]));
            } else if (s.startsWith("--stepTypePackage")) {
                stf.setPrimaryPackage(kv[1]);
            } else if (s.startsWith("--driver.")) {
                driverConfig.put(kv[0].substring("--driver.".length()), kv[1]);
            } else if (s.startsWith("--driver")) {
                try {
                    wdf = (WebDriverFactory) Class
                            .forName("com.sebuilder.interpreter.webdriverfactory." + kv[1]).newInstance();
                } catch (ClassNotFoundException e) {
                    log.fatal("Unknown WebDriverFactory: " + "com.sebuilder.interpreter.webdriverfactory."
                            + kv[1], e);
                } catch (InstantiationException e) {
                    log.fatal("Could not instantiate WebDriverFactory "
                            + "com.sebuilder.interpreter.webdriverfactory." + kv[1], e);
                } catch (IllegalAccessException e) {
                    log.fatal("Could not instantiate WebDriverFactory "
                            + "com.sebuilder.interpreter.webdriverfactory." + kv[1], e);
                }
            } else {
                paths.add(s);
            }
        } else {
            paths.add(s);
        }
    }

    if (paths.isEmpty()) {
        log.info("Configuration successful but no paths to scripts specified. Exiting.");
        System.exit(0);
    }

    HashMap<String, String> cfg = new HashMap<String, String>(driverConfig);

    for (String path : paths) {
        try {
            TestRun lastRun = null;
            for (Script script : sf.parse(new File(path))) {
                for (Map<String, String> data : script.dataRows) {
                    try {
                        lastRun = script.testRunFactory.createTestRun(script, log, wdf, driverConfig, data,
                                lastRun);
                        if (lastRun.finish()) {
                            log.info(script.name + " succeeded");
                        } else {
                            log.info(script.name + " failed");
                        }
                    } catch (Exception e) {
                        log.info(script.name + " failed", e);
                    }
                }
            }
        } catch (Exception e) {
            log.fatal("Run error.", e);
            System.exit(1);
        }
    }
}

From source file:org.nmdp.b12s.mac.client.http.X509Config.java

public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException, UnrecoverableKeyException {
    URL trustKeyStoreUrl = X509Config.class.getResource("/trusted.jks");

    URL clientKeyStoreUri = X509Config.class.getResource("/test-client.jks");

    SSLContext sslContext = SSLContexts.custom()
            // Configure trusted certs
            .loadTrustMaterial(trustKeyStoreUrl, "changeit".toCharArray())
            // Configure client certificate
            .loadKeyMaterial(clientKeyStoreUri, "changeit".toCharArray(), "changeit".toCharArray()).build();

    try (TextHttpClient httpClient = new TextHttpClient("https://macbeta.b12x.org/mac/api", sslContext)) {

    }/*from ww  w.  j av  a  2s .  c  o  m*/
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {

        HttpGet httpget = new HttpGet("https://macbeta.b12x.org/mac/api/codes/AA");
        System.out.println("executing request " + httpget.getRequestLine());

        try (CloseableHttpResponse response = httpclient.execute(httpget)) {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                Charset charset = StandardCharsets.UTF_8;
                for (Header contentType : response.getHeaders("Content-Type")) {
                    System.out.println("Content-Type: " + contentType);
                    for (String part : contentType.getValue().split(";")) {
                        if (part.startsWith("charset=")) {
                            String charsetName = part.split("=")[1];
                            charset = Charset.forName(charsetName);
                        }
                    }
                }
                System.out.println("Response content length: " + entity.getContentLength());
                String content = EntityUtils.toString(entity, charset);
                System.out.println(content);
            }
            EntityUtils.consume(entity);
        }
    }
}