Example usage for java.util HashMap putAll

List of usage examples for java.util HashMap putAll

Introduction

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

Prototype

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

Source Link

Document

Copies all of the mappings from the specified map to this map.

Usage

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

/**
 * Write checkpoint into the database//from  w  w w . ja  v a 2 s .c  om
 * @param db
 * @param tableId
 * @param orderedColumns
 * @param cvValues
 * @param activeUser
 * @param rolesList
 * @param locale
 * @param isNewRow
 * @param priorGroupReadOnly
 * @param priorGroupModify
 * @param priorGroupPrivileged
 */
private void insertCheckpointIntoExistingTable(OdkConnectionInterface db, String tableId,
        OrderedColumns orderedColumns, HashMap<String, Object> cvValues, String activeUser, String rolesList,
        String locale, boolean isNewRow, String priorDefaultAccess, String priorOwner,
        String priorGroupReadOnly, String priorGroupModify, String priorGroupPrivileged)
        throws ActionNotAuthorizedException {

    String rowId = null;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {

        rowId = (String) cvDataTableVal.get(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }
    } else {
        throw new IllegalArgumentException(
                t + ": rowId should not be null in insertCheckpointIntoExistingTable in the ContentValues");
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
            || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
        cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
        cvDataTableVal.put(DataTableColumns.CONFLICT_TYPE, null);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
        cvDataTableVal.put(DataTableColumns.FORM_ID, null);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
            || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
        cvDataTableVal.put(DataTableColumns.LOCALE, locale);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
            || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
        cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, null);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
            || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
        String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
        cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
    }

    if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
            || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
        cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, activeUser);
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransactionNonExclusive();
        }

        List<String> rolesArray = getRolesArray(rolesList);

        // get the security settings
        TableSecuritySettings tss = getTableSecuritySettings(db, tableId);

        if (isNewRow) {

            // ensure that filter type and value are defined. Use defaults if not.

            if (!cvDataTableVal.containsKey(DataTableColumns.DEFAULT_ACCESS)
                    || (cvDataTableVal.get(DataTableColumns.DEFAULT_ACCESS) == null)) {
                cvDataTableVal.put(DataTableColumns.DEFAULT_ACCESS, tss.defaultAccessOnCreation);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.ROW_OWNER)) {
                cvDataTableVal.put(DataTableColumns.ROW_OWNER, activeUser);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_READ_ONLY)
                    || (cvDataTableVal.get(DataTableColumns.GROUP_READ_ONLY) == null)) {
                cvDataTableVal.put(DataTableColumns.GROUP_READ_ONLY, null);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_MODIFY)
                    || cvDataTableVal.get(DataTableColumns.GROUP_MODIFY) == null) {
                cvDataTableVal.put(DataTableColumns.GROUP_MODIFY, null);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_PRIVILEGED)
                    || cvDataTableVal.get(DataTableColumns.GROUP_PRIVILEGED) == null) {
                cvDataTableVal.put(DataTableColumns.GROUP_PRIVILEGED, null);
            }

            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());

            tss.allowRowChange(activeUser, rolesArray, SyncState.new_row.name(), priorDefaultAccess, priorOwner,
                    priorGroupReadOnly, priorGroupModify, priorGroupPrivileged, RowChange.NEW_ROW);

        } else {

            // don't allow changes to default access or owner or syncState when inserting checkpoints
            cvDataTableVal.put(DataTableColumns.DEFAULT_ACCESS, priorDefaultAccess);

            cvDataTableVal.put(DataTableColumns.ROW_OWNER, priorOwner);

            cvDataTableVal.put(DataTableColumns.GROUP_READ_ONLY, priorGroupReadOnly);

            cvDataTableVal.put(DataTableColumns.GROUP_MODIFY, priorGroupModify);

            cvDataTableVal.put(DataTableColumns.GROUP_PRIVILEGED, priorGroupPrivileged);

            // for this call path, syncState is already updated by caller

            tss.allowRowChange(activeUser, rolesArray, (String) cvDataTableVal.get(DataTableColumns.SYNC_STATE),
                    priorDefaultAccess, priorOwner, priorGroupReadOnly, priorGroupModify, priorGroupPrivileged,
                    RowChange.CHANGE_ROW);
        }

        db.insertOrThrow(tableId, null, cvDataTableVal);

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }

}

From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java

