Example usage for org.apache.commons.lang ArrayUtils toString

List of usage examples for org.apache.commons.lang ArrayUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils toString.

Prototype

public static String toString(Object array) 

Source Link

Document

Outputs an array as a String, treating null as an empty array.

Usage

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes
 * have to be checked before this method.
 * //from  w ww.j av a 2s  .  c om
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@Override
public Identity createAndPersistUser(Attributes userAttributes) {
    // Get and Check Config
    String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes);
    if (reqAttrs != null) {
        log.warn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return null;
    }

    String uid = getAttributeValue(userAttributes
            .get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    String email = getAttributeValue(
            userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        log.error("Can't create user with username='" + uid
                + "', this username does already exist in OLAT database", null);
        return null;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return null;
    }
    if (userManager.userExist(email)) {
        log.error("Can't create user with email='" + email
                + "', a user with that email does already exist in OLAT database", null);
        return null;
    }

    // Create User (first and lastname is added in next step)
    User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            Attribute attr = neAttr.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (!attr.getID().equalsIgnoreCase(
                    syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) {
                String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null)
                    continue;
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (NamingException e) {
        log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    } catch (Exception e) {
        // catch any exception here to properly log error
        log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    }

    // Create Identity
    Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    log.info("Created LDAP user username::" + uid);
    return identity;
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

private List<LDAPUser> doBatchSyncNewAndModifiedUsers(LdapContext ctx, String sinceSentence,
        Map<String, LDAPUser> dnToIdentityKeyMap, LDAPError errors) {
    // Get new and modified users from LDAP
    int count = 0;
    List<LDAPUser> ldapUserList = ldapDao.getUserAttributesModifiedSince(lastSyncDate, ctx);

    // Check for new and modified users
    List<LDAPUser> newLdapUserList = new ArrayList<LDAPUser>();
    Map<Identity, Map<String, String>> changedMapIdentityMap = new HashMap<Identity, Map<String, String>>();
    for (LDAPUser ldapUser : ldapUserList) {
        String user = null;/*  ww  w.j av  a 2  s  . c  om*/
        try {
            Attributes userAttrs = ldapUser.getAttributes();
            String uidProp = syncConfiguration
                    .getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
            user = getAttributeValue(userAttrs.get(uidProp));
            Identity identity = findIdentyByLdapAuthentication(user, errors);
            if (identity != null) {
                Map<String, String> changedAttrMap = prepareUserPropertyForSync(userAttrs, identity);
                if (changedAttrMap != null) {
                    changedMapIdentityMap.put(identity, changedAttrMap);
                }
                if (StringHelper.containsNonWhitespace(ldapUser.getDn())) {
                    dnToIdentityKeyMap.put(ldapUser.getDn(), ldapUser);
                    ldapUser.setCachedIdentity(identity);
                }
            } else if (errors.isEmpty()) {
                String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttrs);
                if (reqAttrs == null) {
                    newLdapUserList.add(ldapUser);
                } else {
                    log.warn("Error in LDAP batch sync: can't create user with username::" + user
                            + " : missing required attributes::" + ArrayUtils.toString(reqAttrs), null);
                }
            } else {
                log.warn(errors.get(), null);
            }

            if (++count % 20 == 0) {
                dbInstance.intermediateCommit();
            }
        } catch (Exception e) {
            // catch here to go on with other users on exeptions!
            log.error("some error occured in looping over set of changed user-attributes, actual user " + user
                    + ". Will still continue with others.", e);
        }
    }

    // sync existing users
    if (changedMapIdentityMap == null || changedMapIdentityMap.isEmpty()) {
        log.info("LDAP batch sync: no users to sync" + sinceSentence);
    } else {
        for (Identity ident : changedMapIdentityMap.keySet()) {
            // sync user is exception save, no try/catch needed
            syncUser(changedMapIdentityMap.get(ident), ident);
            //REVIEW Identity are not saved???
            if (++count % 20 == 0) {
                dbInstance.intermediateCommit();
            }
        }
        log.info("LDAP batch sync: " + changedMapIdentityMap.size() + " users synced" + sinceSentence);
    }

    // create new users
    if (newLdapUserList.isEmpty()) {
        log.info("LDAP batch sync: no users to create" + sinceSentence);
    } else {
        for (LDAPUser ldapUser : newLdapUserList) {
            Attributes userAttrs = ldapUser.getAttributes();
            try {
                Identity identity = createAndPersistUser(userAttrs);
                if (++count % 20 == 0) {
                    dbInstance.intermediateCommit();
                }

                if (StringHelper.containsNonWhitespace(ldapUser.getDn())) {
                    dnToIdentityKeyMap.put(ldapUser.getDn(), ldapUser);
                    ldapUser.setCachedIdentity(identity);
                }
            } catch (Exception e) {
                // catch here to go on with other users on exeptions!
                log.error("some error occured while creating new users, actual userAttribs " + userAttrs
                        + ". Will still continue with others.", e);
            }
        }
        log.info("LDAP batch sync: " + newLdapUserList.size() + " users created" + sinceSentence);
    }

    dbInstance.intermediateCommit();
    return ldapUserList;
}

From source file:org.openanzo.datasource.services.BaseQueryService.java

public org.openanzo.glitter.query.QueryResults query(IOperationContext context, Set<URI> defaultNamedGraphs,
        Set<URI> graphs, Set<URI> namedDatasets, String paramQuery, String queryString, URI baseUri)
        throws AnzoException {
    if (queryString == null || queryString.length() == 0)
        queryString = paramQuery; // TEMP fix until we drop support for
    // paramQuery in messages
    long start = 0;
    if (stats.isEnabled() || log.isDebugEnabled()) {
        start = System.currentTimeMillis();
    }//from w  ww.  j a v  a  2s  .c  o  m
    if (getLockProvider() != null)
        getLockProvider().readLock().lock();
    logEntry();
    if (log.isDebugEnabled()) {
        log.debug(LogUtils.DATASOURCE_MARKER, "Query:{} [{}] [{}] [{}]", new Object[] { queryString,
                defaultNamedGraphs != null ? ArrayUtils.toString(defaultNamedGraphs.toArray(new URI[0]))
                        : "null",
                graphs != null ? ArrayUtils.toString(graphs.toArray(new URI[0])) : "null",
                namedDatasets != null ? ArrayUtils.toString(namedDatasets.toArray(new URI[0])) : "null" });
    }
    try {
        QueryController prepareQuery = new Engine(new ParseOnlyEngineConfig()).prepareQuery(null, queryString,
                null, baseUri);
        QueryDataset uriSet = resolveAndVerifyGraphs(context, defaultNamedGraphs, graphs, namedDatasets,
                queryString, baseUri, prepareQuery);
        Boolean skipCache = context.getAttribute(OPTIONS.SKIPCACHE, Boolean.class);
        boolean skip = (skipCache != null && skipCache) || cache == null;
        skip |= (uriSet.allGraphs || uriSet.allMetadataGraphs || uriSet.allNamedGraphs
                || uriSet.defaultAllGraphs || uriSet.defaultAllMetadataGraphs || uriSet.defaultAllNamedGraphs);
        String cacheString = !skip ? queryString + uriSet.getCacheString() : null;

        org.openanzo.glitter.query.QueryResults queryResults = !skip ? cache.findResults(cacheString, uriSet)
                : null;
        if (queryResults == null) {
            if (stats.isEnabled()) {
                stats.getCacheMiss().increment();
            }
            queryResults = executeQueryInternal(context, uriSet, queryString, baseUri);
            if (!skip && cache != null) {
                cache.cacheResults(cacheString, queryResults, uriSet);
            }
            if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) {
                RequestAnalysis.addAnalysisProperty(RequestAnalysis.ANS_PROP_CACHE_HIT, Boolean.FALSE);
            }
        } else {
            if (stats.isEnabled()) {
                stats.getCacheHit().increment();
            }
            if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) {
                RequestAnalysis.addAnalysisProperty(RequestAnalysis.ANS_PROP_CACHE_HIT, Boolean.TRUE);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug(LogUtils.TIMING_MARKER, "Total Query Time:results,{},{},{}", new Object[] {
                    (System.currentTimeMillis() - start), queryResults.getTotalSolutions(), queryString });
        }
        return queryResults;
    } catch (ParseException pe) {
        throw new GlitterParseException(pe, queryString, pe.getMessage());
    } finally {
        if (stats.isEnabled()) {
            stats.use("query", (System.currentTimeMillis() - start));
        }

        if (getLockProvider() != null)
            getLockProvider().readLock().unlock();
        logExit();
    }
}

