Example usage for java.io PrintWriter println

List of usage examples for java.io PrintWriter println

Introduction

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

Prototype

public void println(Object x) 

Source Link

Document

Prints an Object and then terminates the line.

Usage

From source file:edu.isi.karma.research.modeling.ModelLearner_LOD.java

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

    ServletContextParameterMap contextParameters = ContextParametersRegistry.getInstance().getDefault();
    contextParameters.setParameterValue(ContextParameter.USER_CONFIG_DIRECTORY, "/Users/mohsen/karma/config");

    OntologyManager ontologyManager = new OntologyManager(contextParameters.getId());
    File ff = new File(Params.ONTOLOGY_DIR);
    File[] files = ff.listFiles();
    if (files == null) {
        logger.error("no ontology to import at " + ff.getAbsolutePath());
        return;//from   w w w  .  ja v  a  2  s .  co m
    }

    for (File f : files) {
        if (f.getName().endsWith(".owl") || f.getName().endsWith(".rdf") || f.getName().endsWith(".n3")
                || f.getName().endsWith(".ttl") || f.getName().endsWith(".xml")) {
            logger.info("Loading ontology file: " + f.getAbsolutePath());
            ontologyManager.doImport(f, "UTF-8");
        }
    }
    ontologyManager.updateCache();

    String outputPath = Params.OUTPUT_DIR;
    String graphPath = Params.GRAPHS_DIR;

    FileUtils.cleanDirectory(new File(graphPath));

    List<SemanticModel> semanticModels = ModelReader.importSemanticModelsFromJsonFiles(Params.MODEL_DIR,
            Params.MODEL_MAIN_FILE_EXT);

    ModelLearner_LOD modelLearner = null;

    boolean onlyGenerateSemanticTypeStatistics = false;
    boolean onlyUseOntology = false;
    boolean useCorrectType = false;
    int numberOfCandidates = 4;
    boolean onlyEvaluateInternalLinks = false;
    int maxPatternSize = 3;

    if (onlyGenerateSemanticTypeStatistics) {
        getStatistics(semanticModels);
        return;
    }

    String filePath = Params.RESULTS_DIR + "temp/";
    String filename = "";

    filename += "lod-results";
    filename += useCorrectType ? "-correct" : "-k=" + numberOfCandidates;
    filename += onlyUseOntology ? "-ontology" : "-p" + maxPatternSize;
    filename += onlyEvaluateInternalLinks ? "-internal" : "-all";
    filename += ".csv";

    PrintWriter resultFile = new PrintWriter(new File(filePath + filename));

    resultFile.println("source \t p \t r \t t \n");

    for (int i = 0; i < semanticModels.size(); i++) {
        //      for (int i = 0; i <= 10; i++) {
        //      int i = 1; {

        int newSourceIndex = i;
        SemanticModel newSource = semanticModels.get(newSourceIndex);

        logger.info("======================================================");
        logger.info(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        System.out.println(newSource.getName() + "(#attributes:" + newSource.getColumnNodes().size() + ")");
        logger.info("======================================================");

        SemanticModel correctModel = newSource;
        List<ColumnNode> columnNodes = correctModel.getColumnNodes();

        List<Node> steinerNodes = new LinkedList<Node>(columnNodes);

        String graphName = graphPath + "lod" + Params.GRAPH_FILE_EXT;

        if (onlyUseOntology) {
            modelLearner = new ModelLearner_LOD(new GraphBuilder(ontologyManager, false), steinerNodes);
        } else if (new File(graphName).exists()) {
            // read graph from file
            try {
                logger.info("loading the graph ...");
                DirectedWeightedMultigraph<Node, DefaultLink> graph = GraphUtil.importJson(graphName);
                modelLearner = new ModelLearner_LOD(new GraphBuilderTopK(ontologyManager, graph), steinerNodes);
            } catch (Exception e) {
                e.printStackTrace();
                resultFile.close();
                return;
            }
        } else {
            logger.info("building the graph ...");
            // create and save the graph to file
            //            GraphBuilder_Popularity b = new GraphBuilder_Popularity(ontologyManager, 
            //                  Params.LOD_OBJECT_PROPERIES_FILE, 
            //                  Params.LOD_DATA_PROPERIES_FILE);
            GraphBuilder_LOD_Pattern b = new GraphBuilder_LOD_Pattern(ontologyManager, Params.PATTERNS_DIR,
                    maxPatternSize);
            modelLearner = new ModelLearner_LOD(b.getGraphBuilder(), steinerNodes);
        }

        long start = System.currentTimeMillis();

        List<SortableSemanticModel> hypothesisList = modelLearner.hypothesize(useCorrectType,
                numberOfCandidates);

        long elapsedTimeMillis = System.currentTimeMillis() - start;
        float elapsedTimeSec = elapsedTimeMillis / 1000F;

        List<SortableSemanticModel> topHypotheses = null;
        if (hypothesisList != null) {

            //            for (SortableSemanticModel sss : hypothesisList) {
            //               ModelEvaluation mmm = sss.evaluate(correctModel);
            //               System.out.println(mmm.getPrecision() + ", " + mmm.getRecall());
            //            }
            topHypotheses = hypothesisList.size() > 10 ? hypothesisList.subList(0, 10) : hypothesisList;
        }

        Map<String, SemanticModel> models = new TreeMap<String, SemanticModel>();

        ModelEvaluation me;
        models.put("1-correct model", correctModel);
        if (topHypotheses != null)
            for (int k = 0; k < topHypotheses.size(); k++) {

                SortableSemanticModel m = topHypotheses.get(k);

                me = m.evaluate(correctModel, onlyEvaluateInternalLinks, false);

                String label = "candidate " + k + "\n" +
                //                     (m.getSteinerNodes() == null ? "" : m.getSteinerNodes().getScoreDetailsString()) +
                        "link coherence:"
                        + (m.getLinkCoherence() == null ? "" : m.getLinkCoherence().getCoherenceValue()) + "\n";
                label += (m.getSteinerNodes() == null || m.getSteinerNodes().getCoherence() == null) ? ""
                        : "node coherence:" + m.getSteinerNodes().getCoherence().getCoherenceValue() + "\n";
                label += "confidence:" + m.getConfidenceScore() + "\n";
                label += m.getSteinerNodes() == null ? ""
                        : "mapping score:" + m.getSteinerNodes().getScore() + "\n";
                label += "cost:" + roundDecimals(m.getCost(), 6) + "\n" +
                //                        "-distance:" + me.getDistance() + 
                        "-precision:" + me.getPrecision() + "-recall:" + me.getRecall();

                models.put(label, m);

                if (k == 0) { // first rank model
                    System.out.println("precision: " + me.getPrecision() + ", recall: " + me.getRecall()
                            + ", time: " + elapsedTimeSec);
                    logger.info("precision: " + me.getPrecision() + ", recall: " + me.getRecall() + ", time: "
                            + elapsedTimeSec);
                    String s = newSource.getName() + "\t" + me.getPrecision() + "\t" + me.getRecall() + "\t"
                            + elapsedTimeSec;
                    resultFile.println(s);

                }
            }

        String outName = outputPath + newSource.getName() + Params.GRAPHVIS_OUT_DETAILS_FILE_EXT;

        GraphVizUtil.exportSemanticModelsToGraphviz(models, newSource.getName(), outName,
                GraphVizLabelType.LocalId, GraphVizLabelType.LocalUri, true, true);

    }

    resultFile.close();

}