@Override
public Iterable<VirtualMachineProduct> listProducts(Architecture architecture)
        throws InternalException, CloudException {
    if (products == null) {
        ProviderContext ctx = provider.getContext();

        if (ctx == null) {
            throw new SCEConfigException("No context was configured for this request");
        }//from www.j a  v a2 s . c o  m
        SCEMethod method = new SCEMethod(provider);

        Document xml = method.getAsXML("offerings/image");

        if (xml == null) {
            return Collections.emptyList();
        }
        HashMap<String, VirtualMachineProduct> t = new HashMap<String, VirtualMachineProduct>();
        HashMap<String, VirtualMachineProduct> s = new HashMap<String, VirtualMachineProduct>();
        NodeList items = xml.getElementsByTagName("Image");

        for (int i = 0; i < items.getLength(); i++) {
            HashMap<String, VirtualMachineProduct> prdMap = new HashMap<String, VirtualMachineProduct>();
            NodeList attrs = items.item(i).getChildNodes();
            Architecture a = null;

            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);

                if (attr.getNodeName().equalsIgnoreCase("Architecture") && attr.hasChildNodes()) {
                    String val = attr.getFirstChild().getNodeValue().trim();

                    if (val.equals("i386")) {
                        a = Architecture.I32;
                    } else if (val.startsWith("x86")) {
                        a = Architecture.I64;
                    } else {
                        System.out.println("DEBUG: Unknown architecture: " + val);
                        a = Architecture.I32;
                    }
                } else if (attr.getNodeName().equalsIgnoreCase("SupportedInstanceTypes")
                        && attr.hasChildNodes()) {
                    NodeList types = attr.getChildNodes();

                    for (int k = 0; k < types.getLength(); k++) {
                        Node type = types.item(k);

                        if (type.getNodeName().equalsIgnoreCase("InstanceType") && type.hasChildNodes()) {
                            VirtualMachineProduct prd = new VirtualMachineProduct();
                            NodeList nodes = type.getChildNodes();

                            for (int l = 0; l < nodes.getLength(); l++) {
                                Node node = nodes.item(l);

                                if (node.getNodeName().equals("ID") && node.hasChildNodes()) {
                                    prd.setProviderProductId(node.getFirstChild().getNodeValue().trim());
                                } else if (node.getNodeName().equals("Label") && node.hasChildNodes()) {
                                    prd.setName(node.getFirstChild().getNodeValue().trim());
                                } else if (node.getNodeName().equals("Detail") && node.hasChildNodes()) {
                                    prd.setDescription(node.getFirstChild().getNodeValue().trim());
                                }
                            }
                            if (prd.getProviderProductId() != null) {
                                String[] parts = prd.getProviderProductId().split("/");

                                if (parts.length == 3) {
                                    String[] sub = parts[0].split("\\.");

                                    if (sub.length > 0) {
                                        parts[0] = sub[sub.length - 1];
                                    }
                                    try {
                                        prd.setCpuCount(Integer.parseInt(parts[0]));
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                    try {
                                        prd.setRamSize(new Storage<Megabyte>(Integer.parseInt(parts[1]),
                                                Storage.MEGABYTE));
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                    try {
                                        int idx = parts[2].indexOf("*");

                                        if (idx < 1) {
                                            prd.setRootVolumeSize(new Storage<Gigabyte>(
                                                    Integer.parseInt(parts[2]), Storage.GIGABYTE));
                                        } else {
                                            prd.setRootVolumeSize(new Storage<Gigabyte>(
                                                    Integer.parseInt(parts[2].substring(0, idx)),
                                                    Storage.GIGABYTE));
                                        }
                                    } catch (NumberFormatException ignore) {
                                        // ignore
                                    }
                                }
                                prdMap.put(prd.getProviderProductId(), prd);
                            }
                        }
                    }
                }
            }
            if (a != null) {
                if (a.equals(Architecture.I32)) {
                    t.putAll(prdMap);
                } else if (a.equals(Architecture.I64)) {
                    s.putAll(prdMap);
                }
            }
        }
        HashMap<Architecture, Collection<VirtualMachineProduct>> tmp = new HashMap<Architecture, Collection<VirtualMachineProduct>>();

        tmp.put(Architecture.I32, Collections.unmodifiableCollection(t.values()));
        tmp.put(Architecture.I64, Collections.unmodifiableCollection(s.values()));
        products = tmp;
    }
    return products.get(architecture);
}

From source file:org.opendatakit.services.database.utilities.ODKDatabaseImplUtils.java

