Example usage for java.util Properties store

List of usage examples for java.util Properties store

Introduction

In this page you can find the example usage for java.util Properties store.

Prototype

public void store(OutputStream out, String comments) throws IOException 

Source Link

Document

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the #load(InputStream) load(InputStream) method.

Usage

From source file:org.alfresco.bm.file.AbstractTestFileService.java

/**
 * Looks for a {@link #PROPERTIES_FILE properties file} containing the name of the fileset that
 * this server uses.  The fileset is therefore unique to every local data location.
 *//*from  ww w.j ava2s.  c om*/
private static synchronized String getFileset(File mirrorDir) {
    Properties properties = new Properties();
    // See if there is a file with the properties present
    File propsFile = new File(mirrorDir, PROPERTIES_FILE);
    if (propsFile.exists()) {
        if (propsFile.isDirectory()) {
            throw new RuntimeException(
                    "Expected to find a properties file but found a directory: " + propsFile);
        }
        // Just read the server's unique key from it
        properties = new Properties();
        FileReader reader = null;
        try {
            reader = new FileReader(propsFile);
            properties.load(reader);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load properties from file: " + propsFile, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    }

    // Read the property
    String fileset = properties.getProperty(PROPERTY_FILESET);
    if (fileset == null) {
        // We must write a value into the file
        fileset = UUID.randomUUID().toString();
        properties.put(PROPERTY_FILESET, fileset);
        // Write the properties back
        FileWriter writer = null;
        try {
            writer = new FileWriter(propsFile);
            properties.store(writer, "Auto-generated fileset name");
        } catch (IOException e) {
            throw new RuntimeException("Failed to write fileset to properties file: " + propsFile, e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }
    // Done
    return fileset;
}

From source file:emenda.kwopenproject.Activator.java

public boolean storeProperties(Properties prop) {
    if (prop != null) {
        //Remove temporary filepath value from file before storing
        String filepath = prop.getProperty(PROP_TEMP_FILEPATH);
        prop.remove(PROP_TEMP_FILEPATH);
        try {/*from   w w  w  .  j  ava  2  s. c o  m*/
            logging.writeLog("Storing properties file: " + filepath + "...");
            prop.store(new FileOutputStream(filepath), null);
            logging.writeLog("Storing properties file: " + filepath + "... SUCCESS");
        } catch (Exception e) {
            logging.writeLog("Exception while writing Klocwork Sync properties to file: "
                    + prop.getProperty(PROP_TEMP_FILEPATH) + "\nMessage: " + e.getMessage());
            return false;
        }
    }

    return true;
}

From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java

/**
 * This will publish the artifact to Azkaban for scheduled running.  The artifact should be of the format
 * <p/>/*w w w  .  j  a  v  a2  s. c om*/
 * <p/>
 * The artifact at this point in time will already have included the SSL certs.
 * <p/>
 * Its up to the publisher to reorganize the tar file if needed for its PaaS
 *
 * @param artifact    The artifact to deploy
 * @param callerToken - The token of the user or application that initiated this call
 * @throws DeploymentException - On any exceptions
 */
@Override
public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException {
    File unzippedPack = null;
    File azkabanZip = null;
    ZipOutputStream zipOutputStream = null;
    String flowName;
    final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo();

    // Get the Azkaban authentication token
    final AuthenticationResult authenticatorResult;
    try {
        authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(),
                azConf.getPassword()).login();
    } catch (URISyntaxException e) {
        throw new DeploymentException(e.getMessage());
    }

    if (authenticatorResult.hasError()) {
        log.error("Could not log into Azkaban: " + authenticatorResult.getError());
        throw new DeploymentException(authenticatorResult.getError());
    }

    log.info("Successfully logged into Azkaban. Now creating .zip to upload");

    try {
        // Unzip the artifact
        unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact()));
        log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath());

        // Create a .zip file to submit to Azkaban
        azkabanZip = File.createTempFile("ezbatch_", ".zip");
        log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath());
        zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip));

        // Copy the configs from the artifact to the top level of the zip.  This should contain the Azkaban
        // .jobs and .properties
        final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get();
        final File configDirFile = new File(configDir);
        for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, "")));
            IOUtils.copy(new FileInputStream(f), zipOutputStream);
            zipOutputStream.closeEntry();
        }
        log.info("Copied configs to the .zip");

        // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed
        final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/";
        for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
            zipOutputStream
                    .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/")));

            final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f));
            final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream);

            JarEntry je;
            while ((je = jarInputStream.getNextJarEntry()) != null) {
                jarOutputStream.putNextEntry(je);
                IOUtils.copy(jarInputStream, jarOutputStream);
                jarOutputStream.closeEntry();
            }
            log.info("Created Jar file");

            // Add the SSL certs to the jar
            final String sslPath = UnzipUtil.getSSLPath(configDirFile).get();
            for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE,
                    TrueFileFilter.TRUE)) {
                if (sslFile.isFile()) {
                    jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName()));
                    IOUtils.copy(new FileInputStream(sslFile), jarOutputStream);
                    jarOutputStream.closeEntry();
                }
            }
            log.info("Added SSL certs to jar");

            // Add the application.properties to the jar file so the jobs can read it
            final File appProps = new File(configDir, "application.properties");
            final Properties adjustedProperties = new Properties();
            adjustedProperties.load(new FileInputStream(appProps));
            adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/");
            jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties"));
            adjustedProperties.store(jarOutputStream, null);
            jarOutputStream.closeEntry();

            jarOutputStream.finish();
            zipOutputStream.closeEntry();
        }

        // Check to see if there are any .job files.  If there aren't, this is an external job and we need to create
        // one for the .zip file
        final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false);
        if (jobFiles.isEmpty()) {
            // If there are no job files present then we need to create one for the user
            final StringBuilder sb = new StringBuilder(
                    "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n"
                            + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config");

            for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) {
                sb.append(" -c ").append(xmlConfig.getName());
            }

            zipOutputStream.putNextEntry(new ZipEntry("Analytic.job"));
            IOUtils.copy(new StringReader(sb.toString()), zipOutputStream);
            zipOutputStream.closeEntry();
            log.info("There was no .job file so one was created for the .zip");
            flowName = "Analytic";
        } else {
            flowName = jobInfo.getFlowName();
            if (flowName == null) {
                log.warn("Manifest did not contain flow_name. Guessing what it should be");
                flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName());
                log.info("Guessing the flow name should be:" + flowName);
            }
        }

        zipOutputStream.finish();
        log.info("Finished creating .zip");

        // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip
        // file needs to be uploaded to a project, and the project may or may not already exist.
        final String projectName = ArtifactHelpers.getAppId(artifact) + "_"
                + ArtifactHelpers.getServiceId(artifact);
        final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));
        final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed");

        // If the project already exists, it will return an error, but really it's not a problem
        if (managerResult.hasError()) {
            if (!managerResult.getMessage().contains("already exists")) {
                log.error("Could not create project: " + managerResult.getMessage());
                throw new DeploymentException(managerResult.getMessage());
            } else {
                log.info("Reusing the existing project: " + projectName);
            }
        } else {
            log.info("Created new project: " + projectName);
            log.info("Path: " + managerResult.getPath());
        }

        // Upload the .zip file to the project
        final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(),
                azConf.getAzkabanUrl(), projectName, azkabanZip);
        final UploaderResult uploaderResult = uploader.uploadZip();

        if (uploaderResult.hasError()) {
            log.error("Could not upload the zip file: " + uploaderResult.getError());
            throw new DeploymentException(uploaderResult.getError());
        }

        log.info("Successfully submitted zip file to Azkaban");

        // Schedule the jar to run.  If the start times aren't provided, it will run in 2 minutes

        final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(),
                new URI(azConf.getAzkabanUrl()));

        // Add the optional parameters if they are present
        if (jobInfo.isSetStartDate()) {
            scheduler.setScheduleDate(jobInfo.getStartDate());
        }
        if (jobInfo.isSetStartTime()) {
            scheduler.setScheduleTime(jobInfo.getStartTime());
        }
        if (jobInfo.isSetRepeat()) {
            scheduler.setPeriod(jobInfo.getRepeat());
        }

        final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName,
                uploaderResult.getProjectId());
        if (schedulerResult.hasError()) {
            log.error("Failure to schedule job: " + schedulerResult.getError());
            throw new DeploymentException(schedulerResult.getError());
        }

        log.info("Successfully scheduled flow: " + flowName);

    } catch (Exception ex) {
        log.error("No Nos!", ex);
        throw new DeploymentException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        FileUtils.deleteQuietly(azkabanZip);
        FileUtils.deleteQuietly(unzippedPack);
    }
}