From source file:EchoClient.java

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

     Socket echoSocket = null;/*  www  .  j  a  v  a 2s.  c  o  m*/
     PrintWriter out = null;
     BufferedReader in = null;

     try {
         echoSocket = new Socket("taranis", 7);
         out = new PrintWriter(echoSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(
                                     echoSocket.getInputStream()));
     } catch (UnknownHostException e) {
         System.err.println("Don't know about host: taranis.");
         System.exit(1);
     } catch (IOException e) {
         System.err.println("Couldn't get I/O for "
                            + "the connection to: taranis.");
         System.exit(1);
     }

BufferedReader stdIn = new BufferedReader(
                                new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
 }

From source file:client.QueryLastFm.java

License:asdf

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

    // isAlreadyInserted("asdfs","jas,jnjkah");

    // FileWriter fw = new FileWriter(".\\tracks.csv");
    OutputStream track_os = new FileOutputStream(".\\tracks.csv");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8"));

    OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv");
    PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8"));

    track_id_out.print("");

    ByteArrayInputStream input;/*from www  . j a v  a 2 s . c o  m*/
    Document doc = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String trackName = "";
    String artistName = "";
    String sourceMbid = "";
    out.print("ID");// first row first column
    out.print(",");
    out.print("TrackName");// first row second column
    out.print(",");
    out.println("Artist");// first row third column

    track_id_out.print("source");// first row second column
    track_id_out.print(",");
    track_id_out.println("target");// first row third column
    // track_id_out.print(",");
    // track_id_out.println("type");// first row third column

    // out.flush();

    // out.close();

    // fw.close();

    // os.close();

    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", "cher")
                .setParameter("track", "believe").setParameter("limit", "100")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        HttpGet httpGet = new HttpGet(
                "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044");
        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();
                // Need to focus and resolve this part
                NodeList nodes;
                nodes = root.getChildNodes();

                nodes = root.getElementsByTagName("track");
                if (nodes.getLength() == 0) {
                    // System.out.println("empty");
                    return;
                }
                Node trackNode;
                for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now
                {
                    trackNode = nodes.item(k);
                    NodeList trackAttributes = trackNode.getChildNodes();

                    // check if mbid is present in track attributes
                    // System.out.println("Length  " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0));

                    if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) {
                        if (((Element) trackAttributes.item(5)).hasChildNodes())
                            ;// System.out.println("Go aHead");
                        else
                            continue;
                    } else
                        continue;

                    for (int n = 0; n < trackAttributes.getLength(); n++) {
                        Node attribute = trackAttributes.item(n);
                        if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) {
                            // System.out.println(((Element)attribute).getFirstChild().getNodeValue());
                            trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ 

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                            // System.out.println(n +  "   " +  ((Element)attribute).getFirstChild().getNodeValue());
                            sourceMbid = attribute.getFirstChild().getNodeValue();

                        }

                        if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) {
                            NodeList ArtistNodeList = attribute.getChildNodes();
                            for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                                Node Artistnode = ArtistNodeList.item(j);
                                if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                    // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());
                                    artistName = ((Element) Artistnode).getFirstChild().getNodeValue();
                                }
                            }
                        }
                    }
                    out.print(sourceMbid);
                    out.print(",");
                    out.print(trackName);
                    out.print(",");
                    out.println(artistName);
                    // out.print(",");
                    findSimilarTracks(track_id_out, sourceMbid, trackName, artistName);

                }
                track_id_out.flush();

                out.flush();
                out.close();
                track_id_out.close();
                track_os.close();

                // fw.close();
                Element trac = (Element) nodes.item(0);
                // trac.normalize();
                nodes = trac.getChildNodes();
                // System.out.println(nodes.getLength());

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    if ((node.getNodeName().compareToIgnoreCase("name")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) {
                        // System.out.println(((Element)node).getFirstChild().getNodeValue());
                    }

                    if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) {

                        // System.out.println("Well");
                        NodeList ArtistNodeList = node.getChildNodes();
                        for (int j = 0; j < ArtistNodeList.getLength(); j++) {
                            Node Artistnode = ArtistNodeList.item(j);
                            if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) {
                                /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/
                            }
                            /*System.out.println(Artistnode.getNodeName());*/
                        }
                    }

                }
                /*if(node instanceof Element){
                  //a child element to process
                  Element child = (Element) node;
                  String attribute = child.getAttribute("width");
                }*/

                // System.out.println(root.getAttribute("status"));
                NodeList tracks = root.getElementsByTagName("track");
                Element track = (Element) tracks.item(0);
                // System.out.println(track.getTagName());
                track.getChildNodes();

            } else {
                System.out.println("failed with status" + response.getStatusLine());
            }
            // input = (ByteArrayInputStream)entity1.getContent();
            // do something useful with the response body
            // and ensure it is fully consumed
        } finally {
            response.close();
        }
    }

    finally {
        System.out.println("Exited succesfully.");
        httpclient.close();

    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

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

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }// w w  w .ja  v  a 2  s. c om

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:htmlwordtag.HtmlWordTag.java

