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:hydrograph.ui.expression.editor.pages.AddExternalJarPage.java

public boolean createPropertyFileForSavingData() {
    IProject iProject = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject();
    IFolder iFolder = iProject.getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    Properties properties = new Properties();
    FileOutputStream file = null;
    boolean isFileCreated = false;
    try {//from  w  ww.  ja  v a2s  .  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, "");
        ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE,
                new NullProgressMonitor());
        isFileCreated = 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("IOException occurred while closing output-stream of file", e);
            }
    }
    return isFileCreated;
}

From source file:org.nuxeo.wizard.download.PackageDownloader.java

protected void saveSelectedPackages(List<DownloadPackage> pkgs) {
    File desc = new File(getDownloadDirectory(), PACKAGES_DEFAULT_SELECTION);
    Properties props = new Properties();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < pkgs.size(); i++) {
        if (i > 0) {
            sb.append(",");
        }/*from  w  w w  . j  a v a  2 s .c  o  m*/
        sb.append(pkgs.get(i).getId());
    }
    props.put(PACKAGES_DEFAULT_SELECTION_PACKAGES, sb.toString());
    try {
        props.store(new FileWriter(desc), "Saved from Nuxeo SetupWizard");
    } catch (IOException e) {
        log.error("Unable to save package selection", e);
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.GranuleRemoverOnlineTest.java

/**
 * * deletes existing store/*from   ww w  . j ava  2 s  .  c  o  m*/
 * * create a brand new mosaic dir
 * * create the mosaic on GS
 * 
 */
protected ImageMosaicConfiguration createMosaicConfig() throws IOException {

    // create datastore file
    Properties datastore = new Properties();
    datastore.putAll(getPostgisParams());
    datastore.remove(PostgisNGDataStoreFactory.DBTYPE.key);
    datastore.setProperty("SPI", "org.geotools.data.postgis.PostgisNGDataStoreFactory");
    datastore.setProperty(PostgisNGDataStoreFactory.LOOSEBBOX.key, "true");
    datastore.setProperty(PostgisNGDataStoreFactory.ESTIMATED_EXTENTS.key, "false");
    File datastoreFile = new File(getTempDir(), "datastore.properties");
    LOGGER.info("Creating  " + datastoreFile);
    FileOutputStream out = new FileOutputStream(datastoreFile);
    datastore.store(out, "Datastore file created from fixtures");
    out.flush();
    out.close();
    //        datastore.store(System.out, "Datastore created from fixtures");
    //        datastore.list(System.out);

    // config
    ImageMosaicConfiguration conf = new ImageMosaicConfiguration("", "", "");
    conf.setTimeRegex("(?<=_)\\\\d{8}");
    conf.setTimeDimEnabled("true");
    conf.setTimePresentationMode("LIST");
    conf.setGeoserverURL(getFixture().getProperty("gs_url"));
    conf.setGeoserverUID(getFixture().getProperty("gs_user"));
    conf.setGeoserverPWD(getFixture().getProperty("gs_password"));
    conf.setDatastorePropertiesPath(datastoreFile.getAbsolutePath());
    conf.setDefaultNamespace(WORKSPACE);
    conf.setDefaultStyle("raster");
    conf.setCrs("EPSG:4326");

    return conf;
}

From source file:com.ssy.havefunweb.util.WeixinUtil.java

public void wirteProperties(AccessToken token) throws FileNotFoundException, IOException {
    Properties prop = new Properties();
    SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
    //        String filePath = getClass().getResource("/").getPath() + TOKENPROPERTIES;
    String path = this.getClass().getResource("/").getPath();
    path = path.substring(1, path.indexOf("classes"));//?
    path = path + TOKENPROPERTIES;/*w w w . ja va 2  s . c o  m*/
    OutputStream oFile = new FileOutputStream(path);//true
    //        OutputStream out = getClass().getResourceAsStream(TOKENPROPERTIES_PATH);
    prop.setProperty("access_token", token.getAccess_token());
    prop.setProperty("expires_in", String.valueOf(token.getExpires_in()));
    prop.setProperty("updateTime", String.valueOf(token.getUpdateTime()));
    prop.store(oFile, "Update time" + myFmt.format(new Date()));
    oFile.close();
}

From source file:fi.aalto.drumbeat.drumbeatUI.DrumbeatFileHandler.java

private void handleNewFile(File file) {
    Properties prop = new Properties();
    OutputStream output = null;// ww w .  j a v  a2  s.  c om
    if (file == null)
        return;

    String realEstate = parent.getSite();
    // set the properties value
    String[] fname_array = file.getName().split("\\.");

    try {

        output = new FileOutputStream(DrumbeatConstants.marmotta_import_config_file);

        prop.setProperty("context",
                DrumbeatConstants.marmotta_contexts_baseurl + realEstate + "." + fname_array[0]);
        prop.setProperty("label", realEstate + "." + fname_array[0]);
        parent.createDataset(fname_array[0]);
        // save properties to project root folder
        prop.store(output, null);
    } catch (Exception e) {
        e.printStackTrace();
        Notification n = new Notification("File name error", file.getName() + " ; " + e.getMessage(),
                Notification.Type.ERROR_MESSAGE);
        n.setDelayMsec(5000);
        n.show(Page.getCurrent());
        return;
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    if (!convertIFC2RDFDefault(file, realEstate + "." + fname_array[0]))
        return; // Stop if the conversion fails

    try {
        BIMFileLoader bfl = new BIMFileLoader();
        bfl.load(file);
    } catch (Exception e) {
        Notification n = new Notification("BIMFileLoader error ", e.getMessage(),
                Notification.Type.ERROR_MESSAGE);
        n.setDelayMsec(50000);
        n.show(Page.getCurrent());
        return;
    }
    Notification.show("File was uploaded");
    parent.updateData();
}

From source file:de.xirp.managers.DeleteManager.java

/**
 * Stops the manager, deletes all files which are registered to be
 * deleted on shutdown and writes the the file with the list of
 * files which should be deleted on next startup.<br/><br/>If
 * the manager fails to delete a file on shutdown, it tries to
 * delete the file on next startup./*from  w w  w . j  a va 2  s. co  m*/
 * 
 * @see de.xirp.managers.AbstractManager#stop()
 */
@Override
protected void stop() throws ManagerException {
    super.stop();
    Properties props = new Properties();
    int cnt = 0;
    for (String path : deleteOnShutdown) {
        try {
            FileUtils.forceDelete(new File(path));
        } catch (IOException e) {
            props.put("File_" + cnt++, path); //$NON-NLS-1$
        }
    }
    File f = new File(Constants.TO_DELETE_FILE);
    if (!f.exists()) {
        try {
            f.createNewFile();
        } catch (IOException e) {
            // do nothing, cause we can't to anything in this case
        }
    }

    for (String path : deleteOnStartup) {
        props.put("File_" + cnt++, path); //$NON-NLS-1$
    }
    try {
        FileWriter w = new FileWriter(f);
        props.store(w, "Files to delete on startup"); //$NON-NLS-1$
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
    }
}

From source file:com.evolveum.midpoint.tools.gui.PropertiesGenerator.java

private void backupExistingAndSaveNewProperties(Properties properties, File target) throws IOException {
    if (target.exists()) {
        if (!config.isDisableBackup()) {
            File backupFile = new File(target.getParentFile(), target.getName() + ".backup");
            FileUtils.copyFile(target, backupFile);
        }/*w  w w  . j a  va 2  s . c o  m*/
        target.delete();
    } else {
        System.out.println("Creating new file: " + target.getName());
    }

    File parent = target.getParentFile();
    if (!parent.exists() || !parent.isDirectory()) {
        FileUtils.forceMkdir(parent);
    }
    target.createNewFile();
    Writer writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(target), Charset.forName(ENCODING));
        properties.store(writer, null);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java

public void configurePTrans() throws Exception {
    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(ptransConfFile)) {
        properties.load(in);//  w  w  w  . ja  va2 s  . c  o  m
    }
    properties.setProperty(SERVICES.getExternalForm(), Service.COLLECTD.getExternalForm());
    properties.setProperty(BATCH_DELAY.getExternalForm(), String.valueOf(1));
    properties.setProperty(BATCH_SIZE.getExternalForm(), String.valueOf(1));
    String restUrl = "http://" + BASE_URI + "/" + tenant + "/metrics/numeric/data";
    properties.setProperty(REST_URL.getExternalForm(), restUrl);
    try (OutputStream out = new FileOutputStream(ptransConfFile)) {
        properties.store(out, "");
    }
}

From source file:edu.indiana.d2i.sloan.ui.JobSubmitAction.java

/**
 * upload job//from   w  ww  .j ava  2 s  .  c  om
 * 
 * @throws RemoteException
 * @throws JAXBException
 * @throws NullSigiriJobIdException
 * @throws XMLStreamException
 * @throws RegistryExtException
 * @throws IOException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 */
private void uploadJob() throws RemoteException, JAXBException, NullSigiriJobIdException, XMLStreamException,
        RegistryExtException, IOException, OAuthSystemException, OAuthProblemException {

    Map<String, Object> session = ActionContext.getContext().getSession();
    String username = (String) session.get(Constants.SESSION_USERNAME);
    String accessToken = (String) session.get(Constants.SESSION_TOKEN);
    String refreshToken = (String) session.get(Constants.SESSION_REFRESH_TOKEN);

    AgentsRepoSingleton agentsRepo = AgentsRepoSingleton.getInstance();
    RegistryExtAgent registryExtAgent = agentsRepo.getRegistryExtAgent();

    /**
     * Update token: write token as a property file, all jobs share this
     * token file, which is stored directly under user's home directory. (In
     * registry extension, it is under /htrc/username/files/sloan/jobs/).
     * Each job submission will update this file
     */

    Properties tokenFile = new Properties();

    tokenFile.setProperty(Constants.OAUTH2_ACCESS_TOKEN, accessToken);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    tokenFile.store(os, "");

    String outPath = registryExtAgent.postResource(
            new StringBuilder().append(PortalConfiguration.getRegistryJobPrefix())
                    .append(Constants.OAUTH2_TOKEN_FNAME).toString(),
            new ResourceISType(new ByteArrayInputStream(os.toByteArray()), Constants.OAUTH2_TOKEN_FNAME,
                    "text/plain"));

    logger.info(String.format("Updated token file %s saved to %s", Constants.OAUTH2_TOKEN_FNAME, outPath));

    // remove leading and trailing white-spaces
    selectedJob = selectedJob.trim();

    /* generate registry internal job id */
    String internalJobId = UUID.randomUUID().toString();

    danglingJobId = internalJobId;

    String jobPath = PortalConfiguration.getRegistryJobPrefix() + internalJobId + RegistryExtAgent.separator;
    logger.info("Create new job home=" + jobPath);

    /**
     * check user uploaded job description xml file, make sure it conforms
     * to user xsd
     */

    edu.indiana.d2i.sloan.schema.user.JobDescriptionType userJobDesp = null;

    InputStream is = new ByteArrayInputStream(FileUtils.readFileToByteArray(jobDesp));
    userJobDesp = UserSchemaUtil.readConfigXML(is);
    if (logger.isDebugEnabled()) {
        logger.debug("Use uploaded job desp file:\n");
        logger.debug(UserSchemaUtil.toXMLString(userJobDesp));
    }

    /**
     * Pick user selected worksets
     */
    List<WorksetMetaInfo> selectedWorksets = new ArrayList<WorksetMetaInfo>();

    if (worksetCheckbox != null) {
        for (String idx : worksetCheckbox) {
            /*
             * This happens only when there is only one workset and user
             * doesn't select it when composing the job
             */
            if ("false".equals(idx))
                continue;

            selectedWorksets.add(worksetInfoList.get(Integer.valueOf(idx)));
        }
    }

    /**
     * Convert user schema to internal schema used by sigiri daemon
     */
    JobDescriptionType internalJobDesp = SchemaUtil.user2internal(userJobDesp, accessToken, refreshToken,
            username, internalJobId, jobArchiveFileName, selectedWorksets);

    String internalJobDespStr = InternalSchemaUtil.toXMLString(internalJobDesp);

    if (logger.isDebugEnabled()) {
        logger.debug("Converted internal job description:\n");
        logger.debug(internalJobDespStr);
    }

    // create job.properties file
    Properties jobProp = new Properties();
    jobProp.setProperty(JobProperty.JOB_TITLE, selectedJob);
    jobProp.setProperty(JobProperty.JOB_OWNER, username);
    jobProp.setProperty(JobProperty.JOB_CREATION_TIME, new Date(System.currentTimeMillis()).toString());

    os = new ByteArrayOutputStream();
    jobProp.store(os, "");

    outPath = registryExtAgent.postResource(
            new StringBuilder().append(jobPath).append(Constants.WSO2_JOB_PROP_FNAME).toString(),
            new ResourceISType(new ByteArrayInputStream(os.toByteArray()), Constants.WSO2_JOB_PROP_FNAME,
                    "text/plain"));

    logger.info(String.format("Job property file %s saved to %s", Constants.WSO2_JOB_PROP_FNAME, outPath));

    // post job description
    outPath = registryExtAgent.postResource(
            new StringBuilder().append(jobPath).append(Constants.WSO2_JOB_DESP_FNAME).toString(),
            new ResourceISType(new ByteArrayInputStream(internalJobDespStr.getBytes()),
                    Constants.WSO2_JOB_DESP_FNAME, jobDespContentType));

    logger.info(String.format("Job description file %s saved to %s", Constants.WSO2_JOB_DESP_FNAME, outPath));

    // post archive
    outPath = registryExtAgent.postResource(
            new StringBuilder().append(jobPath).append(PortalConfiguration.getRegistryArchiveFolder())
                    .append(RegistryExtAgent.separator).append(jobArchiveFileName).toString(),
            new ResourceISType(new FileInputStream(jobArchive), jobArchiveFileName, jobArchiveContentType));

    logger.info(String.format("Job archive file %s saved to %s", jobArchiveFileName, outPath));

    // submit to sigiri service
    SigiriAgent sigiriAgent = agentsRepo.getSigiriAgent();
    JobStatus jobStatus = sigiriAgent.submitJob(internalJobDespStr);

    String sigiriJobId = jobStatus.getJobId();

    if (sigiriJobId == null || "".equals(sigiriJobId) || "NoJobId".equals(sigiriJobId))
        throw new NullSigiriJobIdException("None sigiri job id returned");

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Job %s submitted to Sigiri, sigiri job id returned is %s", internalJobId,
                sigiriJobId));
    }

    /**
     * write the job id to registry for future reference
     */
    jobProp.setProperty(JobProperty.SIGIRI_JOB_ID, sigiriJobId);
    jobProp.setProperty(JobProperty.SIGIRI_JOB_STATUS, jobStatus.getStatus());

    jobProp.setProperty(JobProperty.SIGIRI_JOB_STATUS_UPDATE_TIME,
            new Date(System.currentTimeMillis()).toString());
    os = new ByteArrayOutputStream();
    jobProp.store(os, "");

    outPath = registryExtAgent.postResource(
            new StringBuilder().append(jobPath).append(Constants.WSO2_JOB_PROP_FNAME).toString(),
            new ResourceISType(new ByteArrayInputStream(os.toByteArray()), Constants.WSO2_JOB_PROP_FNAME,
                    "text/plain"));

    logger.info(
            String.format("Updated job property file %s saved to %s", Constants.WSO2_JOB_PROP_FNAME, outPath));

    logger.info(String.format("User %s's job %s has been submitted successfully", username, jobPath));

    /**
     * set danglingJobId to null to indicate that job has been submitted
     * successfully (no exceptions occurred)
     */
    danglingJobId = null;
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect.java