From source file:org.openengsb.core.services.GenericSecurePortTest.java

private static void logRequest(Object o) {
    if (o.getClass().isArray()) {
        LOGGER.info(ArrayUtils.toString(o));
    } else {//ww w  . j a v a2 s .c  o  m
        LOGGER.info(o.toString());
    }
}

From source file:org.openengsb.core.services.internal.RequestHandlerImpl.java

private Method findMethod(Object service, String methodName, Class<?>[] argTypes) {
    Method method;/*from  w ww  .j  a v a2 s.c  om*/

    Class<?> serviceClass = retrieveRealServiceClass(service);
    if (serviceClass.isInstance(CustomMarshallerRealTypeAccess.class)) {
        serviceClass = ((CustomMarshallerRealTypeAccess) service).getRealUnproxiedType();
    }
    method = MethodUtils.getMatchingAccessibleMethod(serviceClass, methodName, argTypes);
    if (method == null) {
        throw new IllegalArgumentException(String.format("could not find method matching arguments \"%s(%s)\"",
                methodName, ArrayUtils.toString(argTypes)));
    }

    return method;
}

From source file:org.openengsb.ui.admin.testClient.TestClient.java

protected void performCall() {
    Object service;//from www .ja  v a2  s  .  c  om
    try {
        service = getService(call.getService());
    } catch (OsgiServiceNotAvailableException e1) {
        handleExceptionWithFeedback(e1);
        return;
    }
    Method method;
    try {
        method = getMethodOfService(service, call.getMethod());
    } catch (NoSuchMethodException ex) {
        throw new IllegalArgumentException(ex);
    }
    if (method == null) {
        return;
    }

    try {
        Object result = method.invoke(service, call.getArgumentsAsArray());
        info("Methodcall called successfully");
        Class<?> returnType = method.getReturnType();
        if (returnType.equals(void.class)) {
            return;
        }
        String resultString;
        if (returnType.isArray()) {
            try {
                // to handle byte[] and char[]
                Constructor<String> constructor = String.class.getConstructor(returnType);
                resultString = constructor.newInstance(result);
            } catch (Exception e) {
                resultString = ArrayUtils.toString(result);
            }
        } else {
            resultString = result.toString();
        }
        info("Result " + returnType.getName() + ": " + resultString);
        LOGGER.info("result: {}", resultString);
    } catch (IllegalAccessException e) {
        handleExceptionWithFeedback(e);
    } catch (InvocationTargetException e) {
        handleExceptionWithFeedback(e.getCause());
    } catch (ArgumentConversionException e) {
        printArgumentConversionException(e);
    }
}