public static void main(String[] args)
        throws RepositoryException, MalformedQueryException, QueryEvaluationException {
    //get current path
    String current = System.getProperty("user.dir");
    //get html file from internet
    loadhtml();/*from  w  w w.  j  ava2 s .c om*/
    //make director for output
    verifyArgs();
    //translate html file to rdf
    HtmlWordTag httpClientPost = new HtmlWordTag();
    httpClientPost.input = new File("input");
    httpClientPost.output = new File("output");
    httpClientPost.client = new HttpClient();
    httpClientPost.client.getParams().setParameter("http.useragent", "Calais Rest Client");

    httpClientPost.run();

    //create main memory repository
    Repository repo = new SailRepository(new MemoryStore());
    repo.initialize();

    File file = new File(current + "\\output\\website1.html.xml");

    RepositoryConnection con = repo.getConnection();
    try {
        con.add(file, null, RDFFormat.RDFXML);
    } catch (OpenRDFException e) {
        // handle exception
    } catch (java.io.IOException e) {
        // handle io exception
    }

    System.out.println(con.isEmpty());

    //query entire repostiory
    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n"
            + "PREFIX p: <http://s.opencalais.com/1/pred/>\n"
            + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n"

            + "SELECT  distinct ?s ?n\n" + "WHERE {\n" + "{  ?s rdf:type c:Organization.\n"
            + "   ?s p:name ?n.\n}" + "  UNION \n" + "{  ?s rdf:type c:Person.\n" + "   ?s p:name ?n.\n}"
            + "  UNION \n" + "{  ?s rdf:type geo:City.\n" + "   ?s p:name ?n.\n}" + "}";

    //System.out.println(queryString);

    //insert query through sparql repository connection
    TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    TupleQueryResult result = tupleQuery.evaluate();

    File queryresultdir = new File(current + "\\queryresult");
    if (!queryresultdir.exists()) {
        if (queryresultdir.mkdir()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }

    File queryresult = null;
    try {
        // create new file
        queryresult = new File(current + "\\queryresult\\queryresult1.txt");

        // tries to create new file in the system
        if (queryresult.exists()) {
            if (queryresult.delete()) {
                System.out.println("file queryresult1.txt is already exist.");
                System.out.println("file queryresult1.txt has been delete.");
                if (queryresult.createNewFile()) {
                    System.out.println("create queryresult1.txt success");
                } else {
                    System.out.println("fail to create queryresult1.txt");
                }
            } else {
                System.out.println("fail to delete queryresult1.txt.");
            }
        } else {
            if (queryresult.createNewFile()) {
                System.out.println("create queryresult1.txt success");
            } else {
                System.out.println("fail to create queryresult1.txt");
            }
        }

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

    try {
        PrintWriter outputStream = null;
        try {
            outputStream = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult1.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error to find file queryresult1.txt");
            System.exit(0);
        }
        //go through all triple in sparql repository
        while (result.hasNext()) { // iterate over the result
            BindingSet bindingSet = result.next();
            Value valueOfS = bindingSet.getValue("s");
            Value valueOfN = bindingSet.getValue("n");

            System.out.println(valueOfS + " " + valueOfN);

            outputStream.println(valueOfS + " " + valueOfN);

        }
        outputStream.close();
    } finally {
        result.close();
    }
    //create main memory repository
    Repository repo2 = new SailRepository(new MemoryStore());
    repo2.initialize();

    File file2 = new File(current + "\\output\\website2.html.xml");

    RepositoryConnection con2 = repo2.getConnection();
    try {
        con2.add(file2, null, RDFFormat.RDFXML);
    } catch (OpenRDFException e) {
        // handle exception
    } catch (java.io.IOException e) {
        // handle io exception
    }

    System.out.println(con2.isEmpty());

    //query entire repostiory
    String queryString2 = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n"
            + "PREFIX p: <http://s.opencalais.com/1/pred/>\n"
            + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n"

            + "SELECT  distinct ?s ?n\n" + "WHERE {\n" + "{  ?s rdf:type c:Organization.\n"
            + "   ?s p:name ?n.\n}" + "  UNION \n" + "{  ?s rdf:type c:Person.\n" + "   ?s p:name ?n.\n}"
            + "  UNION \n" + "{  ?s rdf:type geo:City.\n" + "   ?s p:name ?n.\n}" + "}";

    //System.out.println(queryString2);

    //insert query through sparql repository connection
    TupleQuery tupleQuery2 = con2.prepareTupleQuery(QueryLanguage.SPARQL, queryString2);
    TupleQueryResult result2 = tupleQuery2.evaluate();

    File queryresult2 = null;
    try {
        // create new file
        queryresult2 = new File(current + "\\queryresult\\queryresult2.txt");

        // tries to create new file in the system
        if (queryresult2.exists()) {
            if (queryresult2.delete()) {
                System.out.println("file queryresult2.txt is already exist.");
                System.out.println("file queryresult2.txt has been delete.");
                if (queryresult2.createNewFile()) {
                    System.out.println("create queryresult2.txt success");
                } else {
                    System.out.println("fail to create queryresult2.txt");
                }
            } else {
                System.out.println("fail to delete queryresult2.txt.");
            }
        } else {
            if (queryresult2.createNewFile()) {
                System.out.println("create queryresult2.txt success");
            } else {
                System.out.println("fail to create queryresult2.txt");
            }
        }

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

    try {
        PrintWriter outputStream2 = null;
        try {
            outputStream2 = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult2.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error to find file queryresult2.txt");
            System.exit(0);
        }
        //go through all triple in sparql repository
        while (result2.hasNext()) { // iterate over the result
            BindingSet bindingSet = result2.next();
            Value valueOfS = bindingSet.getValue("s");
            Value valueOfN = bindingSet.getValue("n");

            System.out.println(valueOfS + " " + valueOfN);

            outputStream2.println(valueOfS + " " + valueOfN);

        }
        outputStream2.close();
    } finally {
        result2.close();
    }

}

From source file:EchoClient.java

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

        Socket kkSocket = null;//w  ww  . j av a  2  s. c  o m
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            kkSocket = new Socket("taranis", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: taranis.");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;

        while ((fromServer = in.readLine()) != null) {
            System.out.println("Server: " + fromServer);
            if (fromServer.equals("Bye."))
                break;

            fromUser = stdIn.readLine();
            if (fromUser != null) {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);
            }
        }

        out.close();
        in.close();
        stdIn.close();
        kkSocket.close();
    }

From source file:microbiosima.Microbiosima.java

/**
 * @param args//from  w w w .ja v a 2 s  . co  m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:AndroidUninstallStock.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    try {/*w  w w . j  a v  a 2  s.  c o  m*/
        String lang = Locale.getDefault().getLanguage();
        GnuParser cmdparser = new GnuParser();
        Options cmdopts = new Options();
        for (String fld : Arrays.asList("shortOpts", "longOpts", "optionGroups")) {
            // hack for printOptions
            java.lang.reflect.Field fieldopt = cmdopts.getClass().getDeclaredField(fld);
            fieldopt.setAccessible(true);
            fieldopt.set(cmdopts, new LinkedHashMap<>());
        }
        cmdopts.addOption("h", "help", false, "Help");
        cmdopts.addOption("t", "test", false, "Show only report");
        cmdopts.addOption(OptionBuilder.withLongOpt("adb").withArgName("file").hasArg()
                .withDescription("Path to ADB from Android SDK").create("a"));
        cmdopts.addOption(OptionBuilder.withLongOpt("dev").withArgName("device").hasArg()
                .withDescription("Select device (\"adb devices\")").create("d"));
        cmdopts.addOption(null, "restore", false,
                "If packages have not yet removed and are disabled, " + "you can activate them again");
        cmdopts.addOption(null, "google", false, "Delete packages are in the Google section");
        cmdopts.addOption(null, "unapk", false, "Delete /system/app/ *.apk *.odex *.dex"
                + System.lineSeparator() + "(It is required to repeat command execution)");
        cmdopts.addOption(null, "unlib", false, "Delete /system/lib/[libs in apk]");
        //cmdopts.addOption(null, "unfrw", false, "Delete /system/framework/ (special list)");
        cmdopts.addOption(null, "scanlibs", false,
                "(Dangerous!) Include all the libraries of selected packages." + " Use with --unlib");

        cmdopts.addOptionGroup(new OptionGroup() {
            {
                addOption(OptionBuilder.withLongOpt("genfile").withArgName("file").hasArg().isRequired()
                        .withDescription("Create file with list packages").create());
                addOption(OptionBuilder.withLongOpt("lang").withArgName("ISO 639").hasArg().create());
            }
        });
        cmdopts.getOption("lang").setDescription(
                "See hl= in Google URL (default: " + lang + ") " + "for description from Google Play Market");
        CommandLine cmd = cmdparser.parse(cmdopts, args);

        if (args.length == 0 || cmd.hasOption("help")) {
            PrintWriter console = new PrintWriter(System.out);
            HelpFormatter cmdhelp = new HelpFormatter();
            cmdhelp.setOptionComparator(new Comparator<Option>() {
                @Override
                public int compare(Option o1, Option o2) {
                    return 0;
                }
            });
            console.println("WARNING: Before use make a backup with ClockworkMod Recovery!");
            console.println();
            console.println("AndroidUninstallStock [options] [AndroidListSoft.xml]");
            cmdhelp.printOptions(console, 80, cmdopts, 3, 2);
            console.flush();
            return;
        }

        String adb = cmd.getOptionValue("adb", "adb");
        try {
            run(adb, "start-server");
        } catch (IOException e) {
            System.out.println("Error: Not found ADB! Use -a or --adb");
            return;
        }

        final boolean NotTest = !cmd.hasOption("test");

        String deverror = getDeviceStatus(adb, cmd.getOptionValue("dev"));
        if (!deverror.isEmpty()) {
            System.out.println(deverror);
            return;
        }

        System.out.println("Getting list packages:");
        LinkedHashMap<String, String> apklist = new LinkedHashMap<String, String>();
        for (String ln : run(adb, "-s", lastdevice, "shell", "pm list packages -s -f")) {
            // "pm list packages" give list sorted by packages ;)
            String pckg = ln.substring("package:".length());
            String pckgname = ln.substring(ln.lastIndexOf('=') + 1);
            pckg = pckg.substring(0, pckg.length() - pckgname.length() - 1);
            if (!pckgname.equals("android") && !pckgname.equals("com.android.vending")/*Google Play Market*/) {
                apklist.put(pckg, pckgname);
            }
        }
        for (String ln : run(adb, "-s", lastdevice, "shell", "ls /system/app/")) {
            String path = "/system/app/" + ln.replace(".odex", ".apk").replace(".dex", ".apk");
            if (!apklist.containsKey(path)) {
                apklist.put(path, "");
            }
        }
        apklist.remove("/system/app/mcRegistry");
        for (Map.Entry<String, String> info : sortByValues(apklist).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        String genfile = cmd.getOptionValue("genfile");
        if (genfile != null) {
            Path genpath = Paths.get(genfile);
            try (BufferedWriter gen = Files.newBufferedWriter(genpath, StandardCharsets.UTF_8,
                    new StandardOpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING,
                            StandardOpenOption.WRITE })) {
                if (cmd.getOptionValue("lang") != null) {
                    lang = cmd.getOptionValue("lang");
                }

                LinkedHashSet<String> listsystem = new LinkedHashSet<String>() {
                    {
                        add("com.android");
                        add("com.google.android");
                        //add("com.sec.android.app");
                        add("com.monotype.android");
                        add("eu.chainfire.supersu");
                    }
                };

                // \r\n for Windows Notepad
                gen.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
                gen.write("<!-- & raplace with &amp; or use <![CDATA[ ]]> -->\r\n");
                gen.write("<AndroidUninstallStock>\r\n\r\n");
                gen.write("<Normal>\r\n");
                System.out.println();
                System.out.println("\tNormal:");
                writeInfo(gen, apklist, lang, listsystem, true);
                gen.write("\t<apk name=\"Exclude Google and etc\">\r\n");
                for (String exc : listsystem) {
                    gen.write("\t\t<exclude global=\"true\" in=\"package\" pattern=\"" + exc + "\" />\r\n");
                }
                gen.write("\t</apk>\r\n");
                gen.write("</Normal>\r\n\r\n");
                gen.write("<Google>\r\n");
                System.out.println();
                System.out.println("\tGoogle:");
                writeInfo(gen, apklist, lang, listsystem, false);
                gen.write("</Google>\r\n\r\n");
                gen.write("</AndroidUninstallStock>\r\n");
                System.out.println("File " + genpath.toAbsolutePath() + " created.");
            }
            return;
        }

        String[] FileName = cmd.getArgs();
        if (!(FileName.length > 0 && Files.isReadable(Paths.get(FileName[0])))) {
            System.out.println("Error: File " + FileName[0] + " not found!");
            return;
        }

        DocumentBuilderFactory xmlfactory = getXmlDocFactory();

        // DocumentBuilder.setErrorHandler() for print errors
        Document xml = xmlfactory.newDocumentBuilder().parse(new File(FileName[0]));

        LinkedList<AusInfo> Normal = new LinkedList<AusInfo>();
        LinkedList<AusInfo> Google = new LinkedList<AusInfo>();

        NodeList ndaus = xml.getElementsByTagName("AndroidUninstallStock").item(0).getChildNodes();
        for (int ndausx = 0, ndausc = ndaus.getLength(); ndausx < ndausc; ndausx++) {
            Node ndnow = ndaus.item(ndausx);
            NodeList nd = ndnow.getChildNodes();
            String ndname = ndnow.getNodeName();
            for (int ndx = 0, ndc = nd.getLength(); ndx < ndc; ndx++) {
                if (!nd.item(ndx).getNodeName().equalsIgnoreCase("apk")) {
                    continue;
                }
                if (ndname.equalsIgnoreCase("Normal")) {
                    Normal.add(getApkInfo(nd.item(ndx)));
                } else if (ndname.equalsIgnoreCase("Google")) {
                    Google.add(getApkInfo(nd.item(ndx)));
                }
            }
        }

        // FIXME This part must be repeated until the "pm uninstall" will not issue "Failure" on all packages.
        //       Now requires a restart.
        System.out.println();
        System.out.println("Include and Exclude packages (Normal):");
        LinkedHashMap<String, String> apkNormal = getApkFromPattern(apklist, Normal, false);
        System.out.println();
        System.out.println("Global Exclude packages (Normal):");
        apkNormal = getApkFromPattern(apkNormal, Normal, true);
        System.out.println();
        System.out.println("Final list packages (Normal):");
        for (Map.Entry<String, String> info : sortByValues(apkNormal).entrySet()) {
            System.out.println(info.getValue() + " = " + info.getKey());
        }

        LinkedHashMap<String, String> apkGoogle = new LinkedHashMap<String, String>();
        if (cmd.hasOption("google")) {
            System.out.println();
            System.out.println("Include and Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apklist, Google, false);
            System.out.println();
            System.out.println("Global Exclude packages (Google):");
            apkGoogle = getApkFromPattern(apkGoogle, Google, true);
            System.out.println();
            System.out.println("Final list packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(apkGoogle).entrySet()) {
                System.out.println(info.getValue() + " = " + info.getKey());
            }
        }

        if (NotTest) {
            if (!hasRoot(adb)) {
                System.out.println("No Root");
                System.out.println();
                System.out.println("FINISH :)");
                return;
            }
        }

        if (cmd.hasOption("restore")) {
            System.out.println();
            System.out.println("Enable (Restore) packages (Normal):");
            damage(adb, "pm enable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Enable (Restore) packages (Google):");
                damage(adb, "pm enable ", NotTest, apkGoogle, 2);
            }
            System.out.println();
            System.out.println("FINISH :)");
            return;
        } else {
            System.out.println();
            System.out.println("Disable packages (Normal):");
            damage(adb, "pm disable ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Disable packages (Google):");
                damage(adb, "pm disable ", NotTest, apkGoogle, 2);
            }
        }

        if (!cmd.hasOption("unapk") && !cmd.hasOption("unlib")) {
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }

        // Reboot now not needed
        /*if (NotTest) {
        reboot(adb, "-s", lastdevice, "reboot");
        if (!hasRoot(adb)) {
            System.out.println("No Root");
            System.out.println();
            System.out.println("FINISH :)");
            return;
        }
        }*/

        if (cmd.hasOption("unlib")) {
            // "find" not found
            System.out.println();
            System.out.println("Getting list libraries:");
            LinkedList<String> liblist = new LinkedList<String>();
            liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/"));
            String dircur = "/system/lib/";
            for (int x = 0; x < liblist.size(); x++) {
                if (liblist.get(x).startsWith("scan:")) {
                    dircur = liblist.get(x).substring("scan:".length());
                    liblist.remove(x);
                    x--;
                } else if (liblist.get(x).startsWith("d")) {
                    String dir = liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4) + "/";
                    liblist.remove(x);
                    x--;
                    liblist.add("scan:/system/lib/" + dir);
                    liblist.addAll(run(adb, "-s", lastdevice, "shell", "ls -l /system/lib/" + dir));
                    continue;
                }
                liblist.set(x, dircur + liblist.get(x).substring(liblist.get(x).lastIndexOf(':') + 4));
                System.out.println(liblist.get(x));
            }

            final boolean scanlibs = cmd.hasOption("scanlibs");
            LinkedHashMap<String, String> libNormal = getLibFromPatternInclude(adb, liblist, apkNormal, Normal,
                    "Normal", scanlibs);
            libNormal = getLibFromPatternGlobalExclude(libNormal, Normal, "Normal");
            System.out.println();
            System.out.println("Final list libraries (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                System.out.println(info.getKey() + " = " + info.getValue());
            }

            LinkedHashMap<String, String> libGoogle = new LinkedHashMap<String, String>();
            if (cmd.hasOption("google")) {
                libGoogle = getLibFromPatternInclude(adb, liblist, apkGoogle, Google, "Google", scanlibs);
                libGoogle = getLibFromPatternGlobalExclude(libGoogle, Google, "Google");
                System.out.println();
                System.out.println("Final list libraries (Google):");
                for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                    System.out.println(info.getKey() + " = " + info.getValue());
                }
            }

            LinkedHashMap<String, String> apkExclude = new LinkedHashMap<String, String>(apklist);
            for (String key : apkNormal.keySet()) {
                apkExclude.remove(key);
            }
            for (String key : apkGoogle.keySet()) {
                apkExclude.remove(key);
            }

            System.out.println();
            System.out.println("Include libraries from Exclude packages:");
            LinkedHashMap<String, String> libExclude = getLibFromPackage(adb, liblist, apkExclude);
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Normal):");
            for (Map.Entry<String, String> info : sortByValues(libNormal).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libNormal.remove(info.getKey());
                }
            }
            System.out.println();
            System.out.println("Enclude libraries from Exclude packages (Google):");
            for (Map.Entry<String, String> info : sortByValues(libGoogle).entrySet()) {
                if (libExclude.containsKey(info.getKey())) {
                    System.out.println("exclude: " + info.getKey() + " = " + libExclude.get(info.getKey()));
                    libGoogle.remove(info.getKey());
                }
            }

            System.out.println();
            System.out.println("Delete libraries (Normal):");
            damage(adb, "rm ", NotTest, libNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete libraries (Google):");
                damage(adb, "rm ", NotTest, libGoogle, 1);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Cleaning data packages (Normal):");
            damage(adb, "pm clear ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Cleaning data packages (Google):");
                damage(adb, "pm clear ", NotTest, apkGoogle, 2);
            }

            System.out.println();
            System.out.println("Uninstall packages (Normal):");
            damage(adb, "pm uninstall ", NotTest, apkNormal, 2);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Uninstall packages (Google):");
                damage(adb, "pm uninstall ", NotTest, apkGoogle, 2);
            }
        }

        if (cmd.hasOption("unapk")) {
            System.out.println();
            System.out.println("Delete packages (Normal):");
            LinkedHashMap<String, String> dexNormal = new LinkedHashMap<String, String>();
            for (Map.Entry<String, String> apk : apkNormal.entrySet()) {
                dexNormal.put(apk.getKey(), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                dexNormal.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
            }
            damage(adb, "rm ", NotTest, dexNormal, 1);
            if (cmd.hasOption("google")) {
                System.out.println();
                System.out.println("Delete packages (Google):");
                LinkedHashMap<String, String> dexGoogle = new LinkedHashMap<String, String>();
                for (Map.Entry<String, String> apk : apkGoogle.entrySet()) {
                    dexGoogle.put(apk.getKey(), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".dex"), apk.getValue());
                    dexGoogle.put(apk.getKey().replace(".apk", ".odex"), apk.getValue());
                }
                damage(adb, "rm ", NotTest, dexGoogle, 1);
            }
        }

        if (NotTest) {
            run(adb, "-s", lastdevice, "reboot");
        }
        System.out.println();
        System.out.println("FINISH :)");
    } catch (SAXException e) {
        System.out.println("Error parsing list: " + e);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:eu.fbk.utils.lsa.util.Anvur.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }/*from w w  w. j a v  a 2s  .c o m*/

    PropertyConfigurator.configure(logConfig);
    /*
    if (args.length != 2)
    {
    log.println("Usage: java -mx512M eu.fbk.utils.lsa.util.Anvur in-file out-dir");
    System.exit(1);
    }
            
    File l = new File(args[1]);
    if (!l.exists())
    {
    l.mkdir();
    }
    List<String[]> list = readText(new File(args[0]));
    String oldCategory = "";
    for (int i=0;i<list.size();i++)
    {
    String[] s = list.get(i);
    if (!oldCategory.equals(s[0]))
    {
    File f = new File(args[1] + File.separator + s[0]);
    boolean b = f.mkdir();
    logger.debug(f + " created " + b);
    }
            
    File g = new File(args[1] + File.separator + s[0] + File.separator + s[1] + ".txt");
    logger.debug("writing " + g + "...");
    PrintWriter pw = new PrintWriter(new FileWriter(g));
    //pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    if (s.length == 5)
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2] + " " + s[4].replace('_', ' ')));
    }
    else
    {
    pw.println(tokenize(s[1].substring(0, s[1].indexOf(".")).replace('_', ' ') + " " + s[2]));
    }
    pw.flush();
    pw.close();
            
    } // end for i
    */

    if (args.length != 7) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.Anvur input threshold size dim idf in-file-csv fields\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File Ut = new File(args[0] + "-Ut");
    File Sk = new File(args[0] + "-S");
    File r = new File(args[0] + "-row");
    File c = new File(args[0] + "-col");
    File df = new File(args[0] + "-df");
    double threshold = Double.parseDouble(args[1]);
    int size = Integer.parseInt(args[2]);
    int dim = Integer.parseInt(args[3]);
    boolean rescaleIdf = Boolean.parseBoolean(args[4]);

    //"author_check"0,   "authors"1,   "title"2,   "year"3,   "pubtype"4,   "publisher"5,   "journal"6,   "volume"7,   "number"8,   "pages"9,   "abstract"10,   "nauthors",   "citedby"
    String[] labels = { "author_check", "authors", "title", "year", "pubtype", "publisher", "journal", "volume",
            "number", "pages", "abstract", "nauthors", "citedby"
            //author_id   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    };
    String name = buildName(labels, args[6]);

    File bwf = new File(args[5] + name + "-bow.txt");
    PrintWriter bw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bwf), "UTF-8")));
    File bdf = new File(args[5] + name + "-bow.csv");
    PrintWriter bd = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bdf), "UTF-8")));
    File lwf = new File(args[5] + name + "-ls.txt");
    PrintWriter lw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(lwf), "UTF-8")));
    File ldf = new File(args[5] + name + "-ls.csv");
    PrintWriter ld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ldf), "UTF-8")));
    File blwf = new File(args[5] + name + "-bow+ls.txt");
    PrintWriter blw = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(blwf), "UTF-8")));
    File bldf = new File(args[5] + name + "-bow+ls.csv");
    PrintWriter bld = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(bldf), "UTF-8")));
    File logf = new File(args[5] + name + ".log");
    PrintWriter log = new PrintWriter(
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logf), "UTF-8")));

    //System.exit(0);
    LSM lsm = new LSM(Ut, Sk, r, c, df, dim, rescaleIdf);
    LSSimilarity lss = new LSSimilarity(lsm, size);

    List<String[]> list = readText(new File(args[5]));

    // author_check   authors   title   year   pubtype   publisher   journal   volume   number   pages   abstract   nauthors   citedby

    //header
    for (int i = 0; i < list.size(); i++) {
        String[] s1 = list.get(i);
        String t1 = s1[0].toLowerCase();
        bw.print("\t");
        lw.print("\t");
        blw.print("\t");
        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
    } // end for i

    bw.print("\n");
    lw.print("\n");
    blw.print("\n");
    for (int i = 0; i < list.size(); i++) {
        logger.info(i + "\t");
        String[] s1 = list.get(i);
        String t1 = buildText(s1, args[6]);
        BOW bow1 = new BOW(t1);
        logger.info(bow1);

        Vector d1 = lsm.mapDocument(bow1);
        d1.normalize();
        log.println("d1:" + d1);

        Vector pd1 = lsm.mapPseudoDocument(d1);
        pd1.normalize();
        log.println("pd1:" + pd1);

        Vector m1 = merge(pd1, d1);
        log.println("m1:" + m1);

        // write the orginal line
        for (int j = 0; j < s1.length; j++) {
            bd.print(s1[j]);
            bd.print("\t");
            ld.print(s1[j]);
            ld.print("\t");
            bld.print(s1[j]);
            bld.print("\t");

        }
        // write the bow, ls, and bow+ls vectors
        bd.println(d1);
        ld.println(pd1);
        bld.println(m1);

        bw.print(i + "(" + s1[0] + ")");
        lw.print(i + "(" + s1[0] + ")");
        blw.print(i + "(" + s1[0] + ")");
        for (int j = 0; j < i + 1; j++) {
            bw.print("\t");
            lw.print("\t");
            blw.print("\t");
        } // end for j

        for (int j = i + 1; j < list.size(); j++) {
            logger.info(i + "\t" + j);
            String[] s2 = list.get(j);

            String t2 = buildText(s2, args[6]);
            BOW bow2 = new BOW(t2);

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t1:" + t1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") t2:" + t2);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow1:" + bow1);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow2:" + bow2);

            Vector d2 = lsm.mapDocument(bow2);
            d2.normalize();
            log.println("d2:" + d2);

            Vector pd2 = lsm.mapPseudoDocument(d2);
            pd2.normalize();
            log.println("pd2:" + pd2);

            Vector m2 = merge(pd2, d2);
            log.println("m2:" + m2);

            float cosVSM = d1.dotProduct(d2) / (float) Math.sqrt(d1.dotProduct(d1) * d2.dotProduct(d2));
            float cosLSM = pd1.dotProduct(pd2) / (float) Math.sqrt(pd1.dotProduct(pd1) * pd2.dotProduct(pd2));
            float cosBOWLSM = m1.dotProduct(m2) / (float) Math.sqrt(m1.dotProduct(m1) * m2.dotProduct(m2));
            bw.print("\t");
            bw.print(dec.format(cosVSM));
            lw.print("\t");
            lw.print(dec.format(cosLSM));
            blw.print("\t");
            blw.print(dec.format(cosBOWLSM));

            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow\t" + cosVSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") ls:\t" + cosLSM);
            log.println(i + ":" + j + "(" + s1[0] + ":" + s2[0] + ") bow+ls:\t" + cosBOWLSM);
        }
        bw.print("\n");
        lw.print("\n");
        blw.print("\n");
    } // end for i

    logger.info("wrote " + bwf);
    logger.info("wrote " + bwf);
    logger.info("wrote " + bdf);
    logger.info("wrote " + lwf);
    logger.info("wrote " + ldf);
    logger.info("wrote " + blwf);
    logger.info("wrote " + bldf);
    logger.info("wrote " + logf);

    ld.close();
    bd.close();
    bld.close();
    bw.close();
    lw.close();
    blw.close();

    log.close();

}

