Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

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

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:com.krawler.esp.utils.PropsLoader.java

public static Properties loadProperties(String name, ClassLoader loader) {
    if (name == null)
        throw new IllegalArgumentException("null input: name");

    if (name.startsWith("/"))
        name = name.substring(1);//from   w  w w  .  j a  va2  s.c  om

    if (name.endsWith(SUFFIX))
        name = name.substring(0, name.length() - SUFFIX.length());

    Properties result = null;

    InputStream in = null;
    try {
        if (loader == null)
            loader = ClassLoader.getSystemClassLoader();

        if (LOAD_AS_RESOURCE_BUNDLE) {
            name = name.replace('/', '.');
            // Throws MissingResourceException on lookup failures:
            final ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault(), loader);

            result = new Properties();
            for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
                final String key = (String) keys.nextElement();
                final String value = rb.getString(key);

                result.put(key, value);
            }
        } else {
            name = name.replace('.', '/');

            if (!name.endsWith(SUFFIX))
                name = name.concat(SUFFIX);

            // Returns null on lookup failures:
            in = loader.getResourceAsStream(name);
            if (in != null) {
                result = new Properties();
                result.load(in); // Can throw IOException
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        result = null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Throwable ignore) {
                logger.warn(ignore.getMessage(), ignore);
            }
    }

    if (THROW_ON_LOAD_FAILURE && (result == null)) {
        throw new IllegalArgumentException("could not load [" + name + "]" + " as "
                + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource"));
    }

    return result;
}

From source file:com.igormaznitsa.mindmap.model.ModelUtils.java

@Nonnull
public static Properties extractQueryPropertiesFromURI(@Nonnull final URI uri) {
    final Properties result = new Properties();

    final String rawQuery = uri.getRawQuery();
    if (rawQuery != null) {
        final Matcher matcher = URI_QUERY_PARAMETERS.matcher(rawQuery);

        try {/*from ww w.j  a  v a2 s  .c o  m*/
            while (matcher.find()) {
                final String key = URLDecoder.decode(matcher.group(1), "UTF-8"); //NOI18N
                final String value = URLDecoder.decode(matcher.group(2), "UTF-8"); //NOI18N
                result.put(key, value);
            }
        } catch (UnsupportedEncodingException ex) {
            LOGGER.error("Can't decode URI query", ex); //NOI18N
            throw new Error("Unexpected exception, can't find UTF-8 charset!"); //NOI18N
        }
    }

    return result;
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static void evalConfiguration(Configuration conf) {
    Properties props = new Properties();
    for (Map.Entry entry : conf) {
        props.put(entry.getKey(), entry.getValue());
    }/*from   w  w  w  .  ja  v  a 2  s .com*/
    evalProperties(props, conf);
    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        conf.set((String) entry.getKey(), (String) entry.getValue());
    }
}

From source file:org.onesun.atomator.core.SubscriptionManager.java

public static Channel newSubscription(SubscriptionEntry subscriptionEntry, boolean persist) {
    String type = subscriptionEntry.getChannelType();

    Channel channel = null;/*from   w  w  w.  jav  a2  s. c  o  m*/
    SecretEntry entry = OAuthSecretsManager.get(type);
    Properties properties = null;
    Map<String, String> extendedParams = null;

    // There must be an entry for all authenticable sources
    if (entry != null) {
        // KeyStore must exist for authenticated sources
        properties = toProperties(entry);

        // Load any additional properties for the channels
        PropertyEntry propertyEntry = ScribePropertiesManager.getEntries().get(type);
        if (propertyEntry != null) {
            if (propertyEntry.getType().compareToIgnoreCase("scribe") == 0) {
                properties.put(propertyEntry.getKey(), propertyEntry.getValue());
            }
            if (propertyEntry.getType().compareToIgnoreCase("oauth.extension") == 0) {
                if (extendedParams == null) {
                    extendedParams = new HashMap<String, String>();
                }

                extendedParams.put(propertyEntry.getKey(), propertyEntry.getValue());
            }
        }
    }

    if (persist == true) {
        DAOFactory.getSubscriptionDAO().append(subscriptionEntry);
    }

    if (type.compareToIgnoreCase(AdaptorFactory.GENERIC_ADAPTOR_NAME) == 0) {
        channel = new UnAuthenticatedChannel(subscriptionEntry);
    } else {
        channel = new AuthenticatedChannel(subscriptionEntry, properties, extendedParams,
                Configuration.getAuthenticator());
    }

    if (channel != null)
        channel.setup();
    return channel;
}

