Example usage for java.io BufferedWriter write

List of usage examples for java.io BufferedWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:edu.iu.daal_naive.NaiveUtil.java

static void generateGroundTruth(int numOfDataPoints, int nClasses, String localInputDir, FileSystem fs,
        Path dataDir) throws IOException, InterruptedException, ExecutionException {

    // Check data directory
    if (fs.exists(dataDir)) {
        fs.delete(dataDir, true);/*ww w  . j  a v  a2  s  .c om*/
    }
    // Check local directory
    File localDir = new File(localInputDir);
    // If existed, regenerate data
    if (localDir.exists() && localDir.isDirectory()) {
        for (File file : localDir.listFiles()) {
            file.delete();
        }
        localDir.delete();

    }
    boolean success = localDir.mkdir();
    if (success) {
        System.out.println("Directory: " + localInputDir + " created");
    }

    // generate test points
    BufferedWriter writer = new BufferedWriter(new FileWriter(localInputDir + File.separator + "groundtruth"));
    Random random = new Random();

    // double point = 0;
    int label = 0;
    for (int i = 0; i < numOfDataPoints; i++) {
        // for (int j = 0; j < vectorSize; j++) {
        //    point = random.nextDouble()*2 -1;
        //    writer.write(String.valueOf(point));
        //    writer.write(",");
        // }
        label = random.nextInt(nClasses);
        writer.write(String.valueOf(label));
        writer.newLine();
    }

    writer.close();
    System.out.println("Write groundtruth data file");

    // Wrap to path object
    Path localInput = new Path(localInputDir);
    fs.copyFromLocalFile(localInput, dataDir);

}

From source file:com.microsoft.azure.management.containerinstance.samples.ManageContainerInstanceZeroToOneAndOneToManyUsingKubernetesOrchestration.java

/**
 * Main function which runs the actual sample.
 *
 * @param azure instance of the azure client
 * @param clientId secondary service principal client ID
 * @param secret secondary service principal secret
 * @return true if sample runs successfully
 *//*  www .ja  v  a  2s  .  c o m*/