/**
 * Sends a PUT command to create an empty file inside of HDFS.
 * It uses the URL from the original request to do so.
 * It will then consume the 307 response and write to the DataNode as well.
 * The data is "small" in hopes that this will be relatively quick.
 *
 * @throws IOException/*w  w  w . j a  v  a  2  s .  com*/
 * @throws ServletException
 */
public void sendCreate(String nnHostAddress, String userName) throws IOException, ServletException {
    // Set up HttpPut
    String[] nnHost = nnHostAddress.split(":");
    String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME, META_FILE_NAME);

    PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "CREATE&overwrite=true", userName, metapath, PUT);
    Enumeration headers = request.getHeaderNames();
    Properties metadata = new Properties();

    // Set custom metadata headers
    while (headers.hasMoreElements()) {
        String key = (String) headers.nextElement();
        if (key.startsWith("x-amz-meta-")) {
            String value = request.getHeader(key);
            metadata.setProperty(key, value);
        }
    }
    // Include lastModified header
    SimpleDateFormat rc228 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    String modTime = rc228.format(Calendar.getInstance().getTime());
    metadata.setProperty("Last-Modified", modTime);

    // Store metadata headers into serialized HashMap in HttpPut entity.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    metadata.store(baos, null);

    httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
    httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);

    httpClient.executeMethod(httpPut);
    LOG.debug("1st response: " + httpPut.getStatusLine().toString());

    boolean containsRedirect = (httpPut.getResponseHeader("Location") != null);

    if (!containsRedirect) {
        httpPut.releaseConnection();
        LOG.error("1st response did not contain redirect. " + "No metadata will be created.");
        return;
    }

    // Handle redirect header transition
    assert httpPut.getStatusCode() == 307;
    Header locationHeader = httpPut.getResponseHeader("Location");
    httpPut.setURI(new URI(locationHeader.getValue(), true));

    // Consume response and re-allocate connection for redirect
    httpPut.releaseConnection();
    httpClient.executeMethod(httpPut);

    LOG.debug("2nd response: " + httpPut.getStatusLine().toString());

    if (httpPut.getStatusCode() != 200) {
        LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString());
        return;
    }

    assert httpPut.getStatusCode() == 200;
}