From source file:org.openengsb.ui.common.DomainAuthorizationStrategy.java

@Override
public boolean isActionAuthorized(Component arg0, Action arg1) {
    List<SecurityAttributeEntry> attributeList = Lists.newArrayList();
    if (hasSecurityAnnotation(arg0.getClass())) {
        attributeList.addAll(getSecurityAttributes(arg0.getClass()));
    }//from w ww  .j  a v  a 2  s.c  o  m

    LOGGER.info(ArrayUtils.toString(attributeProviders.getClass().getInterfaces()));

    for (SecurityAttributeProvider p : attributeProviders) {
        Collection<SecurityAttributeEntry> runtimeAttributes = p.getAttribute(arg0);
        if (runtimeAttributes != null) {
            attributeList.addAll(runtimeAttributes);
        }
    }

    if (attributeList.isEmpty()) {
        return true;
    }

    String user = getAuthenticatedUser();
    if (user == null) {
        return false;
    }
    UIAction secureAction = new UIAction(attributeList, arg1.getName(),
            ImmutableMap.of("component", (Object) arg0));

    Access checkAccess = authorizer.checkAccess(user, secureAction);
    if (checkAccess != Access.GRANTED) {
        LOGGER.warn("User {} was denied action {} on component {}",
                new Object[] { user, arg1.toString(), arg0.getClass().getName() });
    }
    return checkAccess == Access.GRANTED;
}

From source file:org.openiot.gsn.wrappers.sbox.SboxWrapper.java