From source file:eu.eidas.node.auth.connector.tests.AUCONNECTORSAMLTestCase.java

/**
 * In order to test the//from  w w  w .  j  a v  a  2s.c  om
 * {@link AUCONNECTORSAML#generateSpAuthnRequest(EIDASAuthnRequest)} a saml must
 * be generated.
 *
 * @return The Saml request.
 */
private static byte[] generateSAMLRequest(final String providerName, final boolean setCountry) {
    final AUCONNECTORSAML auconnectorsaml = new AUCONNECTORSAML();
    auconnectorsaml.setSamlSpInstance(TestingConstants.SAML_INSTANCE_CONS.toString());

    final IEIDASLogger mockLoggerBean = mock(IEIDASLogger.class);
    auconnectorsaml.setLoggerBean(mockLoggerBean);

    final EIDASAuthnRequest authData = new EIDASAuthnRequest();
    authData.setPersonalAttributeList(ATTR_LIST);
    authData.setAssertionConsumerServiceURL(TestingConstants.ASSERTION_URL_CONS.toString());
    authData.setIssuer(TestingConstants.SAML_ISSUER_CONS.toString());
    authData.setSamlId(TestingConstants.SAML_ID_CONS.toString());
    authData.setTokenSaml(SAML_TOKEN_ARRAY);
    authData.setProviderName(providerName);
    authData.setQaa(TestingConstants.QAALEVEL_CONS.intValue());
    authData.setSPID(TestingConstants.SPID_CONS.toString());
    authData.setDestination(TestingConstants.DESTINATION_CONS.toString());
    authData.setMessageFormatName("stork1");
    if (setCountry) {
        authData.setCitizenCountryCode(TestingConstants.LOCAL_CONS.toString());
    }
    auconnectorsaml.setSamlEngineFactory(new EidasSamlEngineFactory());
    final Properties configs = new Properties();
    configs.put(EIDASValues.NODE_SUPPORT_EIDAS_MESSAGE_FORMAT_ONLY.toString(), "false");
    AUCONNECTORUtil auconnectorutil = new AUCONNECTORUtil();
    auconnectorutil.setConfigs(configs);
    auconnectorsaml.setConnectorUtil(auconnectorutil);
    return auconnectorsaml.generateSpAuthnRequest(authData).getTokenSaml();
}

From source file:org.esigate.DriverFactory.java

/**
 * Loads all instances according to the properties parameter.
 * /*w  ww .  j a v a2 s .c o  m*/
 * @param props
 *            properties to use for configuration
 */
public static void configure(Properties props) {
    Properties defaultProperties = new Properties();

    HashMap<String, Properties> driversProps = new HashMap<String, Properties>();
    for (Enumeration<?> enumeration = props.propertyNames(); enumeration.hasMoreElements();) {
        String propertyName = (String) enumeration.nextElement();
        String value = props.getProperty(propertyName);
        int idx = propertyName.lastIndexOf('.');
        if (idx < 0) {
            defaultProperties.put(propertyName, value);
        } else {
            String prefix = propertyName.substring(0, idx);
            String name = propertyName.substring(idx + 1);
            Properties driverProperties = driversProps.get(prefix);
            if (driverProperties == null) {
                driverProperties = new Properties();
                driversProps.put(prefix, driverProperties);
            }
            driverProperties.put(name, value);
        }
    }

    // Merge with default properties
    Map<String, Driver> newInstances = new HashMap<String, Driver>();
    for (Entry<String, Properties> entry : driversProps.entrySet()) {
        String name = entry.getKey();
        Properties properties = new Properties();
        properties.putAll(defaultProperties);
        properties.putAll(entry.getValue());
        newInstances.put(name, createDriver(name, properties));
    }
    if (newInstances.get(DEFAULT_INSTANCE_NAME) == null
            && Parameters.REMOTE_URL_BASE.getValue(defaultProperties) != null) {

        newInstances.put(DEFAULT_INSTANCE_NAME, createDriver(DEFAULT_INSTANCE_NAME, defaultProperties));
    }

    instances = new IndexedInstances(newInstances);
}

From source file:eu.eidas.node.auth.connector.tests.AUCONNECTORSAMLTestCase.java

