Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

In this page you can find the example usage for java.io BufferedReader BufferedReader.

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:com.wxpay.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert1.p12"));
    try {//from w w  w .j  ava2 s  .  com
        keyStore.load(instream, "1269885501".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1269885501".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:org.gzk.image.junit.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/apiclient_cert.p12"));
    try {/* www .  j a va 2 s .  c o m*/
        keyStore.load(instream, "1374938902".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1374938902".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.magicbeans.banjiuwan.util.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {/*from  www  .  j  av a 2s .  com*/
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

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

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:ProxyTunnelDemo.java

public static void main(String[] args) throws Exception {

    ProxyClient proxyclient = new ProxyClient();
    // set the host the proxy should create a connection to
    ////  w w w  .j  a  v a  2 s .  c  o m
    // Note:  By default port 80 will be used. Some proxies only allow conections
    // to ports 443 and 8443.  This is because the HTTP CONNECT method was intented
    // to be used for tunneling HTTPS.
    proxyclient.getHostConfiguration().setHost("www.yahoo.com");
    // set the proxy host and port
    proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128);
    // set the proxy credentials, only necessary for authenticating proxies
    proxyclient.getState().setProxyCredentials(new AuthScope("10.0.1.1", 3128, null),
            new UsernamePasswordCredentials("proxy", "proxy"));

    // create the socket
    ProxyClient.ConnectResponse response = proxyclient.connect();

    if (response.getSocket() != null) {
        Socket socket = response.getSocket();
        try {
            // go ahead and do an HTTP GET using the socket
            Writer out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1");
            out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n");
            out.write("Host: www.yahoo.com\r\n");
            out.write("Agent: whatever\r\n");
            out.write("\r\n");
            out.flush();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            // be sure to close the socket when we're done
            socket.close();
        }
    } else {
        // the proxy connect was not successful, check connect method for reasons why
        System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine());
        System.out.println(response.getConnectMethod().getResponseBodyAsString());
    }
}

From source file:com.era7.bioinfo.annotation.AutomaticQualityControl.java

