Example usage for org.apache.commons.io FileUtils writeLines

List of usage examples for org.apache.commons.io FileUtils writeLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeLines.

Prototype

public static void writeLines(File file, Collection lines, String lineEnding) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:com.taobao.android.object.DexDiffInfo.java

public void writeToFile(String bundleName, File diffFile, File diffJsonFile) throws IOException {
    JSONArray jsonArray = new JSONArray();
    if (diffJsonFile.exists()) {
        String content = FileUtils.readFileToString(diffJsonFile);
        jsonArray = JSONArray.parseArray(content);
    }/*from   w  ww. j av  a2s  . c  om*/
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("bundleName", bundleName);
    if (addedMethods.size() > 0) {
        List<String> addMethods = new ArrayList<String>();
        List<MethodDiffInfoObject> diffInfoObjects = new ArrayList<MethodDiffInfoObject>();
        for (DexBackedMethod method : addedMethods) {
            addMethods.add("[add new Method:]" + method.getReturnType() + "  " + method.getName() + "("
                    + Formater.formatStringList(method.getParameterTypes()) + ")  in Class:"
                    + method.getDefiningClass());
            MethodDiffInfoObject diffInfoObject = new MethodDiffInfoObject();
            diffInfoObject.setDiffType(DiffType.ADD);
            diffInfoObject.setReturnType(method.getReturnType());
            diffInfoObject.setMethodDeclaration(
                    method.getName() + "(" + Formater.formatStringList(method.getParameterTypes()) + ")");
            diffInfoObject.setInClass(method.getDefiningClass());
            diffInfoObjects.add(diffInfoObject);
        }
        FileUtils.writeLines(diffFile, addMethods, true);
        jsonObject.put("addedMethods", diffInfoObjects);
    }
    if (modifiedMethods.size() > 0) {
        List<String> modifyMethods = new ArrayList<String>();
        List<MethodDiffInfoObject> diffInfoObjects = new ArrayList<MethodDiffInfoObject>();

        for (DexBackedMethod method : modifiedMethods) {
            modifyMethods.add("[modify Method:]" + method.getReturnType() + "  " + method.getName() + "("
                    + Formater.formatStringList(method.getParameterTypes()) + ")  in Class:"
                    + method.getDefiningClass());
            MethodDiffInfoObject diffInfoObject = new MethodDiffInfoObject();
            diffInfoObject.setDiffType(DiffType.MODIFY);
            diffInfoObject.setReturnType(method.getReturnType());
            diffInfoObject.setMethodDeclaration(
                    method.getName() + "(" + Formater.formatStringList(method.getParameterTypes()) + ")");
            diffInfoObject.setInClass(method.getDefiningClass());
            diffInfoObjects.add(diffInfoObject);
        }
        FileUtils.writeLines(diffFile, modifyMethods, true);
        jsonObject.put("modifiedMethods", diffInfoObjects);
    }
    jsonArray.add(jsonObject);
    FileUtils.writeStringToFile(diffJsonFile, JSON.toJSONString(jsonArray));
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Updates the dependency graph with new information for an XMLVM file.
 * /*w  w  w. ja v a  2s .c  o m*/
 * @param xmlvmFile The xmlvm file that is being added to the dependency graph.
 * @param oldReferences Map of the previous references that this file has.  The inverse dependencies
 * Will need to be removed.
 * @param destDir The directory where dependencies are stored
 * @throws IOException 
 */
private void updateDependencyGraphForFile(File xmlvmFile, Map<String, String> oldReferences, File destDir)
        throws IOException {
    try {
        String ns = "http://xmlvm.org";
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlvmFile);

        NodeList classes = doc.getElementsByTagName("vm:class");
        if (classes.getLength() == 0) {
            return;
        }

        Element clsEl = (Element) classes.item(0);
        StringBuilder sb = new StringBuilder().append(clsEl.getAttribute("package"));
        if (sb.length() > 0) {
            sb.append(".");
        }
        sb.append(clsEl.getAttribute("name"));
        String fqn = sb.toString();

        // Remove old references
        for (Map.Entry<String, String> entry : oldReferences.entrySet()) {
            String cls = entry.getKey();
            String kind = entry.getValue();
            File depsFile = new File(destDir, cls + ".deps");
            if (depsFile.exists()) {
                List<String> deps = FileUtils.readLines(depsFile);
                List<String> strippedDeps = new ArrayList<String>();
                for (String line : deps) {
                    if (line.equals(cls + " " + kind)) {
                        // Do nothing
                    } else {
                        strippedDeps.add(line);
                    }
                }
                FileUtils.writeLines(depsFile, strippedDeps, false);
            }
        }

        // Now add new references

        NodeList refs = doc.getElementsByTagName("vm:reference");
        //System.out.println("Refs len: " + refs.getLength());
        int len = refs.getLength();
        for (int i = 0; i < len; i++) {
            Element el = (Element) refs.item(i);
            String className = el.getAttribute("name");
            File depsFile = new File(destDir, className + ".deps");
            if (!depsFile.exists()) {
                depsFile.createNewFile();
            }
            String usage = el.getAttribute("kind");

            FileUtils.writeStringToFile(depsFile, fqn + " " + usage + "\n", true);

        }
    } catch (ParserConfigurationException | SAXException ex) {
        Logger.getLogger(XMLVM.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}

From source file:ai.api.sample.AIDialogSampleActivity.java

private void serachLaptopAmazon(String keyword, String manufacturer, String mini, String maxi) {

    // Get shared client
    AWSECommerceServicePortType_SOAPClient client = AWSECommerceClient.getSharedClient();
    client.setDebug(true);//from www .j  av  a2s .co  m

    // Build request
    ItemSearch request = new ItemSearch();
    request.associateTag = "teg"; // seems any tag is ok
    request.shared = new ItemSearchRequest();
    request.shared.searchIndex = "Electronics";

    request.shared.responseGroup = new ArrayList<String>();
    request.shared.responseGroup.add("Images");
    request.shared.responseGroup.add("Small");

    ItemSearchRequest itemSearchRequest = new ItemSearchRequest();

    if (keyword.charAt(0) == 'g' || keyword.charAt(0) == 'G' || keyword.equalsIgnoreCase("gaining")
            || keyword.equalsIgnoreCase("giving") || keyword.equalsIgnoreCase("gimme")
            || keyword.equalsIgnoreCase("jimme") || keyword.equalsIgnoreCase("MN")) {
        keyword = "gaming";
    }

    itemSearchRequest.keywords = keyword;

    itemSearchRequest.browseNode = "13896615011";
    itemSearchRequest.browseNode = "565108";

    itemSearchRequest.sort = "salesrank";

    if (manufacturer.equalsIgnoreCase("HBO") || manufacturer.equalsIgnoreCase("FB")
            || manufacturer.equalsIgnoreCase("HD") || manufacturer.equalsIgnoreCase("XP")
            || manufacturer.length() == 2 || manufacturer.equalsIgnoreCase("xb")) {
        Log.i("changing ", manufacturer);
        manufacturer = "HP";
    }

    if (manufacturer.equalsIgnoreCase("adelle") || manufacturer.equalsIgnoreCase("adele")
            || manufacturer.equalsIgnoreCase("Bell") || manufacturer.equalsIgnoreCase("Den")) {
        manufacturer = "Dell";
    }

    itemSearchRequest.manufacturer = manufacturer;
    BigInteger min = new BigInteger(mini + "00");
    BigInteger max = new BigInteger(maxi + "00");

    itemSearchRequest.minimumPrice = min;

    itemSearchRequest.maximumPrice = max;

    request.request = new ArrayList<ItemSearchRequest>();
    request.request.add(itemSearchRequest);

    // authenticate the request
    // http://docs.aws.amazon.com/AWSECommerceService/latest/DG/NotUsingWSSecurity.html
    AWSECommerceClient.authenticateRequest("ItemSearch");
    // Make API call and register callbacks
    client.itemSearch(request, new SOAPServiceCallback<ItemSearchResponse>() {

        @Override
        public void onSuccess(ItemSearchResponse responseObject) {
            // success handling logic
            if (responseObject.items != null && responseObject.items.size() > 0) {

                Items items = responseObject.items.get(0);

                /*for(Items i : responseObject.items)
                {
                if(i!=null) {
                    for (Item ii : i.item) {
                        Log.i("Checking Items", ii.detailPageURL);
                    }
                }
                }*/

                if (items.item != null && items.item.size() > 0) {
                    Item item = items.item.get(0);
                    Toast.makeText(AIDialogSampleActivity.this, item.itemAttributes.title, Toast.LENGTH_LONG)
                            .show();

                    Log.i("Searchresult", items.item.get(1).itemAttributes.title);
                    Log.i("Searchresult", items.item.get(2).itemAttributes.title);

                    Log.i("SearchresultExtended", items.item.get(0).itemAttributes.title);

                    if (items.item.get(0).itemAttributes.audienceRating != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.audienceRating);
                    else
                        Log.i("SearchresultExtended", "rating is null");

                    if (items.item.get(0).itemAttributes.manufacturer != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.manufacturer);
                    else
                        Log.i("SearchresultExtended", "manufacturer is null");

                    if (items.item.get(0).itemAttributes.listPrice != null)
                        Log.i("SearchresultExtended", items.item.get(0).itemAttributes.listPrice.toString());

                    TTS.speakadd("I think the best product is ");
                    TTS.speakadd(item.itemAttributes.title);
                    TTS.speakadd("Dont worry! I have added links for top 3 product to your Speakbuy app");
                    TTS.speakadd("Do you want to continue using speakbuy?");

                    //code to save links
                    int x = 0;

                    try {

                        for (Items i : responseObject.items) {
                            for (Item ii : i.item) {

                                Log.i("Checking Items", ii.detailPageURL);
                                if (x < 3) {
                                    //ReminderActivity.itemsAdapter.add(ii.detailPageURL);
                                    itemsToAdd.add(ii.detailPageURL);
                                }
                                x++;
                            }
                        }
                    } catch (NullPointerException e) {

                        Toast.makeText(AIDialogSampleActivity.this, "Some error Occured", Toast.LENGTH_LONG)
                                .show();
                    }

                    File filesDir = getFilesDir();
                    File todoFile = new File(filesDir, "todo.txt");
                    try {

                        FileUtils.writeLines(todoFile, itemsToAdd, true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //TTS.speakadd(items.item.get(1).itemAttributes.title);
                    //TTS.speakadd("Next item is :");
                    //TTS.speakadd(items.item.get(2).itemAttributes.title);

                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    TTS.speakadd("Sorry, I found no products in that price range");
                    TTS.speakadd("Do you want to continue using speakbuy?");
                }

            } else {
                if (responseObject.operationRequest != null && responseObject.operationRequest.errors != null) {
                    Errors errors = responseObject.operationRequest.errors;
                    if (errors.error != null && errors.error.size() > 0) {
                        com.amazon.webservices.awsecommerceservice._2011_08_01.errors.Error error = errors.error
                                .get(0);
                        Toast.makeText(AIDialogSampleActivity.this, error.message, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(AIDialogSampleActivity.this, "No result", Toast.LENGTH_LONG).show();
                }
            }

        }

        @Override
        public void onFailure(Throwable error, String errorMessage) { // http or parsing error
            //Toast.makeText(AmazonSearchActivity.this, errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSOAPFault(Object soapFault) { // soap fault
            com.leansoft.nano.soap11.Fault fault = (com.leansoft.nano.soap11.Fault) soapFault;
            //Toast.makeText(AmazonSearchActivity.this, fault.faultstring, Toast.LENGTH_LONG).show();
        }

    });

}

From source file:net.sourceforge.seqware.pipeline.tutorial.DeveloperPhase1.java

@Test
public void testModifyingTheWorkflow() throws IOException {
    Log.info("Editing java client at " + JavaClient.getAbsolutePath());
    List<String> readLines = FileUtils.readLines(JavaClient);
    // edit lines to match tutorial changes
    boolean linesAdded = false;
    for (int i = 0; i < readLines.size(); i++) {
        if (readLines.get(i).contains("job11.addParent(job00)")) {
            readLines.add(i + 1,//ww w . j  a  v a  2 s .  c om
                    "\nJob job12 = this.getWorkflow().createBashJob(\"bash_date\");\njob12.setCommand(\"date > dir1/time\");\njob12.addParent(job11);");
            linesAdded = true;
        }
    }
    Assert.assertTrue("lines were not added", linesAdded);
    // write back modified lines
    FileUtils.writeLines(JavaClient, readLines, false);
    //build and install modified bundle
    File buildDir = BundleDir;
    Log.info("build dir detected as " + buildDir.getAbsolutePath());
    String command = "mvn install";
    String genOutput = ITUtility.runArbitraryCommand(command, 0, buildDir);
}

From source file:opennlp.tools.parse_thicket.kernel_interface.TreeKernelBasedClassifier.java

public Boolean classifyText(File f) {
    FileUtils.deleteQuietly(new File(path + unknownToBeClassified));
    if (!(new File(path + modelFileName).exists())) {
        LOG.severe("Model file '" + modelFileName + "'is absent: skip SVM classification");
        return null;
    }/*from   w w w.  jav  a 2s. co  m*/
    Map<Integer, Integer> countObject = new HashMap<Integer, Integer>();
    int itemCount = 0, objectCount = 0;
    List<String> treeBankBuffer = new ArrayList<String>();
    List<String> texts = DescriptiveParagraphFromDocExtractor.getLongParagraphsFromFile(f);
    List<String> lines = formTreeKernelStructuresMultiplePara(texts, "0");
    for (String l : lines) {
        countObject.put(itemCount, objectCount);
        itemCount++;
    }
    objectCount++;
    treeBankBuffer.addAll(lines);

    // write the lists of samples to a file
    try {
        FileUtils.writeLines(new File(path + unknownToBeClassified), null, treeBankBuffer);
    } catch (IOException e) {
        LOG.severe("Problem creating parse thicket files '" + path + unknownToBeClassified
                + "' to be classified\n" + e.getMessage());
    }

    tkRunner.runClassifier(path, unknownToBeClassified, modelFileName, classifierOutput);
    // read classification results
    List<String[]> classifResults = ProfileReaderWriter.readProfiles(path + classifierOutput, ' ');

    itemCount = 0;
    objectCount = 0;
    int currentItemCount = 0;
    float accum = 0;
    LOG.info("\nsvm scores per paragraph: ");
    for (String[] line : classifResults) {
        Float val = Float.parseFloat(line[0]);
        System.out.print(val + " ");
        accum += val;
        currentItemCount++;
    }

    float averaged = accum / (float) currentItemCount;
    LOG.info("\n average = " + averaged);
    currentItemCount = 0;
    Boolean in = false;
    if (averaged > MIN_SVM_SCORE_TOBE_IN)
        return true;
    else
        return false;
}

From source file:opennlp.tools.parse_thicket.kernel_interface.TreeKernelBasedClassifierMultiplePara.java

public void trainClassifier(String posDirectory, String negDirectory) {

    queuePos.clear();//w ww  . j a  v  a2s.  c  om
    queueNeg.clear();
    addFilesPos(new File(posDirectory));
    addFilesNeg(new File(negDirectory));

    List<File> filesPos = new ArrayList<File>(queuePos), filesNeg = new ArrayList<File>(queueNeg);

    Collection<String> treeBankBuffer = new ArrayList<String>();
    int countPos = 0, countNeg = 0;

    for (File f : filesPos) {
        // get first paragraph of text
        List<String> texts = DescriptiveParagraphFromDocExtractor.getLongParagraphsFromFile(f);
        List<String> lines = formTreeKernelStructuresMultiplePara(texts, "1");
        treeBankBuffer.addAll(lines);
        if (bShortRun && countPos > 3000)
            break;

        countPos++;
    }
    for (File f : filesNeg) {
        // get first paragraph of text
        List<String> texts = DescriptiveParagraphFromDocExtractor.getLongParagraphsFromFile(f);
        List<String> lines = formTreeKernelStructuresMultiplePara(texts, "-1");
        treeBankBuffer.addAll(lines);
        if (bShortRun && countNeg > 3000)
            break;

        countNeg++;
    }

    // write the lists of samples to a file
    try {
        FileUtils.writeLines(new File(path + trainingFileName), null, treeBankBuffer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // ProfileReaderWriter.writeReport(treeBankBuffer,
    // path+trainingFileName, ' ');
    // build the model
    tkRunner.runLearner(path, trainingFileName, modelFileName);
}

From source file:opennlp.tools.parse_thicket.kernel_interface.TreeKernelBasedClassifierMultiplePara.java

public List<String[]> classifyFilesInDirectory(String dirFilesToBeClassified) {
    Map<Integer, Integer> countObject = new HashMap<Integer, Integer>();
    int itemCount = 0, objectCount = 0;
    List<String> treeBankBuffer = new ArrayList<String>();
    queuePos.clear();/*from ww w .  j av  a  2  s  .co m*/
    addFilesPos(new File(dirFilesToBeClassified));
    List<File> filesUnkn = new ArrayList<File>(queuePos);
    for (File f : filesUnkn) {
        List<String> texts = DescriptiveParagraphFromDocExtractor.getLongParagraphsFromFile(f);
        List<String> lines = formTreeKernelStructuresMultiplePara(texts, "0");
        for (String l : lines) {
            countObject.put(itemCount, objectCount);
            itemCount++;
        }
        objectCount++;
        treeBankBuffer.addAll(lines);
    }
    // write the lists of samples to a file
    try {
        FileUtils.writeLines(new File(path + unknownToBeClassified), null, treeBankBuffer);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    tkRunner.runClassifier(path, unknownToBeClassified, modelFileName, classifierOutput);
    // read classification results
    List<String[]> classifResults = ProfileReaderWriter.readProfiles(path + classifierOutput, ' ');
    // iterate through classification results and set them as scores for
    // hits
    List<String[]> results = new ArrayList<String[]>();

    itemCount = 0;
    objectCount = 0;
    int currentItemCount = 0;
    float accum = 0;
    for (String[] line : classifResults) {
        Float val = Float.parseFloat(line[0]);
        accum += val;
        // last line
        Boolean bLastLine = false;
        if (itemCount == classifResults.size() - 1)
            bLastLine = true;

        if (objectCount == countObject.get(itemCount) /* && !bLastLine */) {
            itemCount++;
            currentItemCount++;
            continue;
        } else
            while (objectCount != countObject.get(itemCount) - 1) {
                objectCount++;
                String[] rline = new String[] { filesUnkn.get(objectCount).getName(), "unknown", "0",
                        filesUnkn.get(objectCount).getAbsolutePath(), new Integer(itemCount).toString(),
                        new Integer(objectCount).toString() };
                results.add(rline);
            }
        objectCount = countObject.get(itemCount);
        itemCount++;

        float averaged = accum / (float) currentItemCount;
        currentItemCount = 0;
        Boolean in = false;
        if (averaged > MIN_SVM_SCORE_TOBE_IN)
            in = true;

        String[] rline = new String[] { filesUnkn.get(objectCount).getName(), in.toString(),
                new Float(averaged).toString(), filesUnkn.get(objectCount).getAbsolutePath(),
                new Integer(itemCount).toString(), new Integer(objectCount).toString() };
        results.add(rline);
        accum = 0;
    }
    return results;

}

From source file:org.apache.ambari.server.security.encryption.MasterKeyServiceImpl.java

private void persistMaster(File masterFile) {
    EncryptionResult atom = encryptMaster(master);
    try {/*from   w w w.  j  a  v  a  2 s  .  c o  m*/
        ArrayList<String> lines = new ArrayList<String>();
        lines.add(MASTER_PERSISTENCE_TAG);

        String line = Base64.encodeBase64String(
                (Base64.encodeBase64String(atom.salt) + "::" + Base64.encodeBase64String(atom.iv) + "::"
                        + Base64.encodeBase64String(atom.cipher)).getBytes("UTF8"));
        lines.add(line);
        FileUtils.writeLines(masterFile, "UTF8", lines);

        // restrict os permissions to only the user running this process
        chmod("600", masterFile);
    } catch (IOException e) {
        LOG.error("Failed to persist master. " + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.CMFMasterService.java

protected void persistMaster(char[] master, File masterFile) {
    EncryptionResult atom = encryptMaster(master);
    try {/*from   w  w w . j a  va 2s.c  o  m*/
        ArrayList<String> lines = new ArrayList<String>();
        lines.add(MASTER_PERSISTENCE_TAG);

        String line = Base64.encodeBase64String(
                (Base64.encodeBase64String(atom.salt) + "::" + Base64.encodeBase64String(atom.iv) + "::"
                        + Base64.encodeBase64String(atom.cipher)).getBytes("UTF8"));
        lines.add(line);
        FileUtils.writeLines(masterFile, "UTF8", lines);

        // restrict os permissions to only the user running this process
        chmod("600", masterFile);
    } catch (IOException e) {
        LOG.failedToPersistMasterSecret(e);
    }
}

From source file:org.apache.hadoop.gateway.services.security.impl.DefaultMasterService.java

private void persistMaster(char[] master, File masterFile) {
    EncryptionResult atom = encryptMaster(master);
    try {//from w  w w.  j a v  a 2  s  .c  o m
        ArrayList<String> lines = new ArrayList<String>();
        lines.add(MASTER_PERSISTENCE_TAG);

        String line = Base64.encodeBase64String(
                (Base64.encodeBase64String(atom.salt) + "::" + Base64.encodeBase64String(atom.iv) + "::"
                        + Base64.encodeBase64String(atom.cipher)).getBytes("UTF8"));
        lines.add(line);
        FileUtils.writeLines(masterFile, "UTF8", lines);

        // restrict os permissions to only the user running this process
        chmod("600", masterFile);
    } catch (IOException e) {
        // TODO log appropriate message that the master secret has not been persisted
        e.printStackTrace();
    }
}