Example usage for java.util Map putAll

List of usage examples for java.util Map putAll

Introduction

In this page you can find the example usage for java.util Map putAll.

Prototype

void putAll(Map<? extends K, ? extends V> m);

Source Link

Document

Copies all of the mappings from the specified map to this map (optional operation).

Usage

From source file:com.square.client.gwt.server.service.UtilServiceGwtImpl.java

@Override
@SuppressWarnings("unchecked")
public Map<String, String> mapperCriteresRecherche(
        RemotePagingCriteriasGwt<? extends IsSerializable> criteres) {
    // on construit l'objet noyau suivant la correspondance
    try {//w w  w . j a  va2 s  .  com
        final Class cls = Class.forName(CORRESPONDANCE_TYPE.get(criteres.getCriterias().getClass().getName()));
        final Constructor ct = cls.getConstructor();
        final Object criteriasDto = ct.newInstance();

        // on convertit les criteres en criteres noyau
        mapperDozerBean.map(criteres.getCriterias(), criteriasDto);
        final RemotePagingCriteriasDto criteresDto = new RemotePagingCriteriasDto(criteriasDto,
                criteres.getFirstResult(), criteres.getMaxResult());
        final List<RemotePagingSort> listSort = mapperDozerBean.mapList(criteres.getListeSorts(),
                RemotePagingSort.class);
        criteresDto.setListeSorts(listSort);

        resetConverter();

        final Map<String, String> map = BeanUtils.describe(criteresDto.getCriterias());
        map.putAll(BeanUtils.describe(criteresDto));

        // on nettoie la map
        final Set<String> keyset = new HashSet<String>(map.keySet());
        for (String key : keyset) {
            if (StringUtils.isBlank(map.get(key)) || key.equals("class") || key.equals("criterias")) {
                map.remove(key);
            }
        }
        return map;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (SecurityException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (InstantiationException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        throw new TechnicalException(MESSAGE_ERREUR);
    }
}

From source file:com.bisone.saiku.security.replace.SessionService.java

public Map<String, Object> getAllSessionObjects() {
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Object p = auth.getPrincipal();
        //TODO ??
        createSession(auth, null, null);
        if (sessionHolder.containsKey(p)) {
            Map<String, Object> r = new HashMap<String, Object>();
            r.putAll(sessionHolder.get(p));
            return r;
        }/*ww  w .ja v a  2 s .c om*/

    }
    return new HashMap<String, Object>();
}

From source file:com.surveypanel.form.validation.RequiredValidator.java

@Override
public void validate(QuestionImpl question, FormData formData, Locale locale, Map<String, String> config,
        ValidationResult validationResult) throws Exception {
    Integer maximum = 0;/* w  ww  .  j av  a2 s.c  om*/
    Integer minimum = 0;

    String error_min = config.containsKey("error_min") ? config.get("error_min") : "form.error.min";
    String error_max = config.containsKey("error_max") ? config.get("error_max") : "form.error.max";
    String error_req = config.containsKey("error_req") ? config.get("error_req") : getDefaultErrorKey();

    String min = config.get("min");
    String max = config.get("max");

    if (max != null)
        maximum = Integer.parseInt(max);
    if (min != null)
        minimum = Integer.parseInt(min);

    if (question.isMulti()) {
        Map<String, List<String>> errorFields = new HashMap<String, List<String>>();
        Map<String, List<String>> validFieldNames = new HashMap<String, List<String>>();
        FormData[] values = (FormData[]) formData.getValue();
        for (FormData data : values) {
            String[] splitFieldName = data.getName().split("_");
            Map<String, List<String>> targetMap = validFieldNames;

            if (checkEmptyString((String) data.getValue())) {
                targetMap = errorFields;
                List<String> removed = validFieldNames.remove(splitFieldName[0]);
            }

            if (splitFieldName.length == 2) {
                List<String> list = targetMap.get(splitFieldName[0]);
                if (list == null) {
                    list = new ArrayList<String>();
                    list.add(splitFieldName[1]);
                    targetMap.put(splitFieldName[0], list);
                } else {
                    list.add(splitFieldName[1]);
                }
            } else {
                List<String> list = new ArrayList<String>();
                list.add(data.getName());
                targetMap.put(data.getName(), list);
            }
        }

        if (minimum > 0 && validFieldNames.size() < minimum) {
            validationResult.addError(
                    qDefinition.getText(error_min, new Object[] { question.getName(), min, minimum }, locale));
        }
        if (maximum > 0 && validFieldNames.size() > maximum) {
            validationResult.addError(
                    qDefinition.getText(error_max, new Object[] { question.getName(), min, maximum }, locale));
        }
        if (maximum == 0 && minimum == 0 && errorFields.size() > 0) {
            Map<String, List<String>> errorFieldsCopy = new HashMap<String, List<String>>();
            errorFieldsCopy.putAll(errorFields);
            for (String key : errorFields.keySet()) {
                if (errorFieldsCopy.containsKey(key) || !validFieldNames.containsKey(key)) {
                    validationResult.addError(key,
                            qDefinition.getText(error_req, new Object[] { key }, locale));
                } else {
                    errorFieldsCopy.remove(key);
                }
            }
            if (!errorFieldsCopy.isEmpty()) {
                validationResult
                        .addError(qDefinition.getText(error_req, new Object[] { question.getName() }, locale));
            }
        }
    } else {
        if (checkEmptyString((String) formData.getValue())) {
            validationResult
                    .addError(qDefinition.getText(error_req, new Object[] { question.getName() }, locale));
        }
    }

}

From source file:net.sf.jasperreports.customvisualization.export.CVElementJsonHandler.java

/**
 * /*from  w  w w  .j  a  v a  2  s .  com*/
 * Creates the main component configuration. This also includes the
 * information about which renderer to use.
 * 
 * @param context
 * @param element
 * @return
 */
@Override
public String getJsonFragment(JsonExporterContext context, JRGenericPrintElement element) {
    Map<String, Object> originalConfiguration = (Map<String, Object>) element
            .getParameterValue(CVPrintElement.CONFIGURATION);

    if (originalConfiguration == null) {
        log.warn("Configuration object in the element " + element + " is NULL!");
        throw new JRRuntimeException("Configuration object in the element " + element + " is NULL!");
    }

    // Duplicate the configuration.
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.putAll(originalConfiguration);

    ObjectMapper mapper = new ObjectMapper();
    try {
        if (!configuration.containsKey("instanceData")) {
            JsonExporter exporter = ((JsonExporter) context.getExporterRef());
            HtmlResourceHandler htmlResourceHandler = exporter.getExporterOutput() != null
                    ? exporter.getExporterOutput().getResourceHandler()
                    : null;

            Map<String, Object> jsonConfiguration = createConfigurationForJSON(configuration,
                    htmlResourceHandler);
            String instanceData = mapper.writeValueAsString(jsonConfiguration);

            configuration.put("instanceData", instanceData);
        }
    } catch (Exception ex) {
        log.warn("(JSON): Error dumping the JSON for the configuration...: " + ex.getMessage(), ex);
    }

    configuration.put("module", element.getParameterValue(CVPrintElement.MODULE));

    Map<String, Object> velocityContext = new HashMap<String, Object>();
    velocityContext.put("elementId", CVUtils.getElementId(element));
    velocityContext.put("configuration", configuration);

    return VelocityUtil.processTemplate(CV_ELEMENT_JSON_TEMPLATE, velocityContext);
}

From source file:com.glaf.activiti.executionlistener.UserTaskExecutionListener.java

@Override
public void notify(DelegateExecution execution) {
    logger.debug("----------------------------------------------------");
    logger.debug("-----------------UserTaskExecutionListener----------");
    logger.debug("----------------------------------------------------");

    CommandContext commandContext = Context.getCommandContext();

    logger.debug("dbSqlsession:" + commandContext.getDbSqlSession());
    logger.debug("sqlsession:" + commandContext.getDbSqlSession().getSqlSession());

    if (execution != null && outputVar != null) {
        Map<String, Object> paramMap = new java.util.HashMap<String, Object>();
        paramMap.putAll(execution.getVariables());

        String statement = "getMembershipUsers";

        String output = (String) outputVar.getValue(execution);

        if (statementId != null && statementId.getExpressionText() != null) {
            statement = statementId.getExpressionText();
            logger.debug("statementId:" + statement);
        }/*w  w  w .  j  a  v a  2s.c om*/

        if (roleId != null && roleId.getExpressionText() != null) {
            logger.debug("roleId:" + roleId.getExpressionText());
            paramMap.put("roleId", roleId.getExpressionText());
        }

        if (StringUtils.isNotEmpty(statement)) {
            MyBatisEntityDAO entityDAO = new MyBatisEntityDAO(commandContext.getDbSqlSession().getSqlSession());
            List<?> list = entityDAO.getList(statement, paramMap);
            if (list != null && !list.isEmpty()) {
                Collection<String> users = new java.util.HashSet<String>();

                for (Object object : list) {
                    if (object instanceof org.activiti.engine.identity.User) {
                        String actorId = ((org.activiti.engine.identity.User) object).getId();
                        if (!users.contains(actorId)) {
                            users.add(actorId);
                        }
                    } else if (object instanceof com.glaf.core.identity.User) {
                        String actorId = ((com.glaf.core.identity.User) object).getActorId();
                        if (!users.contains(actorId)) {
                            users.add(actorId);
                        }
                    }
                }

                logger.debug("users:" + users);

                if (users.size() > 0) {
                    execution.setVariable(output, users);
                }

            } else {
                String expr = (String) expression.getValue(execution);
                if (expr != null) {
                    if (expr.startsWith("user(") && expr.endsWith("")) {
                        expr = StringTools.replaceIgnoreCase(expr, "user(", "");
                        expr = StringTools.replaceIgnoreCase(expr, ")", "");
                        execution.setVariable(output, expr);
                    } else if (expr.startsWith("users(") && expr.endsWith("")) {
                        expr = StringTools.replaceIgnoreCase(expr, "users(", "");
                        expr = StringTools.replaceIgnoreCase(expr, ")", "");
                        List<String> candidateUsers = StringTools.split(expr, ",");
                        execution.setVariable(output, candidateUsers);
                    }
                }
            }
        }
    }
}

From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java

private Map getEnvVars() throws MojoExecutionException {
    if (beforeSql != null) {
        Map envVars = new HashMap();
        try {//from   ww  w.  j av  a2  s  .co m
            envVars.putAll(CommandLineUtils.getSystemEnvVars());
        } catch (IOException e) {
            throw new MojoExecutionException("Could not copy system environment variables.", e);
        }
        envVars.put("SQLPATH", getPluginTempDirectory().getAbsolutePath());
        File login = new File(getPluginTempDirectory(), "login.sql");
        // login.deleteOnExit();
        try {
            login.createNewFile();
            FileOutputStream loginFos;
            loginFos = new FileOutputStream(login);
            loginFos.write(beforeSql.getBytes());

            loginFos.flush();
            loginFos.close();
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Could not write " + login.getPath(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not write " + login.getPath(), e);
        }
        return envVars;
    } else {
        return null;
    }

}