public static void main(String[] args) {

    if (args.length != 4) {
        System.out.println("This program expects four parameters: \n" + "1. Gene annotation XML filename \n"
                + "2. Reference protein set (.fasta)\n" + "3. Output TXT filename\n"
                + "4. Initial Blast XML results filename (the one used at the very beginning of the semiautomatic annotation process)\n");
    } else {//from   www.j  av  a2 s.c o m

        BufferedWriter outBuff = null;

        try {

            File inFile = new File(args[0]);
            File fastaFile = new File(args[1]);
            File outFile = new File(args[2]);
            File blastFile = new File(args[3]);

            //Primero cargo todos los datos del archivo xml del blast
            BufferedReader buffReader = new BufferedReader(new FileReader(blastFile));
            StringBuilder stBuilder = new StringBuilder();
            String line = null;

            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }

            buffReader.close();
            System.out.println("Creating blastoutput...");
            BlastOutput blastOutput = new BlastOutput(stBuilder.toString());
            System.out.println("BlastOutput created! :)");
            stBuilder.delete(0, stBuilder.length());

            HashMap<String, String> blastProteinsMap = new HashMap<String, String>();
            ArrayList<Iteration> iterations = blastOutput.getBlastOutputIterations();
            for (Iteration iteration : iterations) {
                blastProteinsMap.put(iteration.getQueryDef().split("\\|")[1].trim(), iteration.toString());
            }
            //freeing some memory
            blastOutput = null;
            //------------------------------------------------------------------------

            //Initializing writer for output file
            outBuff = new BufferedWriter(new FileWriter(outFile));

            //reading gene annotation xml file.....
            buffReader = new BufferedReader(new FileReader(inFile));
            stBuilder = new StringBuilder();
            line = null;
            while ((line = buffReader.readLine()) != null) {
                stBuilder.append(line);
            }
            buffReader.close();

            XMLElement genesXML = new XMLElement(stBuilder.toString());
            //freeing some memory I don't need anymore
            stBuilder.delete(0, stBuilder.length());

            //reading file with the reference proteins set
            ArrayList<String> proteinsReferenceSet = new ArrayList<String>();
            buffReader = new BufferedReader(new FileReader(fastaFile));
            while ((line = buffReader.readLine()) != null) {
                if (line.charAt(0) == '>') {
                    proteinsReferenceSet.add(line.split("\\|")[1]);
                }
            }
            buffReader.close();

            Element pGenes = genesXML.asJDomElement().getChild(PredictedGenes.TAG_NAME);

            List<Element> contigs = pGenes.getChildren(ContigXML.TAG_NAME);

            System.out.println("There are " + contigs.size() + " contigs to be checked... ");

            outBuff.write("There are " + contigs.size() + " contigs to be checked... \n");
            outBuff.write("Proteins reference set: \n");
            for (String st : proteinsReferenceSet) {
                outBuff.write(st + ",");
            }
            outBuff.write("\n");

            for (Element elem : contigs) {
                ContigXML contig = new ContigXML(elem);

                //escribo el id del contig en el que estoy
                outBuff.write("Checking contig: " + contig.getId() + "\n");
                outBuff.flush();

                List<XMLElement> geneList = contig.getChildrenWith(PredictedGene.TAG_NAME);
                System.out.println("geneList.size() = " + geneList.size());

                int numeroDeGenesParaAnalizar = geneList.size() / FACTOR;
                if (numeroDeGenesParaAnalizar == 0) {
                    numeroDeGenesParaAnalizar++;
                }

                ArrayList<Integer> indicesUtilizados = new ArrayList<Integer>();

                outBuff.write("\nThe contig has " + geneList.size() + " predicted genes, let's analyze: "
                        + numeroDeGenesParaAnalizar + "\n");

                for (int j = 0; j < numeroDeGenesParaAnalizar; j++) {
                    int geneIndex;

                    boolean geneIsDismissed = false;
                    do {
                        geneIsDismissed = false;
                        geneIndex = (int) Math.round(Math.floor(Math.random() * geneList.size()));
                        PredictedGene tempGene = new PredictedGene(geneList.get(geneIndex).asJDomElement());
                        if (tempGene.getStatus().equals(PredictedGene.STATUS_DISMISSED)) {
                            geneIsDismissed = true;
                        }
                    } while (indicesUtilizados.contains(new Integer(geneIndex)) && geneIsDismissed);

                    indicesUtilizados.add(geneIndex);
                    System.out.println("geneIndex = " + geneIndex);

                    //Ahora hay que sacar el gen correspondiente al indice y hacer el control de calidad
                    PredictedGene gene = new PredictedGene(geneList.get(geneIndex).asJDomElement());

                    outBuff.write("\nAnalyzing gene with id: " + gene.getId() + " , annotation uniprot id: "
                            + gene.getAnnotationUniprotId() + "\n");
                    outBuff.write("eValue: " + gene.getEvalue() + "\n");

                    //--------------PETICION POST HTTP BLAST----------------------
                    PostMethod post = new PostMethod(BLAST_URL);
                    post.addParameter("program", "blastx");
                    post.addParameter("sequence", gene.getSequence());
                    post.addParameter("database", "uniprotkb");
                    post.addParameter("email", "ppareja@era7.com");
                    post.addParameter("exp", "1e-10");
                    post.addParameter("stype", "dna");

                    // execute the POST
                    HttpClient client = new HttpClient();
                    int status = client.executeMethod(post);
                    System.out.println("status post = " + status);
                    InputStream inStream = post.getResponseBodyAsStream();

                    String fileName = "jobid.txt";
                    FileOutputStream outStream = new FileOutputStream(new File(fileName));
                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //Once the file is created I just have to read one line in order to extract the job id
                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    String jobId = buffReader.readLine();
                    buffReader.close();

                    System.out.println("jobId = " + jobId);

                    //--------------HTTP CHECK JOB STATUS REQUEST----------------------
                    GetMethod get = new GetMethod(CHECK_JOB_STATUS_URL + jobId);
                    String jobStatus = "";
                    do {

                        try {
                            Thread.sleep(1000);//sleep for 1000 ms                                
                        } catch (InterruptedException ie) {
                            //If this thread was intrrupted by nother thread
                        }

                        status = client.executeMethod(get);
                        //System.out.println("status get = " + status);

                        inStream = get.getResponseBodyAsStream();

                        fileName = "jobStatus.txt";
                        outStream = new FileOutputStream(new File(fileName));

                        while ((len = inStream.read(buffer)) != -1) {
                            outStream.write(buffer, 0, len);
                        }
                        outStream.close();

                        //Once the file is created I just have to read one line in order to extract the job id
                        buffReader = new BufferedReader(new FileReader(new File(fileName)));
                        jobStatus = buffReader.readLine();
                        //System.out.println("jobStatus = " + jobStatus);
                        buffReader.close();

                    } while (!jobStatus.equals(FINISHED_JOB_STATUS));

                    //Once I'm here the blast should've already finished

                    //--------------JOB RESULTS HTTP REQUEST----------------------
                    get = new GetMethod(JOB_RESULT_URL + jobId + "/out");

                    status = client.executeMethod(get);
                    System.out.println("status get = " + status);

                    inStream = get.getResponseBodyAsStream();

                    fileName = "jobResults.txt";
                    outStream = new FileOutputStream(new File(fileName));

                    while ((len = inStream.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();

                    //--------parsing the blast results file-----

                    TreeSet<GeneEValuePair> featuresBlast = new TreeSet<GeneEValuePair>();

                    buffReader = new BufferedReader(new FileReader(new File(fileName)));
                    while ((line = buffReader.readLine()) != null) {
                        if (line.length() > 3) {
                            String prefix = line.substring(0, 3);
                            if (prefix.equals("TR:") || prefix.equals("SP:")) {
                                String[] columns = line.split(" ");
                                String id = columns[1];
                                //System.out.println("id = " + id);

                                String e = "";

                                String[] arraySt = line.split("\\.\\.\\.");
                                if (arraySt.length > 1) {
                                    arraySt = arraySt[1].trim().split(" ");
                                    int contador = 0;
                                    for (int k = 0; k < arraySt.length && contador <= 2; k++) {
                                        String string = arraySt[k];
                                        if (!string.equals("")) {
                                            contador++;
                                            if (contador == 2) {
                                                e = string;
                                            }
                                        }

                                    }
                                } else {
                                    //Number before e-
                                    String[] arr = arraySt[0].split("e-")[0].split(" ");
                                    String numeroAntesE = arr[arr.length - 1];
                                    String numeroDespuesE = arraySt[0].split("e-")[1].split(" ")[0];
                                    e = numeroAntesE + "e-" + numeroDespuesE;
                                }

                                double eValue = Double.parseDouble(e);
                                //System.out.println("eValue = " + eValue);
                                GeneEValuePair g = new GeneEValuePair(id, eValue);
                                featuresBlast.add(g);
                            }
                        }
                    }

                    GeneEValuePair currentGeneEValuePair = new GeneEValuePair(gene.getAnnotationUniprotId(),
                            gene.getEvalue());

                    System.out.println("currentGeneEValuePair.id = " + currentGeneEValuePair.id);
                    System.out.println("currentGeneEValuePair.eValue = " + currentGeneEValuePair.eValue);
                    boolean blastContainsGene = false;
                    for (GeneEValuePair geneEValuePair : featuresBlast) {
                        if (geneEValuePair.id.equals(currentGeneEValuePair.id)) {
                            blastContainsGene = true;
                            //le pongo la e que tiene en el wu-blast para poder comparar
                            currentGeneEValuePair.eValue = geneEValuePair.eValue;
                            break;
                        }
                    }

                    if (blastContainsGene) {
                        outBuff.write("The protein was found in the WU-BLAST result.. \n");
                        //Una vez que se que esta en el blast tengo que ver que sea la mejor
                        GeneEValuePair first = featuresBlast.first();
                        outBuff.write("Protein with best eValue according to the WU-BLAST result: " + first.id
                                + " , " + first.eValue + "\n");
                        if (first.id.equals(currentGeneEValuePair.id)) {
                            outBuff.write("Proteins with best eValue match up \n");
                        } else {
                            if (first.eValue == currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has the same eValue \n");
                            } else if (first.eValue > currentGeneEValuePair.eValue) {
                                outBuff.write(
                                        "The one with best eValue is not the same protein but has a worse eValue :) \n");
                            } else {
                                outBuff.write(
                                        "The best protein from BLAST has an eValue smaller than ours, checking if it's part of the reference set...\n");
                                //System.exit(-1);
                                if (proteinsReferenceSet.contains(first.id)) {
                                    //The protein is in the reference set and that shouldn't happen
                                    outBuff.write(
                                            "The protein was found on the reference set, checking if it belongs to the same contig...\n");
                                    String iterationSt = blastProteinsMap.get(gene.getAnnotationUniprotId());
                                    if (iterationSt != null) {
                                        outBuff.write(
                                                "The protein was found in the BLAST used at the beginning of the annotation process.\n");
                                        Iteration iteration = new Iteration(iterationSt);
                                        ArrayList<Hit> hits = iteration.getIterationHits();
                                        boolean contigFound = false;
                                        Hit errorHit = null;
                                        for (Hit hit : hits) {
                                            if (hit.getHitDef().indexOf(contig.getId()) >= 0) {
                                                contigFound = true;
                                                errorHit = hit;
                                                break;
                                            }
                                        }
                                        if (contigFound) {
                                            outBuff.write(
                                                    "ERROR: A hit from the same contig was find in the Blast file: \n"
                                                            + errorHit.toString() + "\n");
                                        } else {
                                            outBuff.write("There is no hit with the same contig! :)\n");
                                        }
                                    } else {
                                        outBuff.write(
                                                "The protein is NOT in the BLAST used at the beginning of the annotation process.\n");
                                    }

                                } else {
                                    //The protein was not found on the reference set so everything's ok
                                    outBuff.write(
                                            "The protein was not found on the reference, everything's ok :)\n");
                                }
                            }
                        }

                    } else {
                        outBuff.write("The protein was NOT found on the WU-BLAST !! :( \n");

                        //System.exit(-1);
                    }

                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //closing outputfile
                outBuff.close();
            } catch (IOException ex) {
                Logger.getLogger(AutomaticQualityControl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}

From source file:com.adobe.aem.demo.Analytics.java

public static void main(String[] args) {

    String hostname = null;//  w  w w .  j  a  va2  s  .  c om
    String url = null;
    String eventfile = null;

    // Command line options for this tool
    Options options = new Options();
    options.addOption("h", true, "Hostname");
    options.addOption("u", true, "Url");
    options.addOption("f", true, "Event data file");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("u")) {
            url = cmd.getOptionValue("u");
        }

        if (cmd.hasOption("f")) {
            eventfile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("h")) {
            hostname = cmd.getOptionValue("h");
        }

        if (eventfile == null || hostname == null || url == null) {
            System.out.println("Command line parameters: -h hostname -u url -f path_to_XML_file");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    URLConnection urlConn = null;
    DataOutputStream printout = null;
    BufferedReader input = null;
    String u = "http://" + hostname + "/" + url;
    String tmp = null;
    try {

        URL myurl = new URL(u);
        urlConn = myurl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        printout = new DataOutputStream(urlConn.getOutputStream());

        String xml = readFile(eventfile, StandardCharsets.UTF_8);
        printout.writeBytes(xml);
        printout.flush();
        printout.close();

        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        logger.debug(xml);
        while (null != ((tmp = input.readLine()))) {
            logger.debug(tmp);
        }
        printout.close();
        input.close();

    } catch (Exception ex) {

        logger.error(ex.getMessage());

    }

}

From source file:gentracklets.GenTracklets.java

public static void main(String[] args) throws OrekitException {

    // load the data files
    File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip");
    DataProvidersManager DM = DataProvidersManager.getInstance();
    ZipJarCrawler crawler = new ZipJarCrawler(data);
    DM.clearProviders();/*  www . j a  v  a2  s  .c o  m*/
    DM.addProvider(crawler);

    // Read in TLE elements
    File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle");
    FileReader TLEfr;
    Vector<TLE> tles = new Vector<>();
    tles.setSize(30);

    try {
        // read and save TLEs to a vector
        TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle");
        BufferedReader readTLE = new BufferedReader(TLEfr);

        Scanner s = new Scanner(tleFile);

        String line1, line2;
        TLE2 tle = new TLE2();

        int nrOfObj = 4;
        for (int ii = 1; ii < nrOfObj + 1; ii++) {
            System.out.println(ii);
            line1 = s.nextLine();
            line2 = s.nextLine();
            if (TLE.isFormatOK(line1, line2)) {
                tles.setElementAt(new TLE(line1, line2), ii);
                System.out.println(tles.get(ii).toString());
            } else {
                System.out.println("format problem");
            }

        }
        readTLE.close();

        // define a groundstation
        Frame inertialFrame = FramesFactory.getEME2000();
        TimeScale utc = TimeScalesFactory.getUTC();
        double longitude = FastMath.toRadians(7.465);
        double latitude = FastMath.toRadians(46.87);
        double altitude = 950.;
        GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);
        TopocentricFrame staF = new TopocentricFrame(earth, station, "station");

        Vector<Orbit> eles = new Vector<>();
        eles.setSize(tles.size());
        for (int ii = 1; ii < nrOfObj + 1; ii++) {
            double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2),
                    (1.0 / 3));
            // convert them to orbits
            Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(),
                    tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(),
                    PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU);

            eles.setElementAt(kep, ii);

            // set up propagators
            KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii));

            System.out.println("a: " + a);

            // Initial state definition
            double mass = 1000.0;
            SpacecraftState initialState = new SpacecraftState(kep, mass);

            // Adaptive step integrator
            // with a minimum step of 0.001 and a maximum step of 1000
            double minStep = 0.001;
            double maxstep = 1000.0;
            double positionTolerance = 10.0;
            OrbitType propagationType = OrbitType.KEPLERIAN;
            double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType);
            AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep,
                    tolerances[0], tolerances[1]);

            NumericalPropagator propagator = new NumericalPropagator(integrator);
            propagator.setOrbitType(propagationType);

            // set up and add force models
            double AMR = 0.4;
            double crossSection = mass * AMR;
            double Cd = 0.01;
            double Cr = 0.5;
            double Co = 0.8;
            NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4);
            ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel(
                    FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);
            SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co);
            PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            SolarRadiationPressure srp = new SolarRadiationPressure(sun,
                    Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc);

            propagator.addForceModel(srp);
            propagator.addForceModel(holmesFeatherstone);
            propagator.setInitialState(initialState);

            // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets)
            Vector<AbsoluteDate> startDates = new Vector<>();
            startDates.setSize(3);
            startDates.setElementAt(new AbsoluteDate(2015, 12, 8, 20, 00, 00, utc), 0);
            startDates.setElementAt(new AbsoluteDate(2015, 12, 9, 21, 00, 00, utc), 1);
            startDates.setElementAt(new AbsoluteDate(2015, 12, 10, 22, 00, 00, utc), 2);

            double tstep = 30;
            int l = 7;

            for (int tt = 0; tt < startDates.size(); tt++) {

                // set up output file
                String app = "S_" + tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt";
                //                    FileWriter trackletsOutKep = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1h/AMR040/" + app);
                //                    FileWriter trackletsOutPer = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1h/AMR040/" + app);
                //                    BufferedWriter trackletsKepBW = new BufferedWriter(trackletsOutKep);
                //                    BufferedWriter trackletsPerBW = new BufferedWriter(trackletsOutPer);

                // with formatted output
                File file1 = new File(
                        "/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1d/AMR040/" + app);
                File file2 = new File(
                        "/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1d/AMR040/" + app);
                file1.createNewFile();
                file2.createNewFile();
                Formatter fmt1 = new Formatter(file1);
                Formatter fmt2 = new Formatter(file2);

                for (int kk = 0; kk < l; kk++) {
                    AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk);
                    SpacecraftState currentStateKep = kepler.propagate(propDate);
                    SpacecraftState currentStatePer = propagator.propagate(propDate);

                    System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t"
                            + currentStateKep.getDate());

                    // convert to RADEC coordinates
                    double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF,
                            inertialFrame, propDate);
                    double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF,
                            inertialFrame, propDate);

                    // write the tracklets to seperate files with the RA, DEC, epoch and fence given
                    //                        System.out.println(tles.get(kk).getSatelliteNumber() + "\t" + radec[0] / (2 * FastMath.PI) * 180 + "\t" + currentState.getDate());
                    AbsoluteDate year = new AbsoluteDate(YEAR, utc);
                    fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2],
                            (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1));
                    fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2],
                            (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1));

                }
                fmt1.flush();
                fmt1.close();
                fmt2.flush();
                fmt2.close();

            }
        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException iox) {
        Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox);
    }

}

