Example usage for java.util Properties size

List of usage examples for java.util Properties size

Introduction

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

Prototype

@Override
    public int size() 

Source Link

Usage

From source file:org.pentaho.platform.plugin.services.importer.LocaleFilesProcessor.java

/**
 * /*from  w w  w. j  ava  2  s  . co  m*/
 * @param file
 * @param parentPath
 * @param bytes
 * @return false - means discard the file extension type
 * @throws IOException
 */
public boolean isLocaleFile(IRepositoryFileBundle file, String parentPath, byte[] bytes) throws IOException {

    boolean isLocale = false;
    String fileName = file.getFile().getName();
    String actualFilePath = file.getPath();
    RepositoryFile localeRepositoryFile = file.getFile();
    if (ImportSession.getSession().getManifest() != null
            && ImportSession.getSession().getManifest().getManifestInformation().getManifestVersion() != null) {
        fileName = ExportFileNameEncoder.decodeZipFileName(fileName);
        actualFilePath = ExportFileNameEncoder.decodeZipFileName(actualFilePath);
        localeRepositoryFile = new RepositoryFile.Builder(localeRepositoryFile)
                .name(ExportFileNameEncoder.decodeZipFileName(localeRepositoryFile.getName())).build();
    }
    int sourceVersion = 0; // 0 = Not a local file, 1 = 4.8 .properties file, 2= Sugar 5.0 .local file
    if (fileName.endsWith(PROPERTIES_EXT)) {
        sourceVersion = 1;
    } else if (fileName.endsWith(LOCALE_EXT)) {
        sourceVersion = 2;
    }
    if (sourceVersion != 0) {
        InputStream inputStream = new ByteArrayInputStream(bytes);
        Properties properties = loadProperties(inputStream);

        String name = getProperty(properties, NAME, sourceVersion);
        String title = getProperty(properties, TITLE, sourceVersion);
        String description = getProperty(properties, DESCRIPTION, sourceVersion);
        String url_name = getProperty(properties, URL_NAME, sourceVersion);
        String url_description = getProperty(properties, URL_DESCRIPTION, sourceVersion);

        if (!StringUtils.isEmpty(url_name)) {
            name = url_name;
        }
        if (!StringUtils.isEmpty(title)) {
            name = title;
        }

        description = !StringUtils.isEmpty(description) ? description : "";
        if (!StringUtils.isEmpty(url_description)) {
            description = url_description;
        }

        if (!StringUtils.isEmpty(name)) {
            String filePath = (actualFilePath.equals("/") || actualFilePath.equals("\\")) ? "" : actualFilePath;
            filePath = RepositoryFilenameUtils.concat(parentPath, filePath);
            LocaleFileDescriptor localeFile = new LocaleFileDescriptor(name, description, filePath,
                    localeRepositoryFile, inputStream);
            localeFiles.add(localeFile);

            /**
             * assumes that the properties file has additional localization attributes and should be imported
             */
            if (properties.size() <= 2 || sourceVersion == 2) {
                isLocale = true;
            }
        }
    }
    return isLocale;
}

From source file:org.rhq.bundle.ant.AntLauncherTest.java