From source file:com.github.etorres.codexposed.ArgValidator.java

/**
 * Example: set valid values to method parameters. Internally uses Java unmodifiable maps.
 * @param required - required parameter, empty map is allowed
 * @param optional - optional parameter/* www  .  java2  s. c o m*/
 * @return A new map combining both input parameters.
 * @throws NullPointerException When a required parameter has <code>null</code> value.
 */
public Map<String, String> mapParams(final Map<String, String> required,
        final @Nullable Map<String, String> optional) {
    final Map<String, String> required2 = unmodifiableMap(checkNotNull(required, "Uninitialized map"));
    final Map<String, String> optional2 = (optional != null ? unmodifiableMap(optional)
            : Collections.<String, String>emptyMap());
    // operate on the canonicalized version of the parameters
    final Map<String, String> response = new Hashtable<>(required2);
    response.putAll(optional2);
    return response;
}

From source file:com.github.etorres.codexposed.ArgValidator.java

/**
 * Example: set valid values to method parameters. Internally uses Java standard maps.
 * @param required - required parameter, empty map is allowed
 * @param optional - optional parameter/*from ww w. j a va  2 s . co  m*/
 * @return A new map combining both input parameters.
 * @throws NullPointerException When a required parameter has <code>null</code> value.
 */
public Map<String, String> mutableMapParams(final Map<String, String> required,
        final @Nullable Map<String, String> optional) {
    final Map<String, String> required2 = new Hashtable<>(checkNotNull(required, "Uninitialized list"));
    final Map<String, String> optional2 = (optional != null ? new Hashtable<>(optional)
            : new Hashtable<String, String>());
    // operate on the canonicalized version of the parameters
    final Map<String, String> response = new Hashtable<>(required2);
    response.putAll(optional2);
    return response;
}