From source file:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException/*ww w  .  ja v  a2 s. c o  m*/
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}

From source file:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

public static void main(String[] args) throws Exception {

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {//from  ww w .  ja  v  a  2 s  .  com
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:clientpaxos.ClientPaxos.java

/**
 * @param args the command line arguments
 *//*from www. j a  v a  2s .  c  om*/
public static void main(String[] args) throws IOException, InterruptedException, Exception {
    // TODO code application logic here

    String host = "";
    int port = 0;

    try (BufferedReader br = new BufferedReader(new FileReader("ipserver.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        if (line != null) {
            host = line;
            line = br.readLine();
            if (line != null) {
                port = Integer.parseInt(line);
            }
        }
    }

    scanner = new Scanner(System.in);

    //System.out.print("Input server IP hostname : ");
    //host = scan.nextLine();
    //System.out.print("Input server Port : ");
    //port = scan.nextInt();
    //scan.nextLine();
    tcpSocket = new Socket(host, port);
    System.out.println("Connected");
    Thread t = new Thread(new StringGetter());
    t.start();
    while (true) {
        sleep(100);
        if (!voteInput) {
            System.out.print("COMMAND : ");
        }
        //send msg to server
        String msg = scanner.next();
        //if ((day && isAlive == 1) || (!day && role.equals("werewolf") && isAlive == 1)) {
        ParseCommand(msg);
        //}
    }
}