public void testHandover() throws Exception {
    AntLauncher ant = new AntLauncher(true);

    final List<HandoverInfoArgument> handoverInfoArguments = new ArrayList<HandoverInfoArgument>();
    HandoverTarget handoverTarget = new HandoverTarget() {
        @Override/*from ww  w .jav a  2 s .  c o  m*/
        public boolean handoverContent(HandoverInfo handoverInfo) {
            HandoverInfoArgument handoverInfoArgument;
            try {
                handoverInfoArgument = new HandoverInfoArgument(handoverInfo);
            } catch (IOException e) {
                return false;
            }
            handoverInfoArguments.add(handoverInfoArgument);
            try {
                FileUtil.writeFile(handoverInfo.getContent(), handoverInfoArgument.handoverInfoTestContentFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
    };
    ant.setHandoverTarget(handoverTarget);

    List<BuildListener> buildListeners = createBuildListeners();
    Properties inputProps = createInputProperties("/handover-test-bundle-input.properties");

    BundleAntProject project = ant.executeBundleDeployFile(getFileFromTestClasses("handover-test-bundle.xml"),
            inputProps, buildListeners);
    assertNotNull(project);
    assertEquals(project.getBundleName(), "example.com (EAP 6)");
    assertEquals(project.getBundleVersion(), "1.0");
    assertEquals(project.getBundleDescription(), "example.com corporate website hosted on EAP 6");

    Set<String> bundleFiles = project.getBundleFileNames();
    assertNotNull(bundleFiles);
    assertEquals(bundleFiles.size(), 2, String.valueOf(bundleFiles));
    assertTrue(bundleFiles.contains("prepareDatasource.cli"), String.valueOf(bundleFiles)); // handed over file
    assertTrue(bundleFiles.contains("fileToHandover.zip"), String.valueOf(bundleFiles)); // handed over archive

    ConfigurationDefinition projectConfigDef = project.getConfigurationDefinition();
    assertEquals(projectConfigDef.getPropertyDefinitions().size(), 3,
            String.valueOf(projectConfigDef.getPropertyDefinitions()));

    PropertyDefinitionSimple propDef = projectConfigDef
            .getPropertyDefinitionSimple("myapp.datasource.property");
    assertNotNull(propDef);
    assertEquals(propDef.getType(), PropertySimpleType.INTEGER);
    assertTrue(propDef.isRequired());

    propDef = projectConfigDef.getPropertyDefinitionSimple("myapp.listener.port");
    assertNotNull(propDef);
    assertEquals(propDef.getType(), PropertySimpleType.INTEGER);
    assertTrue(propDef.isRequired());

    propDef = projectConfigDef.getPropertyDefinitionSimple("myapp.runtime.name");
    assertNotNull(propDef);
    assertEquals(propDef.getType(), PropertySimpleType.STRING);
    assertTrue(propDef.isRequired());

    Configuration projectConfig = project.getConfiguration();
    assertNotNull(projectConfig);
    assertEquals(projectConfig.getProperties().size(), 3, String.valueOf(projectConfig.getProperties()));
    assertEquals(projectConfig.getSimpleValue("myapp.datasource.property"), "10",
            String.valueOf(projectConfig.getProperties()));
    assertEquals(projectConfig.getSimpleValue("myapp.listener.port"), "9777",
            String.valueOf(projectConfig.getProperties()));
    assertEquals(projectConfig.getSimpleValue("myapp.runtime.name"), "site.war",
            String.valueOf(projectConfig.getProperties()));

    assertEquals(handoverInfoArguments.size(), 2, String.valueOf(handoverInfoArguments));
    Iterator<HandoverInfoArgument> handoverInfoIterator = handoverInfoArguments.iterator();

    HandoverInfoArgument handoverInfoArgument = handoverInfoIterator.next();
    HandoverInfo handoverInfo = handoverInfoArgument.handoverInfo;
    InputStream cliScriptContent = getClass().getClassLoader().getResourceAsStream("prepareDatasource.cli");
    assertNotNull(cliScriptContent);
    FileInputStream actualContent = new FileInputStream(handoverInfoArgument.handoverInfoTestContentFile);
    assertEquals(slurp(actualContent), slurp(cliScriptContent));
    assertEquals(handoverInfo.getFilename(), "prepareDatasource.cli");
    assertEquals(handoverInfo.getAction(), "execute-script");
    assertEquals(handoverInfo.getParams(), Collections.emptyMap());
    assertEquals(handoverInfo.isRevert(), false);

    handoverInfoArgument = handoverInfoIterator.next();
    handoverInfo = handoverInfoArgument.handoverInfo;
    final Properties[] propertiesHolder = new Properties[1];
    ZipUtil.walkZipFile(handoverInfoArgument.handoverInfoTestContentFile, new ZipUtil.ZipEntryVisitor() {
        @Override
        public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception {
            String entryName = entry.getName();
            if (entryName.equals("archived-subdir/archived-file-in-subdir.properties")) {
                Properties properties = new Properties();
                properties.load(stream);
                propertiesHolder[0] = properties;
            }
            return true;
        }
    });
    Properties properties = propertiesHolder[0];
    assertNotNull(properties);
    assertEquals(properties.size(), 3, String.valueOf(properties));
    assertEquals(properties.getProperty("templatized.variable"), "9777", String.valueOf(properties));
    assertEquals(handoverInfo.getFilename(), "fileToHandover.zip");
    assertEquals(handoverInfo.getAction(), "deployment");
    assertEquals(handoverInfo.getParams(), new HashMap<String, String>() {
        {
            put("runtimeName", "site.war");
        }
    });
    assertEquals(handoverInfo.isRevert(), false);
}

From source file:com.joptimizer.util.MPSParserNetlibTest.java

/**
 * Tests the parsing of a netlib problem.
 *///from w w  w .ja  v a  2s  . com
public void xxxtestSingleNetlib() throws Exception {
    log.debug("testSingleNetlib");
    //String problemName = "afiro";
    //String problemName = "afiroPresolved";
    //String problemName = "adlittle";
    //String problemName = "kb2";
    //String problemName = "sc50a";
    //String problemName = "sc50b";
    //String problemName = "blend";
    //String problemName = "scorpion";
    //String problemName = "recipe";
    //String problemName = "recipePresolved";
    //String problemName = "sctap1";
    //String problemName = "fit1d";
    //String problemName = "israel";
    //String problemName = "grow15";
    //String problemName = "etamacro";
    //String problemName = "pilot";
    //String problemName = "pilot4";
    //String problemName = "osa-14";
    //String problemName = "brandyPresolved";
    String problemName = "maros";

    File f = Utils.getClasspathResourceAsFile("lp" + File.separator + "netlib" + File.separator + problemName
            + File.separator + problemName + ".mps");
    MPSParser mpsParser = new MPSParser();
    mpsParser.parse(f);

    Properties expectedSolProps = null;
    try {
        //this is the solution of the mps problem given by Mathematica
        expectedSolProps = load(Utils.getClasspathResourceAsFile(
                "lp" + File.separator + "netlib" + File.separator + problemName + File.separator + "sol.txt"));
    } catch (Exception e) {
    }

    log.debug("name: " + mpsParser.getName());
    log.debug("n   : " + mpsParser.getN());
    log.debug("meq : " + mpsParser.getMeq());
    log.debug("mieq: " + mpsParser.getMieq());
    log.debug("meq+mieq: " + (mpsParser.getMeq() + mpsParser.getMieq()));
    List<String> variablesNames = mpsParser.getVariablesNames();
    log.debug("x: " + ArrayUtils.toString(variablesNames));
    //      log.debug("c: " + ArrayUtils.toString(p.getC()));
    //      log.debug("G: " + ArrayUtils.toString(p.getG()));
    //      log.debug("h: " + ArrayUtils.toString(p.getH()));
    //      log.debug("A: " + ArrayUtils.toString(p.getA()));
    //      log.debug("b: " + ArrayUtils.toString(p.getB()));
    //      log.debug("lb:" + ArrayUtils.toString(p.getLb()));
    //      log.debug("ub:" + ArrayUtils.toString(p.getUb()));

    //check consistency: if the problem was correctly parsed, the expectedSol must be its solution
    double delta = 1.e-7;
    if (expectedSolProps != null) {
        //key = variable name
        //value = sol value
        assertEquals(expectedSolProps.size(), variablesNames.size());
        RealVector expectedSol = new ArrayRealVector(variablesNames.size());
        for (int i = 0; i < variablesNames.size(); i++) {
            expectedSol.setEntry(i, Double.parseDouble(expectedSolProps.getProperty(variablesNames.get(i))));
        }
        log.debug("expectedSol: " + ArrayUtils.toString(expectedSol.toArray()));

        //check objective function value
        Map<String, LPNetlibProblem> problemsMap = LPNetlibProblem.loadAllProblems();
        LPNetlibProblem problem = problemsMap.get(problemName);
        RealVector c = new ArrayRealVector(mpsParser.getC().toArray());
        double value = c.dotProduct(expectedSol);
        log.debug("optimalValue: " + problem.optimalValue);
        log.debug("value       : " + value);
        assertEquals(problem.optimalValue, value, delta);

        //check G.x < h
        if (mpsParser.getG() != null) {
            RealMatrix G = new Array2DRowRealMatrix(mpsParser.getG().toArray());
            RealVector h = new ArrayRealVector(mpsParser.getH().toArray());
            RealVector Gxh = G.operate(expectedSol).subtract(h);
            double maxGxh = -Double.MAX_VALUE;
            for (int i = 0; i < Gxh.getDimension(); i++) {
                //log.debug(i);
                maxGxh = Math.max(maxGxh, Gxh.getEntry(i));
                assertTrue(Gxh.getEntry(i) <= 0);
            }
            log.debug("max(G.x - h): " + maxGxh);
        }

        //check A.x = b
        if (mpsParser.getA() != null) {
            RealMatrix A = new Array2DRowRealMatrix(mpsParser.getA().toArray());
            RealVector b = new ArrayRealVector(mpsParser.getB().toArray());
            RealVector Axb = A.operate(expectedSol).subtract(b);
            double norm = Axb.getNorm();
            log.debug("||A.x -b||: " + norm);
            assertEquals(0., norm, delta * mpsParser.getN());//some more tolerance
        }

        //check upper and lower bounds
        for (int i = 0; i < mpsParser.getLb().size(); i++) {
            double di = Double.isNaN(mpsParser.getLb().getQuick(i)) ? -Double.MAX_VALUE
                    : mpsParser.getLb().getQuick(i);
            assertTrue(di <= expectedSol.getEntry(i));
        }
        for (int i = 0; i < mpsParser.getUb().size(); i++) {
            double di = Double.isNaN(mpsParser.getUb().getQuick(i)) ? Double.MAX_VALUE
                    : mpsParser.getUb().getQuick(i);
            assertTrue(di >= expectedSol.getEntry(i));
        }
    }

    Utils.writeDoubleArrayToFile(mpsParser.getC().toArray(), "target" + File.separator + "c.txt");
    Utils.writeDoubleMatrixToFile(mpsParser.getG().toArray(), "target" + File.separator + "G.csv");
    Utils.writeDoubleArrayToFile(mpsParser.getH().toArray(), "target" + File.separator + "h.txt");
    Utils.writeDoubleMatrixToFile(mpsParser.getA().toArray(), "target" + File.separator + "A.csv");
    Utils.writeDoubleArrayToFile(mpsParser.getB().toArray(), "target" + File.separator + "b.txt");
    Utils.writeDoubleArrayToFile(mpsParser.getLb().toArray(), "target" + File.separator + "lb.txt");
    Utils.writeDoubleArrayToFile(mpsParser.getUb().toArray(), "target" + File.separator + "ub.txt");
}

From source file:org.jahia.services.usermanager.jcr.JCRUserManagerProvider.java

/**
 * Find users according to a table of name=value properties. If the left
 * side value is "*" for a property then it will be tested against all the
 * properties. ie *=test* will match every property that starts with "test"
 *
 * @param searchCriterias a Properties object that contains search criteria
 *                        in the format name,value (for example "*"="*" or "username"="*test*") or
 *                        null to search without criteria
 * @param external do we consider only external users? <code>null</code> if all users should be considered
 * @param providerKey the key of the user provider; <code>null</code> if all users should be considered
 * @return Set a set of JahiaUser elements that correspond to those
 *         search criteria// ww w  . ja  v a  2  s.c o m
 */
public Set<JahiaUser> searchUsers(final Properties searchCriterias, final Boolean external,
        final String providerKey) {
    try {
        return jcrTemplate.doExecuteWithSystemSession(new JCRCallback<Set<JahiaUser>>() {
            public Set<JahiaUser> doInJCR(JCRSessionWrapper session) throws RepositoryException {
                Set<JahiaUser> users = new HashSet<JahiaUser>();
                if (session.getWorkspace().getQueryManager() != null) {
                    StringBuilder query = new StringBuilder(128);
                    if (external != null) {
                        query.append("u.[" + JCRUser.J_EXTERNAL + "] = '").append(external).append("'");
                    }
                    if (providerKey != null) {
                        query.append(query.length() > 0 ? " AND " : "")
                                .append(" u.[" + JCRUser.J_EXTERNAL_SOURCE + "] = '").append(providerKey)
                                .append("'");
                    }

                    if (searchCriterias != null && searchCriterias.size() > 0) {
                        // Avoid wildcard attribute
                        if (!(searchCriterias.containsKey("*") && searchCriterias.size() == 1
                                && searchCriterias.getProperty("*").equals("*"))) {
                            Iterator<Map.Entry<Object, Object>> objectIterator = searchCriterias.entrySet()
                                    .iterator();
                            if (objectIterator.hasNext()) {
                                query.append(query.length() > 0 ? " AND " : "").append(" (");
                                while (objectIterator.hasNext()) {
                                    Map.Entry<Object, Object> entry = objectIterator.next();
                                    String propertyKey = (String) entry.getKey();
                                    if ("username".equals(propertyKey)) {
                                        propertyKey = "j:nodename";
                                    }
                                    String propertyValue = (String) entry.getValue();
                                    if ("*".equals(propertyValue)) {
                                        propertyValue = "%";
                                    } else {
                                        if (propertyValue.contains("*")) {
                                            propertyValue = propertyValue.replaceAll("\\*", "%");
                                        } else {
                                            propertyValue = propertyValue + "%";
                                        }
                                    }
                                    if ("*".equals(propertyKey)) {
                                        query.append("(CONTAINS(u.*,'" + propertyValue.replaceAll("%", "")
                                                + "') OR LOWER(u.[j:nodename]) LIKE '")
                                                .append(propertyValue.toLowerCase()).append("') ");
                                    } else {
                                        query.append(
                                                "LOWER(u.[" + propertyKey.replaceAll("\\.", "\\\\.") + "])")
                                                .append(" LIKE '").append(propertyValue.toLowerCase())
                                                .append("'");
                                    }
                                    if (objectIterator.hasNext()) {
                                        query.append(" OR ");
                                    }
                                }
                                query.append(")");
                            }
                        }
                    }
                    if (query.length() > 0) {
                        query.insert(0, "WHERE ");
                    }
                    query.insert(0, "SELECT * FROM [" + Constants.JAHIANT_USER + "] as u ");
                    query.append(" ORDER BY u.[j:nodename]");
                    if (logger.isDebugEnabled()) {
                        logger.debug(query.toString());
                    }
                    Query q = session.getWorkspace().getQueryManager().createQuery(query.toString(),
                            Query.JCR_SQL2);
                    QueryResult qr = q.execute();
                    NodeIterator ni = qr.getNodes();
                    while (ni.hasNext()) {
                        Node usersFolderNode = ni.nextNode();
                        users.add(new JCRUser(usersFolderNode.getIdentifier()));
                    }
                }

                return users;
            }
        });
    } catch (RepositoryException e) {
        logger.error("Error while searching for users", e);
        return new HashSet<JahiaUser>();
    }
}

From source file:org.apache.jmeter.JMeter.java

@Override
public String[][] getIconMappings() {
    final String defaultIconProp = "org/apache/jmeter/images/icon.properties"; //$NON-NLS-1$
    final String iconSize = JMeterUtils.getPropDefault(TREE_ICON_SIZE, DEFAULT_TREE_ICON_SIZE);
    String iconProp = JMeterUtils.getPropDefault("jmeter.icons", defaultIconProp);//$NON-NLS-1$
    Properties p = JMeterUtils.loadProperties(iconProp);
    if (p == null && !iconProp.equals(defaultIconProp)) {
        log.info(iconProp + " not found - using " + defaultIconProp);
        iconProp = defaultIconProp;/*from w  w w . j  a va 2 s.  c o  m*/
        p = JMeterUtils.loadProperties(iconProp);
    }
    if (p == null) {
        log.info(iconProp + " not found - using inbuilt icon set");
        return DEFAULT_ICONS;
    }
    log.info("Loaded icon properties from " + iconProp);
    String[][] iconlist = new String[p.size()][3];
    Enumeration<?> pe = p.keys();
    int i = 0;
    while (pe.hasMoreElements()) {
        String key = (String) pe.nextElement();
        String[] icons = JOrphanUtils.split(p.getProperty(key), " ");//$NON-NLS-1$
        iconlist[i][0] = key;
        iconlist[i][1] = icons[0].replace(KEY_SIZE, iconSize);
        if (icons.length > 1) {
            iconlist[i][2] = icons[1].replace(KEY_SIZE, iconSize);
        }
        i++;
    }
    return iconlist;
}

From source file:org.infoglue.cms.util.CmsPropertyHandler.java

public static Properties getCharacterReplacingMapping() {
    Properties properties = new Properties();

    String characterReplacingMappingString = CmsPropertyHandler.getServerNodeDataProperty(null,
            "niceURICharacterReplacingMapping", true, null);
    logger.info("characterReplacingMappingString:" + characterReplacingMappingString);
    if (characterReplacingMappingString != null && !characterReplacingMappingString.equals("")) {
        try {/* www  .  j a v a2s.  c  om*/
            properties.load(new ByteArrayInputStream(characterReplacingMappingString.getBytes("ISO-8859-1")));
        } catch (Exception e) {
            logger.error("Error loading properties from string. Reason:" + e.getMessage());
            e.printStackTrace();
        }
    }
    if (properties.size() == 0) {
        properties.put("", "a");
        properties.put("", "a");
        properties.put("", "o");
        properties.put("", "A");
        properties.put("", "A");
        properties.put("", "O");
    }

    return properties;
}

From source file:org.springframework.data.jdbc.config.oracle.PoolingDataSourceBeanDefinitionParser.java

protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    ResourceLoader rl = parserContext.getReaderContext().getResourceLoader();
    //attributes/*from  w w w . java 2 s  .  c  o  m*/
    String propertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);
    String connectionPropertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);

    String connectionPropertyPrefix = element.getAttribute(CONNECTION_PROPERTIES_PREFIX_ATTRIBUTE);
    String cachingPropertyPrefix = element.getAttribute(CONNECTON_CACHE_PROPERTIS_PREFIX_ATTRIBUTE);
    String url = element.getAttribute(URL_ATTRIBUTE);
    String username = element.getAttribute(USERNAME_ATTRIBUTE);
    String password = element.getAttribute(PASSWORD_ATTRIBUTE);
    String onsConfiguration = element.getAttribute(ONS_CONFIGURATION_ATTRIBUTE);
    String fastConnectionFailoverEnabled = element.getAttribute(FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
    String connectionCachingEnabled = element.getAttribute(CONNECTION_CACHING_ENABLED_ATTRIBUTE);

    boolean propertyFileProvided = false;

    Map<String, Object> providedProperties = new HashMap<String, Object>();

    // defaults
    if (!StringUtils.hasText(propertyFileLocation) && !StringUtils.hasText(connectionPropertyFileLocation)) {
        propertyFileLocation = DEFAULT_PROPERTY_FILE_LOCATION;
    }
    if (!StringUtils.hasText(connectionPropertyPrefix)) {
        connectionPropertyPrefix = DEFAULT_PROPERTY_PREFIX;
    }

    // look for property files
    if (StringUtils.hasText(propertyFileLocation)) {
        logger.debug("Using properties location: " + propertyFileLocation);
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(propertyFileLocation);
        Resource r = rl.getResource(resolvedLocation);
        logger.debug("Loading properties from resource: " + r);
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        factoryBean.setLocation(r);
        try {
            factoryBean.afterPropertiesSet();
            Properties resource = factoryBean.getObject();
            for (Map.Entry<Object, Object> entry : resource.entrySet()) {
                providedProperties.put((String) entry.getKey(), entry.getValue());
            }
            propertyFileProvided = true;
        } catch (FileNotFoundException e) {
            propertyFileProvided = false;
            if (propertyFileLocation.equals(DEFAULT_PROPERTY_FILE_LOCATION)) {
                logger.debug("Unable to find " + propertyFileLocation);
            } else {
                parserContext.getReaderContext()
                        .error("pooling-datasource defined with attribute '" + PROPERTIES_LOCATION_ATTRIBUTE
                                + "' but the property file was not found at location \"" + propertyFileLocation
                                + "\"", element);
            }
        } catch (IOException e) {
            logger.warn("Error loading " + propertyFileLocation + ": " + e.getMessage());
        }
    } else {
        propertyFileProvided = false;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Using provided properties: " + providedProperties);
    }

    if (connectionPropertyPrefix == null) {
        connectionPropertyPrefix = "";
    }
    if (connectionPropertyPrefix.length() > 0 && !connectionPropertyPrefix.endsWith(".")) {
        connectionPropertyPrefix = connectionPropertyPrefix + ".";
    }
    logger.debug("Using connection properties prefix: " + connectionPropertyPrefix);

    if (cachingPropertyPrefix == null) {
        cachingPropertyPrefix = "";
    }
    if (cachingPropertyPrefix.length() > 0 && !cachingPropertyPrefix.endsWith(".")) {
        cachingPropertyPrefix = cachingPropertyPrefix + ".";
    }
    logger.debug("Using caching properties prefix: " + cachingPropertyPrefix);

    if (!(StringUtils.hasText(connectionCachingEnabled) || providedProperties
            .containsKey(attributeToPropertyMap.get(CONNECTION_CACHING_ENABLED_ATTRIBUTE)))) {
        connectionCachingEnabled = DEFAULT_CONNECTION_CACHING_ENABLED;
    }

    setRequiredAttribute(builder, parserContext, element, providedProperties, connectionPropertyPrefix,
            propertyFileProvided, url, URL_ATTRIBUTE, "URL");
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, username, USERNAME_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, password, PASSWORD_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, connectionCachingEnabled,
            CONNECTION_CACHING_ENABLED_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, fastConnectionFailoverEnabled,
            FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, onsConfiguration,
            ONS_CONFIGURATION_ATTRIBUTE);

    Properties providedConnectionProperties = new Properties();
    Properties providedCachingProperties = new Properties();
    for (String key : providedProperties.keySet()) {
        if (StringUtils.hasText(connectionPropertyPrefix) && key.startsWith(connectionPropertyPrefix)) {
            String newKey = key.substring(connectionPropertyPrefix.length());
            providedConnectionProperties.put(newKey, providedProperties.get(key));
        } else {
            if (StringUtils.hasText(cachingPropertyPrefix) && key.startsWith(cachingPropertyPrefix)) {
                String newKey = key.substring(cachingPropertyPrefix.length());
                providedCachingProperties.put(newKey, providedProperties.get(key));
            } else {
                providedConnectionProperties.put(key, providedProperties.get(key));
            }
        }
    }

    // look for connectionProperties
    Object connProperties = DomUtils.getChildElementValueByTagName(element,
            CONNECTION_PROPERTIES_CHILD_ELEMENT);
    if (connProperties != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using connection-properties");
        }
        builder.addPropertyValue("connectionProperties", connProperties);
    } else {
        if (providedConnectionProperties.size() > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using provided connection properties: " + providedConnectionProperties);
            }
            builder.addPropertyValue("connectionProperties", providedConnectionProperties);
        }
    }

    // look for connectionCacheProperties
    Object cacheProperties = DomUtils.getChildElementValueByTagName(element,
            CONNECTION_CACHE_PROPERTIES_CHILD_ELEMENT);
    if (cacheProperties != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using connection-cache-properties: [" + cacheProperties + "]");
        }
        builder.addPropertyValue("connectionCacheProperties", cacheProperties);
    } else {
        if (providedCachingProperties.size() > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using provided caching properties: " + providedCachingProperties);
            }
            builder.addPropertyValue("connectionCacheProperties", providedCachingProperties);
        }
    }

    builder.setRole(BeanDefinition.ROLE_SUPPORT);
}