public static boolean runSample(Azure azure, String clientId, String secret) {
    final String rgName = SdkContext.randomResourceName("rgaci", 15);
    final Region region = Region.US_WEST;

    final String acrName = SdkContext.randomResourceName("acr", 20);

    final String aciName = SdkContext.randomResourceName("acisample", 20);
    final String containerImageName = "microsoft/aci-helloworld";
    final String containerImageTag = "latest";
    final String dockerContainerName = "sample-hello";

    final String acsName = SdkContext.randomResourceName("acssample", 30);
    String servicePrincipalClientId = clientId; // replace with a real service principal client id
    String servicePrincipalSecret = secret; // and corresponding secret
    final String rootUserName = "acsuser";
    String acsSecretName = "mysecret112233";
    String acsNamespace = "acrsample";
    String acsLbIngressName = "lb-acrsample";
    SSHShell shell = null;

    try {
        //=============================================================
        // Create an Azure Container Registry to store and manage private Docker container images

        System.out.println("Creating an Azure Container Registry");

        Date t1 = new Date();

        Registry azureRegistry = azure.containerRegistries().define(acrName).withRegion(region)
                .withNewResourceGroup(rgName).withBasicSku().withRegistryNameAsAdminUser().create();

        Date t2 = new Date();
        System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000)
                + " seconds) " + azureRegistry.id());
        Utils.print(azureRegistry);

        //=============================================================
        // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry

        RegistryCredentials acrCredentials = azureRegistry.getCredentials();
        DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region,
                azureRegistry.loginServerUrl(), acrCredentials.username(),
                acrCredentials.accessKeys().get(AccessKeyType.PRIMARY));

        //=============================================================
        // Pull a temp image from public Docker repo and create a temporary container from that image
        // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR

        dockerClient.pullImageCmd(containerImageName).withTag(containerImageTag)
                .exec(new PullImageResultCallback()).awaitSuccess();
        System.out.println("List local Docker images:");
        List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
        for (Image image : images) {
            System.out.format("\tFound Docker image %s (%s)\n", image.getRepoTags()[0], image.getId());
        }

        CreateContainerResponse dockerContainerInstance = dockerClient
                .createContainerCmd(containerImageName + ":" + containerImageTag).withName(dockerContainerName)
                .exec();
        System.out.println("List Docker containers:");
        List<Container> dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : dockerContainers) {
            System.out.format("\tFound Docker container %s (%s)\n", container.getImage(), container.getId());
        }

        //=============================================================
        // Commit the new container

        String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName;
        String dockerImageId = dockerClient.commitCmd(dockerContainerInstance.getId())
                .withRepository(privateRepoUrl).withTag("latest").exec();

        // We can now remove the temporary container instance
        dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec();

        //=============================================================
        // Push the new Docker image to the Azure Container Registry

        dockerClient.pushImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig())
                .exec(new PushImageResultCallback()).awaitSuccess();

        // Remove the temp image from the local Docker host
        try {
            dockerClient.removeImageCmd(containerImageName + ":" + containerImageTag).withForce(true).exec();
        } catch (NotFoundException e) {
            // just ignore if not exist
        }

        //=============================================================
        // Create a container group with one container instance of default CPU core count and memory size
        //   using public Docker image "microsoft/aci-helloworld" and mounts a new file share as read/write
        //   shared container volume.

        ContainerGroup containerGroup = azure.containerGroups().define(aciName).withRegion(region)
                .withNewResourceGroup(rgName).withLinux()
                .withPrivateImageRegistry(azureRegistry.loginServerUrl(), acrCredentials.username(),
                        acrCredentials.accessKeys().get(AccessKeyType.PRIMARY))
                .withoutVolume().defineContainerInstance(aciName).withImage(privateRepoUrl)
                .withExternalTcpPort(80).attach().create();

        Utils.print(containerGroup);

        //=============================================================
        // Check that the container instance is up and running

        // warm up
        System.out.println("Warming up " + containerGroup.ipAddress());
        Utils.curl("http://" + containerGroup.ipAddress());
        SdkContext.sleep(15000);
        System.out.println("CURLing " + containerGroup.ipAddress());
        System.out.println(Utils.curl("http://" + containerGroup.ipAddress()));

        //=============================================================
        // Check the container instance logs

        String logContent = containerGroup.getLogContent(aciName);
        System.out.format("Logs for container instance: %s\n%s", aciName, logContent);

        //=============================================================
        // If service principal client id and secret are not set via the local variables, attempt to read the service
        //   principal client id and secret from a secondary ".azureauth" file set through an environment variable.
        //
        //   If the environment variable was not set then reuse the main service principal set for running this sample.

        if (servicePrincipalClientId.isEmpty() || servicePrincipalSecret.isEmpty()) {
            String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");

            if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty()
                    || !Files.exists(Paths.get(envSecondaryServicePrincipal))) {
                envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
            }

            servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal);
            servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal);
        }

        //=============================================================
        // Create an SSH private/public key pair to be used when creating the container service

        System.out.println("Creating an SSH private and public key pair");

        SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS");
        System.out.println("SSH private key value: \n" + sshKeys.getSshPrivateKey());
        System.out.println("SSH public key value: \n" + sshKeys.getSshPublicKey());

        //=============================================================
        // Create an Azure Container Service with Kubernetes orchestration

        System.out.println(
                "Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)");

        t1 = new Date();

        ContainerService azureContainerService = azure.containerServices().define(acsName).withRegion(region)
                .withNewResourceGroup(rgName).withKubernetesOrchestration()
                .withServicePrincipal(servicePrincipalClientId, servicePrincipalSecret).withLinux()
                .withRootUsername(rootUserName).withSshKey(sshKeys.getSshPublicKey())
                .withMasterNodeCount(ContainerServiceMasterProfileCount.MIN)
                .withMasterLeafDomainLabel("dns-" + acsName).defineAgentPool("agentpool").withVMCount(1)
                .withVMSize(ContainerServiceVMSizeTypes.STANDARD_D1_V2).withLeafDomainLabel("dns-ap-" + acsName)
                .attach().create();

        t2 = new Date();
        System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000)
                + " seconds) " + azureContainerService.id());
        Utils.print(azureContainerService);

        Thread.sleep(30000);

        //=============================================================
        // Download the Kubernetes config file from one of the master virtual machines

        azureContainerService = azure.containerServices().getByResourceGroup(rgName, acsName);
        System.out.println("Found Kubernetes master at: " + azureContainerService.masterFqdn());

        shell = SSHShell.open(azureContainerService.masterFqdn(), 22, rootUserName,
                sshKeys.getSshPrivateKey().getBytes());

        String kubeConfigContent = shell.download("config", ".kube", true);
        System.out.println("Found Kubernetes config:\n" + kubeConfigContent);

        //=============================================================
        // Instantiate the Kubernetes client using the downloaded ".kube/config" file content
        //     The Kubernetes client API requires setting an environment variable pointing at a real file;
        //        we will create a temporary file that will be deleted automatically when the sample exits

        File tempKubeConfigFile = File.createTempFile("kube", ".config",
                new File(System.getProperty("java.io.tmpdir")));
        tempKubeConfigFile.deleteOnExit();
        BufferedWriter buffOut = new BufferedWriter(new FileWriter(tempKubeConfigFile));
        buffOut.write(kubeConfigContent);
        buffOut.close();

        System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath());
        Config config = new Config();
        KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);

        Thread.sleep(5000);

        //=============================================================
        // List all the nodes available in the Kubernetes cluster

        System.out.println(kubernetesClient.nodes().list());

        //=============================================================
        // Create a namespace where all the sample Kubernetes resources will be created

        Namespace ns = new NamespaceBuilder().withNewMetadata().withName(acsNamespace)
                .addToLabels("acr", "sample").endMetadata().build();
        try {
            System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns));
        } catch (Exception ignored) {
        }

        Thread.sleep(5000);
        for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) {
            System.out.println("\tFound Kubernetes namespace: " + namespace.toString());
        }

        //=============================================================
        // Create a secret of type "docker-repository" that will be used for downloading the container image from
        //     our Azure private container repo

        String basicAuth = new String(Base64.encodeBase64(
                (acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY))
                        .getBytes()));
        HashMap<String, String> secretData = new HashMap<>(1);
        String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }",
                azureRegistry.loginServerUrl(), basicAuth, "acrsample@azure.com");

        dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8");
        secretData.put(".dockercfg", dockerCfg);
        SecretBuilder secretBuilder = new SecretBuilder().withNewMetadata().withName(acsSecretName)
                .withNamespace(acsNamespace).endMetadata().withData(secretData)
                .withType("kubernetes.io/dockercfg");

        System.out.println("Creating new secret: "
                + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build()));

        Thread.sleep(5000);

        for (Secret kubeS : kubernetesClient.secrets().inNamespace(acsNamespace).list().getItems()) {
            System.out.println("\tFound secret: " + kubeS);
        }

        //=============================================================
        // Create a replication controller for our image stored in the Azure Container Registry

        ReplicationController rc = new ReplicationControllerBuilder().withNewMetadata().withName("acrsample-rc")
                .withNamespace(acsNamespace).addToLabels("acrsample-myimg", "myimg").endMetadata().withNewSpec()
                .withReplicas(2).withNewTemplate().withNewMetadata().addToLabels("acrsample-myimg", "myimg")
                .endMetadata().withNewSpec().addNewImagePullSecret(acsSecretName).addNewContainer()
                .withName("acrsample-pod-myimg").withImage(privateRepoUrl).addNewPort().withContainerPort(80)
                .endPort().endContainer().endSpec().endTemplate().endSpec().build();

        System.out.println("Creating a replication controller: "
                + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc));
        Thread.sleep(5000);

        rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get();
        System.out.println("Found replication controller: " + rc.toString());

        for (Pod pod : kubernetesClient.pods().inNamespace(acsNamespace).list().getItems()) {
            System.out.println("\tFound Kubernetes pods: " + pod.toString());
        }

        //=============================================================
        // Create a Load Balancer service that will expose the service to the world

        Service lbService = new ServiceBuilder().withNewMetadata().withName(acsLbIngressName)
                .withNamespace(acsNamespace).endMetadata().withNewSpec().withType("LoadBalancer").addNewPort()
                .withPort(80).withProtocol("TCP").endPort().addToSelector("acrsample-myimg", "myimg").endSpec()
                .build();

        System.out.println("Creating a service: "
                + kubernetesClient.services().inNamespace(acsNamespace).create(lbService));

        Thread.sleep(5000);

        System.out.println("\tFound service: "
                + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get());

        //=============================================================
        // Wait until the external IP becomes available

        String serviceIP = null;

        int timeout = 30 * 60 * 1000; // 30 minutes
        String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$";

        while (timeout > 0) {
            try {
                List<LoadBalancerIngress> lbIngressList = kubernetesClient.services().inNamespace(acsNamespace)
                        .withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress();
                if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null
                        && lbIngressList.get(0).getIp().matches(matchIPV4)) {
                    serviceIP = lbIngressList.get(0).getIp();
                    System.out.println("\tFound ingress IP: " + serviceIP);
                    timeout = 0;
                }
            } catch (Exception ignored) {
            }

            if (timeout > 0) {
                timeout -= 30000; // 30 seconds
                Thread.sleep(30000);
            }
        }

        //=============================================================
        // Check that the service is up and running

        if (serviceIP != null) {
            // warm up
            System.out.println("Warming up " + serviceIP);
            Utils.curl("http://" + serviceIP);
            SdkContext.sleep(15000);
            System.out.println("CURLing " + serviceIP);
            System.out.println(Utils.curl("http://" + serviceIP));
        } else {
            System.out.println("ERROR: service unavailable");
        }

        // Clean-up
        kubernetesClient.namespaces().delete(ns);

        shell.close();

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}