/**
 * In order to test the/* w w  w  . j  ava2s  .  c o  m*/
 * {@link AUCONNECTORSAML#processAuthenticationResponse(byte[], EIDASAuthnRequest, EIDASAuthnRequest, String)}
 * a SAML must be generated.
 *
 * @param samlId  The SAML Id.
 * @param isError True if it's to generate an error SAML response or succeed
 *                authentication SAML otherwise.
 * @return The SAML response.
 */
private static byte[] generateSAMLResponse(final String samlId, final boolean isError) {
    final AUCONNECTORSAML auconnectorsaml = new AUCONNECTORSAML();
    auconnectorsaml.setSamlSpInstance(TestingConstants.SAML_INSTANCE_CONS.toString());

    final IEIDASLogger mockLoggerBean = mock(IEIDASLogger.class);
    auconnectorsaml.setLoggerBean(mockLoggerBean);
    auconnectorsaml.setSamlEngineFactory(new EidasSamlEngineFactory());
    AUCONNECTORUtil auconnectorUtil = new AUCONNECTORUtil();
    final Properties configs = new Properties();
    configs.put(EIDASValues.NODE_SUPPORT_EIDAS_MESSAGE_FORMAT_ONLY.toString(), "false");
    auconnectorUtil.setConfigs(configs);
    auconnectorsaml.setConnectorUtil(auconnectorUtil);
    if (isError) {
        final String errorCode = "003002";
        final String errorMessage = "003002 - Authentication Failed.";
        return auconnectorsaml.generateErrorAuthenticationResponse(samlId,
                TestingConstants.SAML_ISSUER_CONS.toString(), TestingConstants.DESTINATION_CONS.toString(),
                TestingConstants.USER_IP_CONS.toString(), errorCode, StatusCode.AUTHN_FAILED_URI, errorMessage);
    } else {
        final EIDASAuthnRequest authData = new EIDASAuthnRequest();
        authData.setPersonalAttributeList(ATTR_LIST);
        authData.setAssertionConsumerServiceURL(TestingConstants.ASSERTION_URL_CONS.toString());
        authData.setIssuer(TestingConstants.SAML_ISSUER_CONS.toString());
        authData.setSamlId(samlId);
        authData.setTokenSaml(SAML_TOKEN_ARRAY);
        authData.setProviderName(TestingConstants.PROVIDERNAME_CERT_CONS.toString());
        authData.setQaa(TestingConstants.QAALEVEL_CONS.intValue());
        return auconnectorsaml.generateAuthenticationResponse(authData,
                TestingConstants.USER_IP_CONS.toString());
    }
}

From source file:com.alibaba.wasp.zookeeper.ZKConfig.java

/**
 * Make a Properties object holding ZooKeeper config equivalent to zoo.cfg.
 * If there is a zoo.cfg in the classpath, simply read it in. Otherwise parse
 * the corresponding config options from the Wasp XML configs and generate
 * the appropriate ZooKeeper properties.
 * @param conf Configuration to read from.
 * @return Properties holding mappings representing ZooKeeper zoo.cfg file.
 *//* w  ww.  j av  a2  s  .  c o  m*/
public static Properties makeZKProps(Configuration conf) {
    // First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
    // it and grab its configuration properties.
    ClassLoader cl = FQuorumPeer.class.getClassLoader();
    final InputStream inputStream = cl.getResourceAsStream(FConstants.ZOOKEEPER_CONFIG_NAME);
    if (inputStream != null) {
        try {
            return parseZooCfg(conf, inputStream);
        } catch (IOException e) {
            LOG.warn("Cannot read " + FConstants.ZOOKEEPER_CONFIG_NAME + ", loading from XML files", e);
        }
    }

    // Otherwise, use the configuration options from Wasp's XML files.
    Properties zkProperties = new Properties();

    // Directly map all of the wasp.zookeeper.property.KEY properties.
    for (Entry<String, String> entry : conf) {
        String key = entry.getKey();
        if (key.startsWith(FConstants.ZK_CFG_PROPERTY_PREFIX)) {
            String zkKey = key.substring(FConstants.ZK_CFG_PROPERTY_PREFIX_LEN);
            String value = entry.getValue();
            // If the value has variables substitutions, need to do a get.
            if (value.contains(VARIABLE_START)) {
                value = conf.get(key);
            }
            zkProperties.put(zkKey, value);
        }
    }

    // If clientPort is not set, assign the default.
    if (zkProperties.getProperty(FConstants.CLIENT_PORT_STR) == null) {
        zkProperties.put(FConstants.CLIENT_PORT_STR, FConstants.DEFAULT_ZOOKEPER_CLIENT_PORT);
    }

    // Create the server.X properties.
    int peerPort = conf.getInt("wasp.zookeeper.peerport", 2888);
    int leaderPort = conf.getInt("wasp.zookeeper.leaderport", 3888);

    final String[] serverHosts = conf.getStrings(FConstants.ZOOKEEPER_QUORUM, FConstants.LOCALHOST);
    for (int i = 0; i < serverHosts.length; ++i) {
        String serverHost = serverHosts[i];
        String address = serverHost + ":" + peerPort + ":" + leaderPort;
        String key = "server." + i;
        zkProperties.put(key, address);
    }

    return zkProperties;
}

From source file:com.ikon.util.impexp.RepositoryImporter.java

/**
 * Import mail./*  w w w  .j a v a  2  s.c o  m*/
 */
private static ImpExpStats importMail(String token, File fs, String fldPath, String fileName, File fDoc,
        String metadata, Writer out, InfoDecorator deco) throws IOException, PathNotFoundException,
        AccessDeniedException, RepositoryException, DatabaseException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    MailModule mm = ModuleManager.getMailModule();
    Properties props = System.getProperties();
    props.put("mail.host", "smtp.dummydomain.com");
    props.put("mail.transport.protocol", "smtp");
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Mail mail = new Mail();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata.equals("JSON")) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                MailMetadata mmd = gson.fromJson(fr, MailMetadata.class);
                mail.setPath(fldPath + "/" + fileName);
                mmd.setPath(mail.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Mail Metadata: {}", mmd);

                // Apply metadata
                ma.importWithMetadata(mmd);

                // Add attachments
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage msg = new MimeMessage(mailSession, fisContent);
                mail = MailUtils.messageToMail(msg);
                mail.setPath(fldPath + "/" + mmd.getName());
                MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

                FileLogger.info(BASE_NAME, "Created document ''{0}''", mail.getPath());
                log.info("Created document '{}'", mail.getPath());
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage msg = new MimeMessage(mailSession, fisContent);
            mail = MailUtils.messageToMail(msg);
            mail.setPath(fldPath + "/" + fileName);
            mm.create(token, mail);
            MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());

            FileLogger.info(BASE_NAME, "Created mail ''{0}''", mail.getPath());
            log.info("Created mail ''{}''", mail.getPath());
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setMails(stats.getMails() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", mail.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", mail.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", mail.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", mail.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", mail.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", mail.getPath());
    } catch (MessagingException e) {
        log.warn("MessagingException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "MessagingException ''{0}''", mail.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:org.pentaho.support.standalone.SDSupportUtility.java

/**
 * sets bi server path/*  w  ww. j  a v a 2 s .  c  o  m*/
 * 
 * @param prop
 */
private static void setBIServerPath(Properties prop) {

    prop.put(SDConstant.TOM_PATH, prop.getProperty(SDConstant.BI_TOM_PATH));

    WEB_XML = new StringBuilder();
    WEB_XML.append(prop.getProperty(SDConstant.BI_TOM_PATH)).append(File.separator).append(SDConstant.WEB_APP)
            .append(File.separator).append(SDConstant.PENTAHO).append(File.separator).append(SDConstant.WEB_INF)
            .append(File.separator).append(SDConstant.WEB_XML);

    prop.put(SDConstant.WEB_XML_PATH, WEB_XML.toString());

    if (!installType.equalsIgnoreCase("Manual")) {

        prop.put(SDConstant.PENTAHO_SOLU_PATH,
                prop.getProperty(SDConstant.BI_PATH) + File.separator + SDConstant.PENTAHO_SOL_DIR);
    }

    if (installType.equalsIgnoreCase("Installer")) {

        prop.put(SDConstant.LOG_FILE_PATH,
                prop.getProperty(SDConstant.BI_TOM_PATH) + File.separator + SDConstant.WEB_APP + File.separator
                        + SDConstant.PENTAHO + File.separator + SDConstant.WEB_INF + File.separator
                        + SDConstant.CLASSES + File.separator + SDConstant.LOG4J_XML);
    } else {

        prop.put(SDConstant.LOG_FILE_PATH, prop.getProperty(SDConstant.BI_TOM_PATH) + File.separator
                + SDConstant.TOM_LOG + File.separator + SDConstant.LOG_FILE);
    }

}