public void run() {
    while (isActive()) {
        try {/*from  w w w  .j a va  2 s. c o m*/
            // delay
            Thread.sleep(samplingRate);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }

        // Retrieve data from server
        JSONArray state = sendCommand("state");
        if (state == null) {
            logger.error("Bad response from server");
        } else {
            Serializable[] dataPacket = new Serializable[fields.length];
            for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
                DataField fieldDefinition = this.fields[fieldIndex];
                JSONObject dataMatch = null;
                for (int dataIndex = 0; dataIndex < fields.length; dataIndex++) {
                    JSONObject fieldData = (JSONObject) state.get(dataIndex);
                    if (fieldDefinition.getName().equalsIgnoreCase((String) fieldData.get("name"))) {
                        dataMatch = fieldData;
                        break;
                    }
                }

                Object value = null;
                if (dataMatch != null) {
                    value = dataMatch.get("value");
                    if (fieldDefinition.getDataTypeID() == DataTypes.BIGINT) {
                        value = Long.valueOf(value.toString());
                    } else if (fieldDefinition.getDataTypeID() == DataTypes.DOUBLE) {
                        value = Double.valueOf(value.toString());
                    } else if (fieldDefinition.getDataTypeID() == DataTypes.INTEGER) {
                        value = Integer.valueOf(value.toString());
                    } else if (fieldDefinition.getDataTypeID() == DataTypes.SMALLINT) {
                        value = Short.valueOf(value.toString());
                    } else if (fieldDefinition.getDataTypeID() == DataTypes.TINYINT) {
                        value = Byte.valueOf(value.toString());
                    } else if (fieldDefinition.getDataTypeID() == DataTypes.VARCHAR) {
                        value = value.toString();
                    }
                }

                dataPacket[fieldIndex] = (Serializable) value;
            }

            logger.debug(
                    "Sending new data packet for sensor " + sensorUID + ": " + ArrayUtils.toString(dataPacket));

            // post the data to GSN
            postStreamElement(dataPacket);
        }
    }
}

From source file:org.openlegacy.terminal.support.binders.ScreenEntityTablesBinder.java