From source file:data_gen.Data_gen.java

private static void Build_json_file(String config_dir, long startTime) throws IOException {
    File f = new File(output_dir + "/" + Default_DataSet_name);
    BufferedWriter wr = new BufferedWriter(new FileWriter(f));

    wr.write("{\"docs\":[");
    wr.write("\n");

    ObjectMapper objectMapper = new ObjectMapper();

    //////////////////////////////////////////////////// flow control: (for loop) for number of
    //////////////////////////////////////////////////// documents and (while) for each field in document
    for (int i = 0; i <= documents_count; i++) {

        fields = Parse_Document_fields(config_dir);
        Iterator iterator = fields.keySet().iterator();
        while (iterator.hasNext()) {

            String key = (String) iterator.next();
            String v = (String) fields.get(key);
            String value = generate_facet_value(v);
            if (value.startsWith("integer.key")) {
                integer_key(fields, key, value);
            }/* www  . j a va2 s  . co m*/
            if (value.startsWith("seq.integer")) {
                seq_integer(fields, key, value);
            }

            if (value.startsWith("range")) {
                range_integer(fields, key, value);
            }
            if (value.charAt(0) == '[') {
                single_enum(fields, key, value);
            }
            if (value.startsWith("multi")) {
                multi_enum_json(fields, key, value);
            }
            if (value.startsWith("date")) {
                generate_date(fields, key, value);
            }

            if (value.equals("text.key")) {
                generate_Text_json(fields, key);
            }

            if (value.equals("text")) {
                generate_Text_json(fields, key);
            }

            if (value.startsWith("(")) {
                String VALUE = value.substring(1, value.length() - 1);
                fields.put(key, VALUE);
            }
        }

        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);

        String s = objectMapper.writeValueAsString(fields);
        wr.write(s);
        wr.write(",\n");

        fields.clear();

        if (i == count_check) {
            System.out.println("Number of Documents created: " + count_check);
            System.out.println("Reading from file: (" + listOfFiles[file_index] + ")");
            System.out.println("Size of all documents so far: (" + total + ") Bytes");
            System.out.println("\n");

            count_check += 1000;
        }
        cnt = i;
    }

    System.out.println("Total Number of Documents created: " + cnt);
    System.out.println("Total size of Dataset created: " + total);

    wr.write("]}");
    wr.flush();

    wr.close();
    long endTime = System.nanoTime();
    long duration = endTime - startTime;
    System.out.println("Total execuion time: " + (double) duration / 1000000000.0 + " Seconds" + "\n");
}