From source file:lambertmrev.LambertMRev.java

/**
 * @param args the command line arguments
 *//*from  www.  jav a2  s.c o  m*/
public static void main(String[] args) {
    // Want to test the Lambert class so you can specify the number of revs for which to compute
    //System.out.print("this is the frames tutorial \n");
    try {
        Frame inertialFrame = FramesFactory.getEME2000();
        TimeScale utc = TimeScalesFactory.getTAI();
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, utc);
        double mu = 3.986004415e+14;

        double a = 24396159; // semi major axis in meters
        double e = 0.72831215; // eccentricity
        double i = Math.toRadians(7); // inclination
        double omega = Math.toRadians(180); // perigee argument
        double raan = Math.toRadians(261); // right ascension of ascending node
        double lM = 0; // mean anomaly

        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        //KeplerianPropagator kepler = new KeplerianPropagator(initialOrbit);

        // set geocentric positions
        Vector3D r1 = new Vector3D(-6.88999e3, 3.92763e4, 2.67053e3);
        Vector3D r2 = new Vector3D(-3.41458e4, 2.05328e4, 3.44315e3);
        Vector3D r1_site = new Vector3D(4.72599e3, 1.26633e3, 4.07799e3);
        Vector3D r2_site = new Vector3D(4.70819e3, 1.33099e3, 4.07799e3);

        // get the topocentric positions
        Vector3D top1 = Transform.geo2radec(r1.scalarMultiply(1000), r1_site.scalarMultiply(1000));
        Vector3D top2 = Transform.geo2radec(r2.scalarMultiply(1000), r2_site.scalarMultiply(1000));

        // time of flight in seconds
        double tof = 3 * 3600;

        // propagate to 0 and tof
        Lambert test = new Lambert();

        boolean cw = false;
        int multi_revs = 1;
        RealMatrix v1_mat;
        Random randomGenerator = new Random();

        PrintWriter out_a = new PrintWriter("out_java_a.txt");
        PrintWriter out_e = new PrintWriter("out_java_e.txt");
        PrintWriter out_rho1 = new PrintWriter("out_java_rho1.txt");
        PrintWriter out_rho2 = new PrintWriter("out_java_rho2.txt");

        // start the loop
        double A, Ecc, rho1, rho2, tof_hyp;

        long time1 = System.nanoTime();
        for (int ll = 0; ll < 1e6; ll++) {

            rho1 = top1.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top1.getZ() / 1000;
            rho2 = top2.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top2.getZ() / 1000;
            //tof_hyp = FastMath.abs(tof + 0.1*3600 * randomGenerator.nextGaussian());
            // from topo to geo
            Vector3D r1_hyp = Transform.radec2geo(top1.getX(), top1.getY(), rho1, r1_site);
            Vector3D r2_hyp = Transform.radec2geo(top2.getX(), top2.getY(), rho2, r2_site);
            //            System.out.println(r1_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(r2_hyp.scalarMultiply(1000).getNorm());
            //            System.out.println(tof/3600);
            test.lambert_problem(r1_hyp.scalarMultiply(1000), r2_hyp.scalarMultiply(1000), tof, mu, cw,
                    multi_revs);

            v1_mat = test.get_v1();

            Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
            //            System.out.println(v1);
            PVCoordinates rv1 = new PVCoordinates(r1_hyp.scalarMultiply(1000), v1);
            Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
            A = orbit_out.getA();
            Ecc = orbit_out.getE();

            //            System.out.println(ll + " - " +A);
            out_a.println(A);
            out_e.println(Ecc);
            out_rho1.println(rho1);
            out_rho2.println(rho2);
        }
        long time2 = System.nanoTime();
        long timeTaken = time2 - time1;

        out_a.close();
        out_e.close();
        out_rho1.close();
        out_rho2.close();

        System.out.println("Time taken " + timeTaken / 1000 / 1000 + " milli secs");

        // get the truth
        test.lambert_problem(r1.scalarMultiply(1000), r2.scalarMultiply(1000), tof, mu, cw, multi_revs);
        v1_mat = test.get_v1();
        Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2));
        PVCoordinates rv1 = new PVCoordinates(r1.scalarMultiply(1000), v1);
        Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu);
        //System.out.println(orbit_out.getA());
    } catch (FileNotFoundException ex) {
        Logger.getLogger(LambertMRev.class.getName()).log(Level.SEVERE, null, ex);
    }
}