@Override
public void populateEntity(Object screenEntity, TerminalSnapshot terminalSnapshot) {

    ScreenPojoFieldAccessor fieldAccessor = new SimpleScreenPojoFieldAccessor(screenEntity);

    Map<String, ScreenTableDefinition> tableDefinitions = tablesDefinitionProvider
            .getTableDefinitions(screenEntity.getClass());

    Set<String> tableFieldNames = tableDefinitions.keySet();

    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("Found {0} tables to bind to entity {1}: {2}", tableFieldNames.size(),
                screenEntity.getClass().getName(), ArrayUtils.toString(tableFieldNames.toArray())));
    }//from   w ww  .  j a  v  a  2  s . com

    for (String tableFieldName : tableFieldNames) {

        ScreenTableDefinition tableDefinition = tableDefinitions.get(tableFieldName);
        List<Object> rows = new ArrayList<Object>();

        List<ScreenColumnDefinition> columnDefinitions = tableDefinition.getColumnDefinitions();
        int startRow = tableDefinition.getStartRow();
        int endRow = tableDefinition.getEndRow();
        for (int currentRow = startRow; currentRow <= endRow; currentRow += tableDefinition.getRowGaps()) {

            Object row = ReflectionUtil.newInstance(tableDefinition.getTableClass());
            ScreenPojoFieldAccessor rowAccessor = new SimpleScreenPojoFieldAccessor(row);

            // 3 states boolean - null - no keys found
            Boolean allKeysAreEmpty = null;

            for (ScreenColumnDefinition columnDefinition : columnDefinitions) {
                final TerminalPosition position = SimpleTerminalPosition.newInstance(
                        currentRow + columnDefinition.getRowsOffset(), columnDefinition.getStartColumn());
                final TerminalField terminalField = terminalSnapshot.getField(position);
                if (columnDefinition.getAttribute() == FieldAttributeType.Value) {
                    if (terminalField != null && terminalField.isHidden()) {
                        continue;
                    }
                    final String cellText = getCellContent(terminalSnapshot, position, columnDefinition);
                    if (columnDefinition.isKey()) {
                        if (cellText.length() == 0) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(MessageFormat.format(
                                        "Key field {0} is empty in row {1}. Aborting table rows collecting",
                                        columnDefinition.getName(), position.getRow()));
                            }
                            allKeysAreEmpty = true;
                        } else {
                            allKeysAreEmpty = false;
                        }
                    }
                    final String expression = columnDefinition.getExpression();
                    if (!StringUtil.isEmpty(expression)) {
                        if (ExpressionUtils.isRegularExpression(expression)) {
                            final Object value = ExpressionUtils.applyRegularExpression(expression.trim(),
                                    cellText);
                            rowAccessor.setFieldValue(columnDefinition.getName(), value);
                        } else {
                            final Expression expr = expressionParser.parseExpression(expression);
                            final Map<String, Object> expressionVars = new HashMap<String, Object>();
                            expressionVars.put("row", row);
                            expressionVars.put("field", terminalField);
                            expressionVars.put("entity", screenEntity);
                            expressionVars.put("cellText", cellText);
                            final EvaluationContext evaluationContext = ExpressionUtils
                                    .createEvaluationContext(row, expressionVars);
                            final Object value = expr.getValue(evaluationContext,
                                    columnDefinition.getJavaType());
                            rowAccessor.setFieldValue(columnDefinition.getName(), value);
                        }
                    } else {
                        rowAccessor.setFieldValue(columnDefinition.getName(), cellText);
                    }
                    rowAccessor.setTerminalField(columnDefinition.getName(), terminalField);
                } else {
                    if (terminalField == null) {
                        logger.warn(MessageFormat.format("Unable to find field in position {0} for table:{1}",
                                position, tableDefinition.getTableEntityName()));
                        break;
                    }

                    if (columnDefinition.getAttribute() == FieldAttributeType.Editable) {
                        rowAccessor.setFieldValue(columnDefinition.getName(), terminalField.isEditable());
                    } else if (columnDefinition.getAttribute() == FieldAttributeType.Color) {
                        rowAccessor.setFieldValue(columnDefinition.getName(), terminalField.getColor());
                    }
                }
            }
            boolean filter = false;
            if (allKeysAreEmpty == null || allKeysAreEmpty == false) {
                if (tableDefinition.getStopExpression() != null) {
                    final Map<String, Object> expressionVars = new HashMap<String, Object>();
                    expressionVars.put("row", row);
                    expressionVars.put("text", terminalSnapshot.getRow(currentRow).getText());
                    final EvaluationContext evaluationContext = ExpressionUtils.createEvaluationContext(row,
                            expressionVars);
                    Expression expr = expressionParser.parseExpression(tableDefinition.getStopExpression());
                    Boolean stop = expr.getValue(evaluationContext, Boolean.class);
                    if (stop) {
                        break;
                    }
                }
                if (tableDefinition.getFilterExpression() != null) {
                    StandardEvaluationContext evaluationContext = new StandardEvaluationContext(row);
                    Expression expr = expressionParser.parseExpression(tableDefinition.getFilterExpression());
                    filter = expr.getValue(evaluationContext, Boolean.class);
                }
                if (!filter) {
                    rows.add(row);
                }
            }
        }
        fieldAccessor.setFieldValue(tableFieldName, rows);
    }
}

From source file:org.openlegacy.terminal.support.DefaultTerminalSession.java

@Override
@SuppressWarnings("unchecked")
public synchronized <S> S getEntity(Class<S> screenEntityClass, Object... keys) throws EntityNotFoundException {

    authorize(screenEntityClass);//from  w w  w . j  a  v a  2s  .co  m

    if (keys.length == 1 && keys[0] == null) {
        keys = new Object[0];
    }

    checkRegistryDirty();

    ScreenEntityDefinition definitions = getScreenEntitiesRegistry().get(screenEntityClass);

    if (keys.length > definitions.getKeys().size()) {
        throw (new EntityNotAccessibleException(MessageFormat.format(
                "Requested entity {0} with keys {1} doesnt matches the defined entity keys count: {2}. Verify key is defined for {3}",
                screenEntityClass, ArrayUtils.toString(keys), definitions.getKeys().size(),
                screenEntityClass.getName())));
    }
    sessionNavigator.navigate(this, screenEntityClass, keys);
    return (S) getEntity();
}