From source file:ems.util.DataHandler.java

public static boolean csvDownload(File file, ObservableList<MyModelSimpleStringProperty> data) {
    StringBuilder sb = new StringBuilder();
    try {/* w  w w .  j  a  v  a2s .com*/
        for (String data1 : Constants.REPORT_COLUMN_HEADERS) {
            sb.append(data1).append(",");
        }
        sb.setLength(sb.length() - 1);
        sb.append("\r\n");
        for (MyModelSimpleStringProperty data1 : data) {
            sb.append(data1.getObj1()).append(",").append(data1.getObj2()).append(",").append(data1.getObj4())
                    .append(",").append(data1.getObj5()).append(",").append(data1.getObj6()).append(",")
                    .append(data1.getObj7()).append(",").append(data1.getObj8()).append(",")
                    .append(data1.getObj9()).append(",").append(data1.getObj10()).append(",")
                    .append(data1.getObj11());
            sb.append("\r\n");
        }
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(sb.toString());
        bw.close();
        fw.close();
        return true;
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return false;
}

From source file:com.khepry.utilities.GenericUtilities.java

public static void displayLogFile(String logFilePath, long logSleepMillis, String xsltFilePath,
        String xsldFilePath) {/* w  w w.  j a va2 s  . c o  m*/
    Logger.getLogger("").getHandlers()[0].close();
    // only display the log file
    // if the logSleepMillis property
    // is greater than zero milliseconds
    if (logSleepMillis > 0) {
        try {
            Thread.sleep(logSleepMillis);
            File logFile = new File(logFilePath);
            File xsltFile = new File(xsltFilePath);
            File xsldFile = new File(xsldFilePath);
            File tmpFile = File.createTempFile("tmpLogFile", ".xhtml", logFile.getParentFile());
            if (logFile.exists()) {
                if (xsltFile.exists() && xsldFile.exists()) {
                    String xslFilePath;
                    String xslFileName;
                    String dtdFilePath;
                    String dtdFileName;
                    try {
                        xslFileName = new File(logFilePath).getName().replace(".xhtml", ".xsl");
                        xslFilePath = logFile.getParentFile().toString().concat("/").concat(xslFileName);
                        FileUtils.copyFile(new File(xsltFilePath), new File(xslFilePath));
                        dtdFileName = new File(logFilePath).getName().replace(".xhtml", ".dtd");
                        dtdFilePath = logFile.getParentFile().toString().concat("/").concat(dtdFileName);
                        FileUtils.copyFile(new File(xsldFilePath), new File(dtdFilePath));
                    } catch (IOException ex) {
                        String message = Level.SEVERE.toString().concat(": ").concat(ex.getLocalizedMessage());
                        Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, message, ex);
                        GenericUtilities.outputToSystemErr(message, logSleepMillis > 0);
                        return;
                    }
                    BufferedWriter bw = Files.newBufferedWriter(Paths.get(tmpFile.getAbsolutePath()),
                            Charset.defaultCharset(), StandardOpenOption.CREATE);
                    List<String> logLines = Files.readAllLines(Paths.get(logFilePath),
                            Charset.defaultCharset());
                    for (String line : logLines) {
                        if (line.startsWith("<!DOCTYPE log SYSTEM \"logger.dtd\">")) {
                            bw.write("<!DOCTYPE log SYSTEM \"" + dtdFileName + "\">\n");
                            bw.write("<?xml-stylesheet type=\"text/xsl\" href=\"" + xslFileName + "\"?>\n");
                        } else {
                            bw.write(line.concat("\n"));
                        }
                    }
                    bw.write("</log>\n");
                    bw.close();
                }
                // the following statement is commented out because it's not quite ready for prime-time yet
                // Files.write(Paths.get(logFilePath), transformLogViaXSLT(logFilePath, xsltFilePath).getBytes(), StandardOpenOption.CREATE);
                Desktop.getDesktop().open(tmpFile);
            } else {
                Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, logFilePath,
                        new FileNotFoundException());
            }
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(GenericUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.zbt.trie.linklist.SimpleTrie.java

private static void writeNode(Node root, java.io.BufferedWriter out, char[] chars, int pointer, String pre,
        String post) throws java.io.IOException {
    Node n = root.firstChild;/*from w w  w.  j a  v a2  s  . c om*/
    while (n != null) {
        if (n.firstChild == null) {
            out.write(pre);
            out.write(new String(chars, 0, pointer));
            out.write(post);
        } else {
            chars[pointer] = (char) n.value;
            writeNode(n, out, chars, pointer + 1, pre, post);
        }
        n = n.nextSibling;
    }
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

private static void addFeatureXML(IProject feature, TechnicalFragment tf) throws Exception {

    String featureLocation = feature.getLocation().toString();
    List<IProject> plugins = tf.getPlugins();
    File f = new File(featureLocation + "/feature.xml");
    if (!f.exists()) {
        f.createNewFile();/* w ww .j a  v  a  2 s . c o  m*/
        BufferedWriter output = new BufferedWriter(new FileWriter(f));
        output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        output.write(
                "<feature id=\"" + feature.getName() + "\" label=\"Feature\" version=\"1.0.0.qualifier\">\n");
        output.write(
                "<description url=\"http://www.example.com/description\"> [Enter Feature Description here.] </description>\n");
        output.write(
                "<copyright url=\"http://www.example.com/copyright\"> [Enter Copyright Description here.] </copyright>\n");
        output.write(
                "<license url=\"http://www.example.com/license\"> [Enter License Description here.] </license>\n");
        for (IProject project : plugins) {
            output.write("<plugin id=\"" + project.getName()
                    + "\" download-size=\"0\" install-size=\"0\" version=\"0.0.0\" unpack=\"false\"/>\n");
        }
        output.write("</feature>\n");
        output.close();
    }
}

From source file:com.photon.phresco.framework.commons.QualityUtil.java

private static void saveDocument(File file, Document doc) throws Exception {

    TransformerFactory factory1 = TransformerFactory.newInstance();
    Transformer transformer = factory1.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String content = writer.toString();
    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(content);
    bufferedWriter.flush();//from   w w  w  . ja  v a2  s.c  om
    bufferedWriter.close();
}

From source file:org.silverpeas.dbbuilder.DBBuilder.java

private static DBXmlDocument loadMasterContribution(File dirXml) throws IOException, AppBuilderException {
    DBXmlDocument destXml = new DBXmlDocument(dirXml, MASTER_DBCONTRIBUTION_FILE);
    destXml.setOutputEncoding(CharEncoding.UTF_8);
    if (!destXml.getPath().exists()) {
        destXml.getPath().createNewFile();
        BufferedWriter destXmlOut = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(destXml.getPath(), false), Charsets.UTF_8));
        try {/*www.jav a2 s .  com*/
            destXmlOut.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            destXmlOut.newLine();
            destXmlOut.write("<allcontributions>");
            destXmlOut.newLine();
            destXmlOut.write("</allcontributions>");
            destXmlOut.newLine();
            destXmlOut.flush();
        } finally {
            IOUtils.closeQuietly(destXmlOut);
        }
    }
    destXml.load();
    return destXml;
}

From source file:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static String createRassetXMLFile(TechnicalFragment tf, String folder) throws Exception {

    String manifestPath = folder + "/rasset.xml";
    File f = new File(manifestPath);
    if (!f.exists()) {
        f.createNewFile();//from ww  w.  ja v a  2  s .c  o  m

        String type = tf.getType();
        String origin = type.equals("Others") ? "no origin" : tf.getOrigin();
        String objective = type.equals("Others") ? "no objective" : tf.getObjective();
        String input = type.equals("Others") ? "no input" : tf.getInput();
        String output = type.equals("Others") ? "no output" : tf.getOutput();
        String toolId = getToolId(tf);
        String description = "";
        if (type.equals("External Tool")) {
            description = ((ExternalToolFragment) tf).getDescription();
        } else if (type.equals("Internal Tool")) {
            description = ((InternalToolFragment) tf).getDescription();
        } else {
            description = "no description";
        }

        BufferedWriter bwriter = new BufferedWriter(new FileWriter(f));
        bwriter.write("<asset xsi:schemaLocation=\"DefaultprofileXML.xsd\" name=\"" + tf.getName()
                + "\" id=\"1\">\n");
        bwriter.write("<type value=\"" + type + "\"></type>\n");
        bwriter.write("<origin value=\"" + origin + "\"></origin>\n");
        bwriter.write("<objective value=\"" + objective + "\"></objective>\n");
        bwriter.write("<input value=\"" + input + "\"></input>\n");
        bwriter.write("<output value=\"" + output + "\"></output>\n");
        if (toolId != null && !toolId.equals("")) {
            bwriter.write("<toolID value=\"" + toolId + "\"></toolID>\n");
        }
        bwriter.write("<description>" + description + "</description>\n");
        List<TechnicalFragment> dependencies = tf.getDependencies();
        for (TechnicalFragment dependency : dependencies) {
            bwriter.write("<dependency value=\"" + dependency.getName() + ".ras.zip\"></dependency>\n");
        }
        if (type.equals("Internal Tool")) {
            List<String> pluginIds = ((InternalToolFragment) tf).getPluginIds();
            for (String pluginId : pluginIds) {
                bwriter.write("<plugin value=\"" + pluginId + "\"></plugin>\n");
            }
        }
        bwriter.write("</asset>\n");
        bwriter.close();
    }

    return manifestPath;
}