private void upsertDataIntoExistingTable(OdkConnectionInterface db, String tableId,
        OrderedColumns orderedColumns, Map<String, Object> cvValues, boolean shouldUpdate,
        boolean asServerRequestedChange, String activeUser, String rolesList, String locale,
        boolean asCsvRequestedChange) throws ActionNotAuthorizedException {

    String rowId = null;//from ww w  . j  a v a2 s  .co m
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    Object[] whereArgs = new Object[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;
    String updatedSyncState = SyncState.new_row.name();
    String priorDefaultAccess = DataTableColumns.DEFAULT_DEFAULT_ACCESS;
    String priorOwner = DataTableColumns.DEFAULT_ROW_OWNER;
    String priorGroupReadOnly = DataTableColumns.DEFAULT_GROUP_READ_ONLY;
    String priorGroupModify = DataTableColumns.DEFAULT_GROUP_MODDIFY;
    String priorGroupPrivileged = DataTableColumns.DEFAULT_GROUP_PRIVILEGED;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>();
    cvDataTableVal.putAll(cvValues);

    // if this is a server-requested change, all the user fields and admin columns should be specified.
    if (asServerRequestedChange && !asCsvRequestedChange) {
        for (String columnName : orderedColumns.getRetentionColumnNames()) {
            if (!cvDataTableVal.containsKey(columnName)) {
                throw new IllegalArgumentException(t + ": Not all user field values are set during server "
                        + (shouldUpdate ? "update" : "insert") + " in table " + tableId + " missing: "
                        + columnName);
            }
        }
        for (String columnName : ADMIN_COLUMNS) {
            if (!cvDataTableVal.containsKey(columnName)) {
                throw new IllegalArgumentException(t + ": Not all metadata field values are set during server "
                        + (shouldUpdate ? "update" : "insert") + " in table " + tableId + " missing: "
                        + columnName);
            }
        }
    }

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransactionNonExclusive();
        }

        if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
            // The user specified a row id; we need to determine whether to
            // insert or update the record, or to reject the action because
            // there are either checkpoint records for this row id, or, if
            // a server conflict is associated with this row, that the
            // _conflict_type to update was not specified.
            //
            // i.e., the tuple (_id, _conflict_type) should be unique. If
            // we find that there are more than 0 or 1 records matching this
            // tuple, then we should reject the update request.
            //
            // TODO: perhaps we want to allow updates to the local conflict
            // row if there are no checkpoints on it? I.e., change the
            // tri-state conflict type to a pair of states (local / remote).
            // and all local changes are flagged local. Remote only exists
            // if the server is in conflict.

            rowId = (String) cvDataTableVal.get(DataTableColumns.ID);
            if (rowId == null) {
                throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
            }

            if (specifiesConflictType) {
                if (nullConflictType) {
                    whereClause = K_DATATABLE_ID_EQUALS_PARAM + S_AND + DataTableColumns.CONFLICT_TYPE
                            + S_IS_NULL;
                    whereArgs[0] = rowId;
                } else {
                    whereClause = K_DATATABLE_ID_EQUALS_PARAM + S_AND + DataTableColumns.CONFLICT_TYPE
                            + S_EQUALS_PARAM;
                    whereArgs[0] = rowId;
                    whereArgs[1] = cvValues.get(DataTableColumns.CONFLICT_TYPE);
                }
            } else {
                whereClause = K_DATATABLE_ID_EQUALS_PARAM;
                whereArgs[0] = rowId;
            }

            AccessContext accessContext = getAccessContext(db, tableId, activeUser,
                    RoleConsts.ADMIN_ROLES_LIST);

            StringBuilder b = new StringBuilder();
            b.append(K_SELECT_FROM).append(tableId).append(K_WHERE).append(whereClause);
            BaseTable data = privilegedQuery(db, tableId, b.toString(), whereArgs, null, accessContext);

            // There must be only one row in the db for the update to work
            if (shouldUpdate) {
                if (data.getNumberOfRows() == 1) {
                    int defaultAccessCursorIndex = data
                            .getColumnIndexOfElementKey(DataTableColumns.DEFAULT_ACCESS);
                    priorDefaultAccess = data.getRowAtIndex(0).getDataByIndex(defaultAccessCursorIndex);
                    if (priorDefaultAccess == null) {
                        priorDefaultAccess = DataTableColumns.DEFAULT_DEFAULT_ACCESS;
                    }
                    int ownerCursorIndex = data.getColumnIndexOfElementKey(DataTableColumns.ROW_OWNER);
                    priorOwner = data.getRowAtIndex(0).getDataByIndex(ownerCursorIndex);
                    int groupReadOnlyCursorIndex = data
                            .getColumnIndexOfElementKey(DataTableColumns.GROUP_READ_ONLY);
                    priorGroupReadOnly = data.getRowAtIndex(0).getDataByIndex(groupReadOnlyCursorIndex);
                    int groupModifyCursorIndex = data.getColumnIndexOfElementKey(DataTableColumns.GROUP_MODIFY);
                    priorGroupModify = data.getRowAtIndex(0).getDataByIndex(groupModifyCursorIndex);
                    int groupPrivilegedCursorIndex = data
                            .getColumnIndexOfElementKey(DataTableColumns.GROUP_PRIVILEGED);
                    priorGroupPrivileged = data.getRowAtIndex(0).getDataByIndex(groupPrivilegedCursorIndex);

                    int syncStateCursorIndex = data.getColumnIndexOfElementKey(DataTableColumns.SYNC_STATE);
                    updatedSyncState = data.getRowAtIndex(0).getDataByIndex(syncStateCursorIndex);

                    // allow updates to in_conflict rows if they are initiated through privileged
                    // code paths (e.g., enforcePermissionsDuringConflictProcessing )
                    if (updatedSyncState.equals(SyncState.deleted.name()) || (!asServerRequestedChange
                            && updatedSyncState.equals(SyncState.in_conflict.name()))) {
                        throw new IllegalStateException(t + ": Cannot update a deleted or in-conflict row");
                    } else if (updatedSyncState.equals(SyncState.synced.name())
                            || updatedSyncState.equals(SyncState.synced_pending_files.name())) {
                        updatedSyncState = SyncState.changed.name();
                    }
                    update = true;
                } else if (data.getNumberOfRows() > 1) {
                    throw new IllegalArgumentException(
                            t + ": row id " + rowId + " has more than 1 row in table " + tableId);
                }
            } else {
                if (data.getNumberOfRows() > 0) {
                    throw new IllegalArgumentException(
                            t + ": row id " + rowId + " is already present in table " + tableId);
                }
            }

        } else {
            rowId = "uuid:" + UUID.randomUUID().toString();
        }

        // TODO: This is broken w.r.t. updates of partial fields
        // TODO: This is broken w.r.t. updates of partial fields
        // TODO: This is broken w.r.t. updates of partial fields
        // TODO: This is broken w.r.t. updates of partial fields

        if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
            cvDataTableVal.put(DataTableColumns.ID, rowId);
        }

        List<String> rolesArray = getRolesArray(rolesList);

        // get the security settings
        TableSecuritySettings tss = getTableSecuritySettings(db, tableId);

        if (!asServerRequestedChange) {
            // do not allow _default_access, _row_owner, _sync_state, _group_privileged
            // _group_modify, _group_read_only to be modified in normal workflow
            if (cvDataTableVal.containsKey(DataTableColumns.DEFAULT_ACCESS)
                    || cvDataTableVal.containsKey(DataTableColumns.ROW_OWNER)
                    || cvDataTableVal.containsKey(DataTableColumns.GROUP_PRIVILEGED)
                    || cvDataTableVal.containsKey(DataTableColumns.GROUP_MODIFY)
                    || cvDataTableVal.containsKey(DataTableColumns.GROUP_READ_ONLY)) {
                tss.canModifyPermissions(activeUser, rolesArray, priorGroupPrivileged, priorOwner);
            }
        }

        if (update) {

            // MODIFYING

            if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                    || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
                cvDataTableVal.put(DataTableColumns.SYNC_STATE, updatedSyncState);
            }

            if (!asServerRequestedChange) {

                // apply row access restrictions
                // this will throw an IllegalArgumentException
                tss.allowRowChange(activeUser, rolesArray, updatedSyncState, priorDefaultAccess, priorOwner,
                        priorGroupReadOnly, priorGroupModify, priorGroupPrivileged, RowChange.CHANGE_ROW);

            }

            if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                    && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
                cvDataTableVal.put(DataTableColumns.LOCALE, locale);
            }

            if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                    && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                    || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
                String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                    || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, activeUser);
            }
        } else {

            // INSERTING

            if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                    || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
                cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                    || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
                cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
                cvDataTableVal.put(DataTableColumns.CONFLICT_TYPE, null);
            }

            if (!asServerRequestedChange) {

                if (!cvDataTableVal.containsKey(DataTableColumns.DEFAULT_ACCESS)
                        || cvDataTableVal.get(DataTableColumns.DEFAULT_ACCESS) == null) {
                    cvDataTableVal.put(DataTableColumns.DEFAULT_ACCESS, tss.defaultAccessOnCreation);
                }

                // activeUser
                if (!cvDataTableVal.containsKey(DataTableColumns.ROW_OWNER)
                        || cvDataTableVal.get(DataTableColumns.ROW_OWNER) == null) {
                    cvDataTableVal.put(DataTableColumns.ROW_OWNER, activeUser);
                }

                tss.allowRowChange(activeUser, rolesArray, updatedSyncState, priorDefaultAccess, priorOwner,
                        priorGroupReadOnly, priorGroupModify, priorGroupPrivileged, RowChange.NEW_ROW);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
                cvDataTableVal.put(DataTableColumns.FORM_ID, null);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                    || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
                cvDataTableVal.put(DataTableColumns.LOCALE, locale);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                    || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                    || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
                String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                    || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
                cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, activeUser);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_READ_ONLY)
                    || (cvDataTableVal.get(DataTableColumns.GROUP_READ_ONLY) == null)) {
                cvDataTableVal.put(DataTableColumns.GROUP_READ_ONLY, null);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_MODIFY)
                    || (cvDataTableVal.get(DataTableColumns.GROUP_MODIFY) == null)) {
                cvDataTableVal.put(DataTableColumns.GROUP_MODIFY, null);
            }

            if (!cvDataTableVal.containsKey(DataTableColumns.GROUP_PRIVILEGED)
                    || (cvDataTableVal.get(DataTableColumns.GROUP_PRIVILEGED) == null)) {
                cvDataTableVal.put(DataTableColumns.GROUP_PRIVILEGED, null);
            }
        }

        cleanUpValuesMap(orderedColumns, cvDataTableVal);

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:net.spfbl.http.ServerHTTP.java