From source file:com.floreantpos.license.FiveStarPOSLicenseManager.java

/**
 * Creates a new template file.//from   w w w .  j a v  a2s.c  o  m
 * 
 * @param templateFile
 * @throws IOException
 */
private final void createTemplateFile(File templateFile) throws IOException {

    OutputStream output = new FileOutputStream(templateFile);

    Properties properties = new OrderedProperties();
    properties.put(License.LICENSED_TO, "************");
    properties.put(License.PURCHASE_ID, UUID.randomUUID().toString());
    properties.put(License.PURCHASE_DATE, License.DATE_FORMAT.format(new Date()));
    properties.put(License.MACHINE_KEY, "************");
    properties.put(License.BACK_OFFICE, "false");
    properties.put(License.KITCHEN_DISPLAY, "false");
    properties.put(License.EXPIRATION_DATE, License.DATE_FORMAT.format(DateUtils.addDays(new Date(), 30)));
    properties.store(output, "License template file");

    output.close();
}

From source file:net.sourceforge.doddle_owl.ui.GeneralOntologySelectionPanel.java

public void saveGeneralOntologyInfo(File saveFile) {
    BufferedWriter writer = null;
    try {/* www . ja v a  2  s .  c om*/
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile), "UTF-8"));
        Properties properties = new Properties();
        properties.setProperty("EDR(general)", String.valueOf(isEDREnable()));
        properties.setProperty("EDR(technical)", String.valueOf(isEDRTEnable()));
        properties.setProperty("WordNet", String.valueOf(isWordNetEnable()));
        properties.setProperty("JPN WordNet", String.valueOf(isJpnWordNetEnable()));
        properties.setProperty("JWO", String.valueOf(isJWOEnable()));
        properties.store(writer, "Ontology Info");
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ioe2) {
                ioe2.printStackTrace();
            }
        }
    }
}