From source file:org.jahia.services.usermanager.JahiaUserManagerService.java

public Set<JCRUserNode> searchUsers(final Properties searchCriterias, String siteKey,
        final String[] providerKeys, boolean excludeProtected, JCRSessionWrapper session) {

    try {//  ww w.  j a  v  a 2s .c o m

        int limit = 0;
        Set<JCRUserNode> users = new HashSet<JCRUserNode>();

        if (session.getWorkspace().getQueryManager() != null) {

            StringBuilder query = new StringBuilder();

            // Add provider to query
            if (providerKeys != null) {
                List<JCRStoreProvider> providers = getProviders(siteKey, providerKeys, session);
                if (!providers.isEmpty()) {
                    query.append("(");
                    for (JCRStoreProvider provider : providers) {
                        query.append(query.length() > 1 ? " OR " : "");
                        if (provider.isDefault()) {
                            query.append("u.[j:external] = false");
                        } else {
                            query.append("ISDESCENDANTNODE('").append(provider.getMountPoint()).append("')");
                        }
                    }
                    query.append(")");
                } else {
                    return users;
                }
            }

            // Add criteria
            if (searchCriterias != null && !searchCriterias.isEmpty()) {
                Properties filters = (Properties) searchCriterias.clone();
                String operation = " OR ";
                if (filters.containsKey(MULTI_CRITERIA_SEARCH_OPERATION)) {
                    if (((String) filters.get(MULTI_CRITERIA_SEARCH_OPERATION)).trim().toLowerCase()
                            .equals("and")) {
                        operation = " AND ";
                    }
                    filters.remove(MULTI_CRITERIA_SEARCH_OPERATION);
                }
                if (filters.containsKey(COUNT_LIMIT)) {
                    limit = Integer.parseInt((String) filters.get(COUNT_LIMIT));
                    logger.debug("Limit of results has be set to " + limit);
                    filters.remove(COUNT_LIMIT);
                }
                // Avoid wildcard attribute
                if (!(filters.containsKey("*") && filters.size() == 1
                        && filters.getProperty("*").equals("*"))) {
                    Iterator<Map.Entry<Object, Object>> criteriaIterator = filters.entrySet().iterator();
                    if (criteriaIterator.hasNext()) {
                        query.append(query.length() > 0 ? " AND " : "").append(" (");
                        while (criteriaIterator.hasNext()) {
                            Map.Entry<Object, Object> entry = criteriaIterator.next();
                            String propertyKey = (String) entry.getKey();
                            if ("username".equals(propertyKey)) {
                                propertyKey = "j:nodename";
                            }
                            String propertyValue = (String) entry.getValue();
                            if ("*".equals(propertyValue)) {
                                propertyValue = "%";
                            } else {
                                if (propertyValue.indexOf('*') != -1) {
                                    propertyValue = Patterns.STAR.matcher(propertyValue).replaceAll("%");
                                } else {
                                    propertyValue = propertyValue + "%";
                                }
                            }
                            propertyValue = JCRContentUtils.sqlEncode(propertyValue);
                            if ("*".equals(propertyKey)) {
                                query.append("(CONTAINS(u.*,'"
                                        + QueryParser
                                                .escape(Patterns.PERCENT.matcher(propertyValue).replaceAll(""))
                                        + "') OR LOWER(u.[j:nodename]) LIKE '")
                                        .append(propertyValue.toLowerCase()).append("') ");
                            } else {
                                query.append("LOWER(u.[" + Patterns.DOT.matcher(propertyKey).replaceAll("\\\\.")
                                        + "])").append(" LIKE '").append(propertyValue.toLowerCase())
                                        .append("'");
                            }
                            if (criteriaIterator.hasNext()) {
                                query.append(operation);
                            }
                        }
                        query.append(")");
                    }
                }
            }

            if (query.length() > 0) {
                query.insert(0, " and ");
            }
            if (excludeProtected) {
                query.insert(0, " and [j:nodename] <> '" + GUEST_USERNAME + "'");
            }
            String s = (siteKey == null) ? "/users/" : "/sites/" + siteKey + "/users/";
            query.insert(0, "SELECT * FROM [" + Constants.JAHIANT_USER + "] as u where isdescendantnode(u,'"
                    + JCRContentUtils.sqlEncode(s) + "')");
            if (logger.isDebugEnabled()) {
                logger.debug(query.toString());
            }
            Query q = session.getWorkspace().getQueryManager().createQuery(query.toString(), Query.JCR_SQL2);
            if (limit > 0) {
                q.setLimit(limit);
            }
            QueryResult qr = q.execute();
            NodeIterator ni = qr.getNodes();
            while (ni.hasNext()) {
                Node userNode = ni.nextNode();
                users.add((JCRUserNode) userNode);
            }
        }

        return users;
    } catch (RepositoryException e) {
        logger.error("Error while searching for users", e);
        return new HashSet<JCRUserNode>();
    }
}