public synchronized HashMap<String, String> getMap() {
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(MAP);
    return map;// ww w.  j  a va 2 s  . c  om
}

From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java

protected HashMap<String, String> prepareScoreItemdata(HttpServletRequest request) {
    HashMap<String, String> scoreItemdata = new HashMap<String, String>();
    EventCRFBean ecb = (EventCRFBean) request.getAttribute(INPUT_EVENT_CRF);
    SectionDAO sdao = new SectionDAO(getDataSource());
    ArrayList<SectionBean> sbs = sdao.findAllByCRFVersionId(ecb.getCRFVersionId());
    for (SectionBean section : sbs) {
        HashMap<String, String> data = prepareSectionItemDataBeans(section.getId(), request);
        if (data != null && data.size() > 0) {
            scoreItemdata.putAll(data);
        }//from  w w  w  .ja v a  2s. c om
    }
    return scoreItemdata;
}

From source file:net.spfbl.http.ServerHTTP.java

public synchronized void load() {
    long time = System.currentTimeMillis();
    File file = new File("./data/url.map");
    if (file.exists()) {
        try {//from w ww  . j a va 2  s  . c  o m
            HashMap<String, String> map;
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                map = SerializationUtils.deserialize(fileInputStream);
            } finally {
                fileInputStream.close();
            }
            MAP.putAll(map);
            Server.logLoad(time, file);
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
}

From source file:org.bonitasoft.engine.api.impl.ProcessAPIImpl.java

protected Map<String, Serializable> executeOperations(final ConnectorResult connectorResult,
        final List<Operation> operations, final Map<String, Serializable> operationInputValues,
        final SExpressionContext expressionContext, final ClassLoader classLoader,
        final TenantServiceAccessor tenantAccessor) throws SBonitaException {
    final ConnectorService connectorService = tenantAccessor.getConnectorService();
    final OperationService operationService = tenantAccessor.getOperationService();
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {//from www.jav  a  2 s. co  m
        Thread.currentThread().setContextClassLoader(classLoader);
        final Map<String, Serializable> externalDataValue = new HashMap<String, Serializable>(
                operations.size());
        // convert the client operation to server operation
        final List<SOperation> sOperations = convertOperations(operations);
        // set input values of expression with connector result + provided input for this operation
        final HashMap<String, Object> inputValues = new HashMap<String, Object>(operationInputValues);
        inputValues.putAll(connectorResult.getResult());
        expressionContext.setInputValues(inputValues);
        // execute
        final Long containerId = expressionContext.getContainerId();
        operationService.execute(sOperations, containerId == null ? -1 : containerId,
                expressionContext.getContainerType(), expressionContext);
        // return the value of the data if it's an external data
        for (final Operation operation : operations) {
            final LeftOperand leftOperand = operation.getLeftOperand();
            if (LeftOperand.TYPE_EXTERNAL_DATA.equals(leftOperand.getType())) {
                externalDataValue.put(leftOperand.getName(),
                        (Serializable) expressionContext.getInputValues().get(leftOperand.getName()));
            }
        }
        // we finally disconnect the connector
        connectorService.disconnect(connectorResult);
        return externalDataValue;
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java

protected HashMap<String, Pair<String, State>> deltaClusterSync(Connection conn) {
    final HashMap<String, Pair<String, State>> changes = new HashMap<String, Pair<String, State>>();

    synchronized (_cluster.intern()) {
        HashMap<String, Pair<String, State>> newStates = getAllVms(conn);
        if (newStates == null) {
            s_logger.warn("Unable to get the vm states so no state sync at this point.");
            return null;
        }//from ww  w .ja va 2s .  c  o m
        HashMap<String, Pair<String, State>> oldStates = new HashMap<String, Pair<String, State>>(
                s_vms.size(_cluster));
        oldStates.putAll(s_vms.getClusterVmState(_cluster));

        for (final Map.Entry<String, Pair<String, State>> entry : newStates.entrySet()) {
            final String vm = entry.getKey();

            State newState = entry.getValue().second();
            String host_uuid = entry.getValue().first();
            final Pair<String, State> oldState = oldStates.remove(vm);

            //check if host is changed
            if (host_uuid != null && oldState != null) {
                if (!host_uuid.equals(oldState.first()) && newState != State.Stopped
                        && newState != State.Stopping) {
                    s_logger.warn("Detecting a change in host for " + vm);
                    changes.put(vm, new Pair<String, State>(host_uuid, newState));

                    s_logger.debug("11. The VM " + vm + " is in " + newState + " state");
                    s_vms.put(_cluster, host_uuid, vm, newState);
                    continue;
                }
            }

            if (newState == State.Stopped && oldState != null && oldState.second() != State.Stopping
                    && oldState.second() != State.Stopped) {
                newState = getRealPowerState(conn, vm);
            }

            if (s_logger.isTraceEnabled()) {
                s_logger.trace("VM " + vm + ": xen has state " + newState + " and we have state "
                        + (oldState != null ? oldState.toString() : "null"));
            }

            if (vm.startsWith("migrating")) {
                s_logger.warn("Migrating from xen detected.  Skipping");
                continue;
            }
            if (oldState == null) {
                s_vms.put(_cluster, host_uuid, vm, newState);
                s_logger.warn(
                        "Detecting a new state but couldn't find a old state so adding it to the changes: "
                                + vm);
                changes.put(vm, new Pair<String, State>(host_uuid, newState));
            } else if (oldState.second() == State.Starting) {
                if (newState == State.Running) {
                    s_logger.debug("12. The VM " + vm + " is in " + State.Running + " state");
                    s_vms.put(_cluster, host_uuid, vm, newState);
                } else if (newState == State.Stopped) {
                    s_logger.warn("Ignoring vm " + vm + " because of a lag in starting the vm.");
                }
            } else if (oldState.second() == State.Migrating) {
                if (newState == State.Running) {
                    s_logger.debug("Detected that an migrating VM is now running: " + vm);
                    s_vms.put(_cluster, host_uuid, vm, newState);
                }
            } else if (oldState.second() == State.Stopping) {
                if (newState == State.Stopped) {
                    s_logger.debug("13. The VM " + vm + " is in " + State.Stopped + " state");
                    s_vms.put(_cluster, host_uuid, vm, newState);
                } else if (newState == State.Running) {
                    s_logger.warn("Ignoring vm " + vm + " because of a lag in stopping the vm. ");
                }
            } else if (oldState.second() != newState) {
                s_logger.debug("14. The VM " + vm + " is in " + newState + " state was " + oldState.second());
                s_vms.put(_cluster, host_uuid, vm, newState);
                if (newState == State.Stopped) {
                    /*
                     * if (s_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. ");
                     * newState = State.Error; }
                     */
                }
                changes.put(vm, new Pair<String, State>(host_uuid, newState));
            }
        }

        for (final Map.Entry<String, Pair<String, State>> entry : oldStates.entrySet()) {
            final String vm = entry.getKey();
            final State oldState = entry.getValue().second();
            String host_uuid = entry.getValue().first();

            if (s_logger.isTraceEnabled()) {
                s_logger.trace("VM " + vm + " is now missing from xen so reporting stopped");
            }

            if (oldState == State.Stopping) {
                s_logger.warn("Ignoring VM " + vm + " in transition state stopping.");
                s_vms.remove(_cluster, host_uuid, vm);
            } else if (oldState == State.Starting) {
                s_logger.warn("Ignoring VM " + vm + " in transition state starting.");
            } else if (oldState == State.Stopped) {
                s_logger.debug("VM missing " + vm + " old state stopped so removing.");
                s_vms.remove(_cluster, host_uuid, vm);
            } else if (oldState == State.Migrating) {
                s_logger.warn("Ignoring VM " + vm + " in migrating state.");
            } else {
                State newState = State.Stopped;
                s_logger.warn("The VM is now missing marking it as Stopped " + vm);
                changes.put(vm, new Pair<String, State>(host_uuid, newState));
            }
        }
    }
    return changes;
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public WGDatabase retrievePersonalisationDB(Domain domainConfig) throws WGAServerException {
    PersonalisationDatabase config = domainConfig.getPersonalisation();

    // Get basic information
    String strType = config.getImplClassName();

    // Look if impl class is reachable
    Class<WGDatabaseCore> typeClass;
    try {//www . jav a 2  s  .  c  o  m
        Class theClass = Class.forName(strType, true, WGFactory.getImplementationLoader());
        if (!WGDatabaseCore.class.isAssignableFrom(theClass)) {
            throw new WGAServerException("Cannot connect personalisation database for domain \""
                    + domainConfig.toString() + "\" - Database implementation class \"" + strType
                    + "\" is no WGDatabaseCore implementation.");
        }
        typeClass = theClass;
    } catch (ClassNotFoundException e) {
        throw new WGAServerException(
                "Cannot attach personalisation database to domain \"" + domainConfig.toString()
                        + "\" - Database implementation class \"" + strType + "\" not available.");
    } catch (NoClassDefFoundError e) {
        throw new WGAServerException("Cannot attach personalisation database to domain \""
                + domainConfig.toString() + "\" - Database implementation class or dependent class for type \""
                + strType + "\" not found: \"" + e.getMessage());
    } catch (VerifyError e) {
        log.error("Cannot attach personalisation database to domain \"" + domainConfig.toString()
                + "\" - Verify error: " + e.getMessage());
        return null;
    }

    // Retrieve server
    WGDatabaseServer server = getDatabaseServers().get(config.getDbServer());
    if (server == null) {
        throw Problem.create(new UpdateConfigOccasion(), new DomainScope(domainConfig.getName()),
                "updateConfigProblem.domainPersServerUnknown", ProblemSeverity.HIGH,
                Problem.var("serverid", config.getDbServer()));
    }

    // Merge db options from global, server, database
    HashMap<String, String> dbOptions = new HashMap<String, String>();
    putDefaultDbOptions(dbOptions);
    dbOptions.putAll(_wgaConfiguration.getGlobalDatabaseOptions());
    dbOptions.putAll(server.getOptions());
    dbOptions.putAll(config.getDatabaseOptions());

    // Mandatory db options
    dbOptions.put(WGDatabase.COPTION_DBREFERENCE, "personalisation_" + domainConfig.getUid());

    // get the database object
    WGDatabase db = null;
    try {
        if (config.isLazyConnecting()) {
            db = server.prepareDatabase(typeClass, dbOptions);
        } else {
            db = server.openDatabase(typeClass, dbOptions);
        }
    } catch (WGAPIException e) {
        throw new WGAServerException("Could not connect to database", e);
    } catch (ModuleDependencyException e) {
        throw new WGAServerException(
                "Could not connect to database because of missing dependency: " + e.getMessage());
    }

    if (db == null) {
        throw new WGAServerException("Could not open personalisation database for domain '"
                + domainConfig.getName() + " - Check logged messages above for error details");
    } else if (!db.getRoles().contains(WGDatabase.ROLE_USERPROFILES)) {
        throw new WGAServerException("Could not open personalisation database \for domain '"
                + domainConfig.getName() + " - This type does not deliver user profiles");
    }

    if (config.isLazyConnecting()) {
        log.info("Preparing personalisation database on path \"" + db.getPath() + "\" for domain \""
                + domainConfig.getName() + "\"");
        db.addDatabaseConnectListener(this);
    } else {
        log.info("Attaching personalisation database on path \"" + db.getPath() + "\" to domain \""
                + domainConfig.getName() + "\"");
        try {
            log.info("Personalisation database of domain " + domainConfig.getName()
                    + " is content store version " + db.getContentStoreVersion());
        } catch (WGAPIException e) {
            throw new WGAServerException(
                    "Exception determining content store version of personalisation database for domain "
                            + domainConfig.getName(),
                    e);
        }
    }

    // Set domain
    db.setAttribute(WGACore.DBATTRIB_DOMAIN, domainConfig.getUid());

    // Mark this database as fully connected
    db.setAttribute(DBATTRIB_FULLY_CONNECTED, "true");

    return db;
}

From source file:de.innovationgate.wgpublisher.WGACore.java

private WGDatabase retrieveContentDB(ContentDatabase config, Map<String, Serializable> dbConnectionFailures) {

    final ProblemOccasion occ = new ConnectDatabaseProblemOccasion(config.getKey());
    _problemRegistry.clearProblemOccasion(occ);

    try {/*from  w  ww.j a  va  2s.  co  m*/
        final String dbType = (config instanceof ContentStore ? "Web application" : "Data source");

        if (config instanceof ContentStore) {
            logCategoryInfo(dbType + " " + config.getKey(), 2);
        } else {
            logCategoryInfo(dbType + " " + config.getKey(), 2);
        }

        // Get basic information
        String strType = config.getImplClassName();
        String strKey = config.getKey();

        // retrieve dbserver for db
        WGDatabaseServer server = getDatabaseServers().get(config.getDbServer());
        if (server == null) {
            throw Problem.create(occ, "databaseConnectionFailed.unknownServer", ProblemSeverity.HIGH,
                    Problem.var("server", config.getDbServer()));
        }

        if (strKey.equalsIgnoreCase("start") || strKey.equalsIgnoreCase("bi")
                || strKey.equalsIgnoreCase("static") || strKey.equalsIgnoreCase("statictml")
                || strKey.startsWith(PluginConfig.PLUGIN_DBKEY_PREFIX)) {
            throw Problem.create(occ, "databaseConnectionFailed.invalidDbkey", ProblemSeverity.HIGH);
        }

        // Look if the server is able and allowed to instantiate this db type
        Class<WGDatabaseCore> typeClass;
        try {
            Class theClass = WGFactory.getImplementationLoader().loadClass(strType);
            if (!WGDatabaseCore.class.isAssignableFrom(theClass)) {
                throw new WGAServerException(
                        "Cannot map " + dbType + " to key \"" + strKey + "\" - Database implementation class \""
                                + strType + "\" is no WGDatabaseCore implementation.");
            }
            typeClass = theClass;
        } catch (Exception e) {
            throw Problem.create(occ, "databaseConnectionFailed.invalidImplementation", ProblemSeverity.HIGH,
                    Problem.var("class", strType), e);
        }

        // Test for retrievable design for content stores
        if (config instanceof ContentStore) {
            ContentStore csConfig = (ContentStore) config;
            if (csConfig.getDesign() != null) {
                try {
                    WGADesign design = getDesignManager().getDesignForConfig(csConfig.getDesign());
                    if (design == null) {
                        throw Problem.create(occ, "applyDesignProblem.unknownDesign", ProblemSeverity.HIGH,
                                Problem.var("design", (new DesignReference(csConfig.getDesign()).toString())));
                    }
                } catch (Problem p) {
                    throw p;
                } catch (WGADesignRetrievalException e) {
                    String design = (new DesignReference(csConfig.getDesign())).toString();
                    if (e.getDesign() != null) {
                        design = e.getDesign();
                    }
                    throw Problem.create(occ, "applyDesignProblem.unretrievableDesign", ProblemSeverity.HIGH,
                            Problem.var("design", design), e);
                } catch (Exception e) {
                    throw Problem.create(occ, "applyDesignProblem.invalidDesign", ProblemSeverity.HIGH,
                            Problem.var("design", (new DesignReference(csConfig.getDesign()).toString())), e);
                }
            }
        }

        // Evaluate title
        String title = config.getTitle();

        // Evaluate domain
        /*
        Element domainElement = (Element) databaseElement.selectSingleNode("domain");
        DomainConfiguration domainConfig = new DomainConfiguration();
                
        if (domainElement != null) {
        domainConfig = getDomainConfig(domainElement.getStringValue());
        }*/
        Domain domainCfg = getWgaConfiguration().getDomain(config.getDomain());
        WGADomain domain = getDomain(domainCfg);

        // Collect db options from global, server, database
        HashMap<String, String> dbOptions = new HashMap<String, String>();
        putDefaultDbOptions(dbOptions);
        dbOptions.putAll(_wgaConfiguration.getGlobalDatabaseOptions());
        dbOptions.putAll(config.getDatabaseOptions());

        // We collect those options that were added on database level in here
        // and add this set as database attribute
        // so we can tell them later from lower priority options
        Set<String> firstLevelDBOptions = new HashSet<String>();
        firstLevelDBOptions.addAll(config.getDatabaseOptions().keySet());

        // Mandatory db options
        dbOptions.put(WGDatabase.COPTION_DBREFERENCE, strKey.toLowerCase());

        // Optionally add hotpatches path
        String hotPatchesPath = System.getProperty(SYSPROPERTY_JDBC_HOTPATCHES);
        if (hotPatchesPath != null) {
            File hotPatchesFile = getWGAFile(hotPatchesPath);
            if (hotPatchesFile != null) {
                dbOptions.put(WGDatabaseImpl.COPTION_HOTPATCH, hotPatchesFile.getAbsolutePath());
            }
        }

        // get the database object
        WGDatabase db = null;

        if (config.isLazyConnecting()) {
            db = server.prepareDatabase(typeClass, dbOptions);
        } else {
            db = server.openDatabase(typeClass, dbOptions);
        }

        if (db == null || (!config.isLazyConnecting() && !db.isSessionOpen())) {
            throw new WGAServerException("Could not open database for key " + strKey.toLowerCase()
                    + " - Check logged messages from the application log for error details");
        }

        try {

            if (!config.isLazyConnecting()) {
                db.getSessionContext().setTask("Initializing database in WGA");
                log.info("Mapping " + dbType + " on path \"" + db.getPath() + "\" (" + db.getTypeName()
                        + ") to database key \"" + strKey.toLowerCase() + "\"");
                try {
                    if (db.getContentStoreVersion() >= WGDatabase.CSVERSION_WGA5) {
                        int patchLevel = db.getContentStorePatchLevel();
                        log.info("Database for " + strKey.toLowerCase() + " is a WGA Content Store of version "
                                + db.getContentStoreVersion()
                                + (patchLevel != 0 ? " at patch level " + patchLevel : ""));
                    }
                } catch (WGAPIException e) {
                    throw new WGAServerException(
                            "Exception determining content store version of database " + strKey.toLowerCase(),
                            e);
                }
            } else {
                log.info("Preparing " + dbType + " on path \"" + db.getPath() + "\" (" + db.getTypeName()
                        + ") as database for key \"" + strKey.toLowerCase() + "\"");
            }

            if (title != null) {
                db.setTitle(title);
            }

            // Inject the default language if configured, else trigger determination
            if (config instanceof ContentStore) {
                ContentStore csConfig = (ContentStore) config;
                if (!WGUtils.isEmpty(csConfig.getDefaultLanguage())) {
                    db.setDefaultLanguage(csConfig.getDefaultLanguage());
                } else {
                    db.onConnect(new DatabaseAction() {
                        @Override
                        public void run(WGDatabase db) throws Exception {
                            try {
                                db.determineDefaultLanguage();
                            } catch (WGAPIException e) {
                                getLog().error("Exception determining default language for " + dbType + " "
                                        + db.getDbReference(), e);
                                _problemRegistry.addProblem(Problem.create(occ,
                                        "databaseDefaultLanguageProblem.invalidDefaultLanguage",
                                        ProblemSeverity.LOW, e));
                            }
                        }
                    });
                }
            }
            ;

            // Set mandatory database attributes
            initializeDBAttributes(db, strKey, domain.getName(), firstLevelDBOptions);

            // Inject domain authentication module
            if (domain.getAuthModule() != null) {
                try {
                    db.setAuthenticationModule(new DomainRedirectionAuthModule(this, domain.getName()));
                } catch (Exception e) {
                    throw Problem.create(occ, "databaseConnectionFailed.invalidAuth", ProblemSeverity.HIGH, e);
                }
            }

            // Configure design provider, if neccessary
            if (config instanceof ContentStore) {
                ContentStore csConfig = (ContentStore) config;
                if (csConfig.getDesign() != null) {
                    getDesignManager().applyDesign(db, csConfig, occ);
                }
            }

            // Determine if ACL is empty
            // If so, eventually add domain default manager
            boolean aclEmpty = false;
            try {
                if (db.isConnected() && db.isSessionOpen() && db.hasFeature(WGDatabase.FEATURE_ACL_MANAGEABLE)
                        && db.getACL().getAllEntries().size() == 0) {
                    aclEmpty = true;
                }
            } catch (WGBackendException e1) {
                getLog().error("Error retrieving ACL state of " + dbType + " '" + db.getDbReference() + "'",
                        e1);
            }

            if (aclEmpty && domain.getConfig().getDefaultManager() != null) {
                try {
                    getLog().info("Adding default manager '" + domain.getConfig().getDefaultManager()
                            + "' to ACL of '" + strKey + "'");
                    db.getACL().createUserEntry(domain.getConfig().getDefaultManager(),
                            WGDatabase.ACCESSLEVEL_MANAGER);
                } catch (WGAPIException e) {
                    getLog().error("Exception on adding default manager to ACL of '" + strKey + "'", e);
                }
            }

            // Process system container
            SystemContainerManager.SystemContainerContext scContext = null;
            try {
                scContext = _systemContainerManager.addDatabase(db, aclEmpty);
            } catch (Problem p) {
                throw p;
            } catch (InvalidCSConfigVersionException e) {
                throw Problem.create(occ, "databaseConnectionFailed.incompatibleDesign", ProblemSeverity.HIGH,
                        Problem.var("targetversion", e.getTargetVersion()), e);
            } catch (Exception e) {
                throw Problem.create(occ, "databaseConnectionFailed.invalidDesign", ProblemSeverity.HIGH, e);
            }

            // Merge publisher options from global, server, design, database
            Map<String, String> publisherOptions = new HashMap<String, String>();
            publisherOptions.putAll(_wgaConfiguration.getGlobalPublisherOptions());
            if (scContext != null) {
                scContext.putPublisherOptions(publisherOptions);
            }
            publisherOptions.putAll(config.getPublisherOptions());

            // We collect those options that were added on database level in here
            // and add this set as database attribute
            // so we can tell them later from lower priority options
            Set<String> firstLevelPublisherOptions = new HashSet<String>();
            firstLevelPublisherOptions.addAll(config.getPublisherOptions().keySet());
            db.setAttribute(DBATTRIB_FIRSTLEVELPUBLISHEROPTIONS, firstLevelPublisherOptions);

            // Publisher options initialisation, which is equal for content dbs and plugins
            processPublisherOptions(db, publisherOptions);

            // check if db is empty before hdb script runs
            boolean isEmptyDB = false;
            try {
                isEmptyDB = (db.isConnected() && db.hasFeature(WGDatabase.FEATURE_FULLCONTENTFEATURES)
                        && db.isContentEmpty());
            } catch (WGAPIException e) {
                this.log.error("Unable to check if database '" + db.getDbReference() + "' is empty.", e);
            }

            // Validate default language definition
            if (!isEmptyDB && db.hasFeature(WGDatabase.FEATURE_FULLCONTENTFEATURES)) {
                db.onConnect(new ValidateDefaultLanguageAction());
            }

            // Eventually prepare "external self-personalisation"
            if (db.hasFeature(WGDatabase.FEATURE_FULLCONTENTFEATURES)
                    && domain.getConfig().getPersonalisation() == null
                    && !db.hasFeature(WGDatabase.FEATURE_SELF_PERSONALIZABLE)) {
                try {
                    createExternalSelfPersonalisation(db);
                } catch (WGAPIException e) {
                    this.log.error("Exception creating external personalisation database for db '"
                            + db.getDbReference() + "'. Profiles will not be available.", e);
                    _problemRegistry.addProblem(Problem.create(occ,
                            "databaseConnectionProblem.invalidExternalPersDb", ProblemSeverity.LOW, e));
                }
            }

            // Add listeners for events and register embedded event scripts
            db.addDatabaseEventListener(_eventManager);
            db.addContentEventListener(_eventManager);
            db.addWorkflowEventListener(_eventManager);
            if (db.isConnected()) {
                _eventManager.updateDatabaseEvents(db);
            }

            // Add file annotators
            updateFileAnnotators(db);

            // add File Converter
            db.setFileConverter(_fileConverter);

            // Do system container initialisations
            if (scContext != null) {
                scContext.performInitialisation(new Boolean(isEmptyDB));
                // Revalidate the default language if the database was empty before initialisation, might have new definitions now
                if (isEmptyDB) {
                    db.onConnect(new ValidateDefaultLanguageAction());
                }
            }

            // Mark this database as fully connected
            db.setAttribute(DBATTRIB_FULLY_CONNECTED, "true");

            if (_externalFileServingConfig.isEnabled()
                    && db.getBooleanAttribute(DBATTRIB_EXTERNAL_FILE_SERVING_ENABLED, false)) {
                getLog().info("External file serving enabled for database '" + db.getDbReference() + "'.");
            }

            return db;
        } catch (Throwable e) {
            // Cleanup if anything after initial connecting went wrong which makes using this db impossible
            if (db.isReady()) {
                try {
                    db.close();
                } catch (Exception e2) {
                    // Swallowing this exception as anything went wrong before anyway
                }
            }
            throw e;
        }

    } catch (Problem problem) {
        _problemRegistry.addProblem(problem);
        dbConnectionFailures.put(config.getKey(), problem.getMessage());
        log.error(problem.getMessage(), problem.getCause());
        return null;

    } catch (Throwable e) {
        Problem problem;
        if (e.getCause() instanceof LicenseException) {
            problem = Problem.create(occ, "databaseConnectionFailed.licenseError", ProblemSeverity.HIGH, e);
        } else {
            problem = Problem.create(occ, "databaseConnectionFailed.exception", ProblemSeverity.HIGH, e);
        }
        _problemRegistry.addProblem(problem);
        dbConnectionFailures.put(config.getKey(), e.getMessage());
        log.error("An unexpected exception occurred connecting database " + config.getKey(), e);
        return null;
    }

}