From source file:com.irusist.xiaoao.turntable.service.RequestService.java

/**
 * ?//from  w w  w .j a  v a2s . com
 *
 * @param account
 *         ??
 * @param token
 *         oauth?token
 */
private void request(String account, String token) {
    HttpClient client = new DefaultHttpClient();
    HttpPost method = new HttpPost(getUrl());

    method.addHeader("Connection", "close");
    method.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    //        method.addHeader("User-Agent", Constants.USER_AGENT);
    method.addHeader("User-Agent", Constants.USER_AGENT_IPHONE);

    Map<String, String> params = getCommonParams(token);
    params.putAll(getParams());

    List<NameValuePair> body = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        body.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }

    InputStream inputStream = null;
    try {
        HttpEntity entity = new UrlEncodedFormEntity(body, Constants.DEFAULT_ENCODING);
        method.setEntity(entity);

        HttpResponse response = client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            StringBuilder output = new StringBuilder();
            output.append("?: ").append(account).append(",: ");
            inputStream = new InflaterInputStream(response.getEntity().getContent());
            byte[] data = new byte[1024];
            int len;
            while ((len = inputStream.read(data)) != -1) {
                output.append(new String(data, 0, len));
            }

            System.out.println(output.toString());
        } else {
            System.out.println("");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.github.etorres.codexposed.ArgValidator.java

/**
 * Example: set valid values to method parameters. Internally uses Java unmodifiable maps.
 * @param required - required parameter, empty map is not allowed
 * @param optional - optional parameter/*from  www . j av  a 2 s .  c  om*/
 * @return A new map combining both input parameters.
 * @throws NullPointerException When a required parameter has <code>null</code> value.
 * @throws IllegalArgumentException When a required parameter is empty.
 */
public Map<String, String> mapParams2(final Map<String, String> required,
        final @Nullable Map<String, String> optional) {
    final Map<String, String> required2 = unmodifiableMap(checkNotNull(required, "Uninitialized map"));
    checkArgument(!required2.isEmpty(), "Empty map is not allowed");
    final Map<String, String> optional2 = (optional != null ? unmodifiableMap(optional)
            : Collections.<String, String>emptyMap());
    // operate on the canonicalized version of the parameters
    final Map<String, String> response = new Hashtable<>(required2);
    response.putAll(optional2);
    return response;
}