From source file:org.jets3t.apps.uploader.Uploader.java

/**
 * Retrieves a signed PUT URL from the given URL address.
 * The URL must point at a server-side script or service that accepts POST messages.
 * The POST message will include parameters for all the items in uploaderProperties,
 * that is everything in the file uploader.properties plus all the applet's parameters.
 * Based on this input, the server-side script decides whether to allow access and return
 * a signed PUT URL.//w  w w .j  ava 2  s .com
 *
 * @param credsProviderParamName
 * the name of the parameter containing the server URL target for the PUT request.
 * @return
 * the AWS credentials provided by the server-side script if access was allowed, null otherwise.
 *
 * @throws HttpException
 * @throws Exception
 */
private GatekeeperMessage contactGatewayServer(S3Object[] objects) throws Exception {
    // Retrieve credentials from URL location value by the property 'credentialsServiceUrl'.
    String gatekeeperUrl = uploaderProperties.getStringProperty("gatekeeperUrl",
            "Missing required property gatekeeperUrl");

    /*
     *  Build Gatekeeper request.
     */
    GatekeeperMessage gatekeeperMessage = new GatekeeperMessage();
    gatekeeperMessage.addApplicationProperties(userInputProperties); // Add User inputs as application properties.
    gatekeeperMessage.addApplicationProperties(parametersMap); // Add any Applet/Application parameters as application properties.

    // Make the Uploader's identifier available to Gatekeeper for version compatibility checking (if necessary)
    gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_CLIENT_VERSION_ID, UPLOADER_VERSION_ID);

    // If a prior failure has occurred, add information about this failure.
    if (priorFailureException != null) {
        gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_PRIOR_FAILURE_MESSAGE,
                priorFailureException.getMessage());
        // Now reset the prior failure variable.
        priorFailureException = null;
    }

    // Add all S3 objects as candiates for PUT signing.
    for (int i = 0; i < objects.length; i++) {
        SignatureRequest signatureRequest = new SignatureRequest(SignatureRequest.SIGNATURE_TYPE_PUT,
                objects[i].getKey());
        signatureRequest.setObjectMetadata(objects[i].getMetadataMap());

        gatekeeperMessage.addSignatureRequest(signatureRequest);
    }

    /*
     *  Build HttpClient POST message.
     */

    // Add all properties/parameters to credentials POST request.
    HttpPost postMethod = new HttpPost(gatekeeperUrl);
    Properties properties = gatekeeperMessage.encodeToProperties();

    Iterator<Map.Entry<Object, Object>> propsIter = properties.entrySet().iterator();
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(properties.size());
    while (propsIter.hasNext()) {
        Map.Entry<Object, Object> entry = propsIter.next();
        String fieldName = (String) entry.getKey();
        String fieldValue = (String) entry.getValue();
        parameters.add(new BasicNameValuePair(fieldName, fieldValue));
    }
    postMethod.setEntity(new UrlEncodedFormEntity(parameters));

    // Create Http Client if necessary, and include User Agent information.
    if (httpClientGatekeeper == null) {
        httpClientGatekeeper = initHttpConnection();
    }

    // Try to detect any necessary proxy configurations.
    try {
        HttpHost proxyHost = PluginProxyUtil.detectProxy(new URL(gatekeeperUrl));
        if (proxyHost != null) {
            httpClientGatekeeper.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
        ((DefaultHttpClient) httpClientGatekeeper).setCredentialsProvider(this);

    } catch (Throwable t) {
        log.debug("No proxy detected");
    }

    // Perform Gateway request.
    log.debug("Contacting Gatekeeper at: " + gatekeeperUrl);
    HttpResponse response = null;
    try {
        response = httpClientGatekeeper.execute(postMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        String contentType = response.getFirstHeader("Content-Type").getValue();
        if (responseCode == 200) {
            InputStream responseInputStream = null;

            Header encodingHeader = response.getFirstHeader("Content-Encoding");
            if (encodingHeader != null && "gzip".equalsIgnoreCase(encodingHeader.getValue())) {
                log.debug("Inflating gzip-encoded response");
                responseInputStream = new GZIPInputStream(response.getEntity().getContent());
            } else {
                responseInputStream = response.getEntity().getContent();
            }

            if (responseInputStream == null) {
                throw new IOException("No response input stream available from Gatekeeper");
            }

            Properties responseProperties = new Properties();
            try {
                responseProperties.load(responseInputStream);
            } finally {
                responseInputStream.close();
            }

            GatekeeperMessage gatekeeperResponseMessage = GatekeeperMessage
                    .decodeFromProperties(responseProperties);

            // Check for Gatekeeper Error Code in response.
            String gatekeeperErrorCode = gatekeeperResponseMessage.getApplicationProperties()
                    .getProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE);
            if (gatekeeperErrorCode != null) {
                log.warn("Received Gatekeeper error code: " + gatekeeperErrorCode);
                failWithFatalError(gatekeeperErrorCode);
                return null;
            }

            if (gatekeeperResponseMessage.getSignatureRequests().length != objects.length) {
                throw new Exception("The Gatekeeper service did not provide the necessary " + objects.length
                        + " response items");
            }

            return gatekeeperResponseMessage;
        } else {
            log.debug("The Gatekeeper did not permit a request. Response code: " + responseCode
                    + ", Response content type: " + contentType);
            throw new Exception("The Gatekeeper did not permit your request");
        }
    } catch (Exception e) {
        throw new Exception("Gatekeeper did not respond", e);
    } finally {
        EntityUtils.consume(response.getEntity());
    }
}