From source file:com.android.sdklib.internal.repository.packages.SamplePackage.java

/**
 * Saves the hash using a properties file
 *//*from   ww w.j a  va2s  .  c om*/
private void saveContentHash(File folder, String hash) {
    Properties props = new Properties();

    props.setProperty("content-hash", hash == null ? "" : hash); //$NON-NLS-1$ //$NON-NLS-2$

    FileOutputStream fos = null;
    try {
        File f = new File(folder, SdkConstants.FN_CONTENT_HASH_PROP);
        fos = new FileOutputStream(f);
        props.store(fos, "## Android - hash of this archive."); //$NON-NLS-1$
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.anuta.internal.YangHelperMojo.java

private void storeFileHashCache(Properties props) {
    String cacheFileName = getCacheFile();
    if (null == cacheFileName) {
        return;/*w  w  w. ja v a  2s  . c  om*/
    }
    File cacheFile = new File(targetDirectory, cacheFileName);
    try {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(cacheFile));
        props.store(out, null);
    } catch (FileNotFoundException e) {
        getLog().warn("Cannot store file hash cache properties file", e);
    } catch (IOException e) {
        getLog().warn("Cannot store file hash cache properties file", e);
    }
}

From source file:com.haulmont.cuba.security.app.EntityLog.java

protected String getChanges(Properties properties) {
    try {/*from  www . ja  v  a  2s.co  m*/
        StringWriter writer = new StringWriter();
        properties.store(writer, null);
        String changes = writer.toString();
        if (changes.startsWith("#"))
            changes = changes.substring(changes.indexOf("\n") + 1); // cut off comments line
        return changes;
    } catch (IOException e) {
        throw new RuntimeException("Error writing entity log attributes", e);
    }
}

From source file:com.sammyun.controller.console.SettingController.java

/**
 * //from  w w w .ja v a 2s .  c  om
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(Setting setting, MultipartFile watermarkImageFile, RedirectAttributes redirectAttributes,
        ModelMap model) {
    if (!isValid(setting)) {
        return ERROR_VIEW;
    }
    if (setting.getUsernameMinLength() > setting.getUsernameMaxLength()
            || setting.getPasswordMinLength() > setting.getPasswordMinLength()) {
        return ERROR_VIEW;
    }
    Setting srcSetting = SettingUtils.get();

    SettingUtils.set(setting);
    cacheService.clear();
    staticService.buildIndex();
    staticService.buildOther();

    OutputStream outputStream = null;
    try {
        org.springframework.core.io.Resource resource = new ClassPathResource(
                CommonAttributes.PRESCHOOLEDU_PROPERTIES_PATH);
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        String templateUpdateDelay = properties.getProperty("template.update_delay");
        String messageCacheSeconds = properties.getProperty("message.cache_seconds");
        if (setting.getIsDevelopmentEnabled()) {
            if (!templateUpdateDelay.equals("0") || !messageCacheSeconds.equals("0")) {
                outputStream = new FileOutputStream(resource.getFile());
                properties.setProperty("template.update_delay", "0");
                properties.setProperty("message.cache_seconds", "0");
                properties.store(outputStream, "Sencloud PROPERTIES");
            }
        } else {
            if (templateUpdateDelay.equals("0") || messageCacheSeconds.equals("0")) {
                outputStream = new FileOutputStream(resource.getFile());
                properties.setProperty("template.update_delay", "3600");
                properties.setProperty("message.cache_seconds", "3600");
                properties.store(outputStream, "Sencloud PROPERTIES");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
    model.addAttribute("menuId", Setting.class.getSimpleName());
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:edit.ct";
}

From source file:hydrograph.ui.expression.editor.dialogs.AddCategoreisDialog.java

public boolean createPropertyFileForSavingData() {
    IProject iProject = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject();
    IFolder iFolder = iProject.getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    FileOutputStream file = null;
    Properties properties = new Properties();
    try {//from  w  ww  .j  a v a 2 s  .  c  o  m
        if (!iFolder.exists()) {
            iFolder.create(true, true, new NullProgressMonitor());
        }
        for (String items : categoriesDialogTargetComposite.getTargetList().getItems()) {
            String jarFileName = StringUtils.trim(StringUtils.substringAfter(items, Constants.DASH));
            String packageName = StringUtils.trim(StringUtils.substringBefore(items, Constants.DASH));
            properties.setProperty(packageName, jarFileName);
        }

        file = new FileOutputStream(iFolder.getLocation().toString() + File.separator
                + PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
        properties.store(file, "");
        return true;
    } catch (IOException | CoreException exception) {
        LOGGER.error("Exception occurred while saving jar file path at projects setting folder", exception);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                LOGGER.warn("Exception in closing output stream. The error message is " + e.getMessage());
            }
        }
    }
    return false;
}