From source file:org.jahia.services.usermanager.jcr.JCRGroupManagerProvider.java

public Set<JahiaGroup> searchGroups(final int siteID, final Properties searchCriterias) {
    try {// w ww  . j a v  a  2s. c  o m
        return jcrTemplate.doExecuteWithSystemSession(new JCRCallback<Set<JahiaGroup>>() {
            public Set<JahiaGroup> doInJCR(JCRSessionWrapper session) throws RepositoryException {
                try {
                    Set<JahiaGroup> users = new HashSet<JahiaGroup>();
                    if (session.getWorkspace().getQueryManager() != null) {
                        StringBuilder query = new StringBuilder("SELECT * FROM [" + Constants.JAHIANT_GROUP
                                + "] as g WHERE g.[" + JCRGroup.J_EXTERNAL + "] = 'false'");
                        if (siteID <= 0) {
                            query.append(" AND ISCHILDNODE(g, '/groups')");
                        } else {
                            String siteName = sitesService.getSite(siteID).getSiteKey();
                            query.append(" AND ISCHILDNODE(g, '/sites/" + siteName + "/groups')");
                        }
                        if (searchCriterias != null && searchCriterias.size() > 0) {
                            // Avoid wildcard attribute
                            if (!(searchCriterias.containsKey("*") && searchCriterias.size() == 1
                                    && searchCriterias.getProperty("*").equals("*"))) {
                                Iterator<Map.Entry<Object, Object>> objectIterator = searchCriterias.entrySet()
                                        .iterator();
                                if (objectIterator.hasNext()) {
                                    query.append(" AND (");
                                    while (objectIterator.hasNext()) {
                                        Map.Entry<Object, Object> entry = objectIterator.next();
                                        String propertyKey = (String) entry.getKey();
                                        if ("groupname".equals(propertyKey)) {
                                            propertyKey = "j:nodename";
                                        }
                                        String propertyValue = (String) entry.getValue();
                                        if ("*".equals(propertyValue)) {
                                            propertyValue = "%";
                                        } else {
                                            if (propertyValue.contains("*")) {
                                                propertyValue = propertyValue.replaceAll("\\*", "%");
                                            } else {
                                                propertyValue = propertyValue + "%";
                                            }
                                        }
                                        if ("*".equals(propertyKey)) {
                                            query.append("(CONTAINS(g.*,'" + propertyValue.replaceAll("%", "")
                                                    + "') OR LOWER(g.[j:nodename]) LIKE '")
                                                    .append(propertyValue.toLowerCase()).append("') ");
                                        } else {
                                            query.append(
                                                    "LOWER(g.[" + propertyKey.replaceAll("\\.", "\\\\.") + "])")
                                                    .append(" LIKE '").append(propertyValue.toLowerCase())
                                                    .append("'");
                                        }
                                        if (objectIterator.hasNext()) {
                                            query.append(" OR ");
                                        }
                                    }
                                    query.append(")");
                                }
                            }
                        }
                        query.append(" ORDER BY g.[j:nodename]");
                        if (logger.isDebugEnabled()) {
                            logger.debug(query.toString());
                        }
                        Query q = session.getWorkspace().getQueryManager().createQuery(query.toString(),
                                Query.JCR_SQL2);
                        QueryResult qr = q.execute();
                        NodeIterator ni = qr.getNodes();
                        while (ni.hasNext()) {
                            Node usersFolderNode = ni.nextNode();
                            users.add(getGroup(usersFolderNode, usersFolderNode.getName(), siteID, false));
                        }
                    }
                    return users;
                } catch (JahiaException e) {
                    logger.error("Error searching groups for site " + siteID, e);
                    return null;
                }
            }
        });

    } catch (RepositoryException e) {
        logger.error("Error while searching groups", e);
        return new HashSet<JahiaGroup>();
    }
}