Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:org.telegram.ui.PassportActivity.java

private void createRequestInterface(Context context) {
    TLRPC.User botUser = null;/* w  ww .ja v  a  2 s .  c o m*/
    if (currentForm != null) {
        for (int a = 0; a < currentForm.users.size(); a++) {
            TLRPC.User user = currentForm.users.get(a);
            if (user.id == currentBotId) {
                botUser = user;
                break;
            }
        }
    }

    FrameLayout frameLayout = (FrameLayout) fragmentView;

    actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport));

    actionBar.createMenu().addItem(info_item, R.drawable.profile_info);

    if (botUser != null) {
        FrameLayout avatarContainer = new FrameLayout(context);
        linearLayout2.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100));

        BackupImageView avatarImageView = new BackupImageView(context);
        avatarImageView.setRoundRadius(AndroidUtilities.dp(32));
        avatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0));

        AvatarDrawable avatarDrawable = new AvatarDrawable(botUser);
        TLRPC.FileLocation photo = null;
        if (botUser.photo != null) {
            photo = botUser.photo.photo_small;
        }
        avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser);

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportRequest",
                R.string.PassportRequest, UserObject.getFirstName(botUser))));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        ((FrameLayout.LayoutParams) bottomCell.getTextView()
                .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    headerCell = new HeaderCell(context);
    headerCell.setText(
            LocaleController.getString("PassportRequestedInformation", R.string.PassportRequestedInformation));
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    if (currentForm != null) {
        int size = currentForm.required_types.size();
        ArrayList<TLRPC.TL_secureRequiredType> personalDocuments = new ArrayList<>();
        ArrayList<TLRPC.TL_secureRequiredType> addressDocuments = new ArrayList<>();
        int personalCount = 0;
        int addressCount = 0;
        boolean hasPersonalInfo = false;
        boolean hasAddressInfo = false;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (isPersonalDocument(requiredType.type)) {
                    personalDocuments.add(requiredType);
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    addressDocuments.add(requiredType);
                    addressCount++;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    hasPersonalInfo = true;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    hasAddressInfo = true;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (isPersonalDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        personalDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        addressDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    addressCount++;
                }
            }
        }
        boolean separatePersonal = !hasPersonalInfo || personalCount > 1;
        boolean separateAddress = !hasAddressInfo || addressCount > 1;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            ArrayList<TLRPC.TL_secureRequiredType> documentTypes;
            TLRPC.TL_secureRequiredType requiredType;
            boolean documentOnly;
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (requiredType.type instanceof TLRPC.TL_secureValueTypePhone
                        || requiredType.type instanceof TLRPC.TL_secureValueTypeEmail) {
                    documentTypes = null;
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    if (separatePersonal) {
                        documentTypes = null;
                    } else {
                        documentTypes = personalDocuments;
                    }
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    if (separateAddress) {
                        documentTypes = null;
                    } else {
                        documentTypes = addressDocuments;
                    }
                    documentOnly = false;
                } else if (separatePersonal && isPersonalDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    documentOnly = true;
                } else if (separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    documentOnly = true;
                } else {
                    continue;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (separatePersonal && isPersonalDocument(requiredType.type)
                        || separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        documentTypes.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    if (isPersonalDocument(requiredType.type)) {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    } else {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    }

                    documentOnly = true;
                } else {
                    continue;
                }
            } else {
                continue;
            }
            addField(context, requiredType, documentTypes, documentOnly, a == size - 1);
        }
    }

    if (botUser != null) {
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setLinkTextColorKey(Theme.key_windowBackgroundWhiteGrayText4);
        if (!TextUtils.isEmpty(currentForm.privacy_policy_url)) {
            String str2 = LocaleController.formatString("PassportPolicy", R.string.PassportPolicy,
                    UserObject.getFirstName(botUser), botUser.username);
            SpannableStringBuilder text = new SpannableStringBuilder(str2);
            int index1 = str2.indexOf('*');
            int index2 = str2.lastIndexOf('*');
            if (index1 != -1 && index2 != -1) {
                bottomCell.getTextView().setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                text.replace(index2, index2 + 1, "");
                text.replace(index1, index1 + 1, "");
                text.setSpan(new LinkSpan(), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            bottomCell.setText(text);
        } else {
            bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportNoPolicy",
                    R.string.PassportNoPolicy, UserObject.getFirstName(botUser), botUser.username)));
        }
        bottomCell.getTextView().setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    bottomLayout = new FrameLayout(context);
    bottomLayout.setBackgroundDrawable(
            Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_passport_authorizeBackground),
                    Theme.getColor(Theme.key_passport_authorizeBackgroundSelected)));
    frameLayout.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));
    bottomLayout.setOnClickListener(view -> {

        class ValueToSend {
            TLRPC.TL_secureValue value;
            boolean selfie_required;
            boolean translation_required;

            public ValueToSend(TLRPC.TL_secureValue v, boolean s, boolean t) {
                value = v;
                selfie_required = s;
                translation_required = t;
            }
        }

        ArrayList<ValueToSend> valuesToSend = new ArrayList<>();
        for (int a = 0, size = currentForm.required_types.size(); a < size; a++) {

            TLRPC.TL_secureRequiredType requiredType;

            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                secureRequiredType = requiredTypeOneOf.types.get(0);
                if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;

                for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                    secureRequiredType = requiredTypeOneOf.types.get(b);
                    if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                        continue;
                    }
                    TLRPC.TL_secureRequiredType innerType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                    if (getValueByType(innerType, true) != null) {
                        requiredType = innerType;
                        break;
                    }
                }
            } else {
                continue;
            }

            TLRPC.TL_secureValue value = getValueByType(requiredType, true);
            if (value == null) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            String key = getNameForType(requiredType.type);
            HashMap<String, String> errors = errorsMap.get(key);
            if (errors != null && !errors.isEmpty()) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            valuesToSend.add(
                    new ValueToSend(value, requiredType.selfie_required, requiredType.translation_required));
        }
        showEditDoneProgress(false, true);
        TLRPC.TL_account_acceptAuthorization req = new TLRPC.TL_account_acceptAuthorization();
        req.bot_id = currentBotId;
        req.scope = currentScope;
        req.public_key = currentPublicKey;
        JSONObject jsonObject = new JSONObject();
        for (int a = 0, size = valuesToSend.size(); a < size; a++) {
            ValueToSend valueToSend = valuesToSend.get(a);
            TLRPC.TL_secureValue secureValue = valueToSend.value;

            JSONObject data = new JSONObject();

            if (secureValue.plain_data != null) {
                if (secureValue.plain_data instanceof TLRPC.TL_securePlainEmail) {
                    TLRPC.TL_securePlainEmail securePlainEmail = (TLRPC.TL_securePlainEmail) secureValue.plain_data;
                } else if (secureValue.plain_data instanceof TLRPC.TL_securePlainPhone) {
                    TLRPC.TL_securePlainPhone securePlainPhone = (TLRPC.TL_securePlainPhone) secureValue.plain_data;
                }
            } else {
                try {
                    JSONObject result = new JSONObject();
                    if (secureValue.data != null) {
                        byte[] decryptedSecret = decryptValueSecret(secureValue.data.secret,
                                secureValue.data.data_hash);

                        data.put("data_hash",
                                Base64.encodeToString(secureValue.data.data_hash, Base64.NO_WRAP));
                        data.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));

                        result.put("data", data);
                    }
                    if (!secureValue.files.isEmpty()) {
                        JSONArray files = new JSONArray();
                        for (int b = 0, size2 = secureValue.files.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.files.get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            files.put(file);
                        }
                        result.put("files", files);
                    }
                    if (secureValue.front_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.front_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject front = new JSONObject();
                        front.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        front.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("front_side", front);
                    }
                    if (secureValue.reverse_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.reverse_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject reverse = new JSONObject();
                        reverse.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        reverse.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("reverse_side", reverse);
                    }
                    if (valueToSend.selfie_required && secureValue.selfie instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.selfie;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject selfie = new JSONObject();
                        selfie.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        selfie.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("selfie", selfie);
                    }
                    if (valueToSend.translation_required && !secureValue.translation.isEmpty()) {
                        JSONArray translation = new JSONArray();
                        for (int b = 0, size2 = secureValue.translation.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.translation
                                    .get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            translation.put(file);
                        }
                        result.put("translation", translation);
                    }
                    jsonObject.put(getNameForType(secureValue.type), result);
                } catch (Exception ignore) {

                }
            }

            TLRPC.TL_secureValueHash hash = new TLRPC.TL_secureValueHash();
            hash.type = secureValue.type;
            hash.hash = secureValue.hash;
            req.value_hashes.add(hash);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("secure_data", jsonObject);
        } catch (Exception ignore) {

        }
        if (currentPayload != null) {
            try {
                result.put("payload", currentPayload);
            } catch (Exception ignore) {

            }
        }
        if (currentNonce != null) {
            try {
                result.put("nonce", currentNonce);
            } catch (Exception ignore) {

            }
        }
        String json = result.toString();

        EncryptionResult encryptionResult = encryptData(AndroidUtilities.getStringBytes(json));

        req.credentials = new TLRPC.TL_secureCredentialsEncrypted();
        req.credentials.hash = encryptionResult.fileHash;
        req.credentials.data = encryptionResult.encryptedData;
        try {
            String key = currentPublicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT));
            RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

            Cipher c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
            c.init(Cipher.ENCRYPT_MODE, pubKey);
            req.credentials.secret = c.doFinal(encryptionResult.decrypyedFileSecret);
        } catch (Exception e) {
            FileLog.e(e);
        }
        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error == null) {
                        ignoreOnFailure = true;
                        callCallback(true);
                        finishFragment();
                    } else {
                        showEditDoneProgress(false, false);
                        if ("APP_VERSION_OUTDATED".equals(error.text)) {
                            AlertsCreator.showUpdateAppAlert(getParentActivity(),
                                    LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert),
                                    true);
                        } else {
                            showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                    error.text);
                        }
                    }
                }));
        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
    });

    acceptTextView = new TextView(context);
    acceptTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    acceptTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.authorize, 0, 0, 0);
    acceptTextView.setTextColor(Theme.getColor(Theme.key_passport_authorizeText));
    acceptTextView.setText(LocaleController.getString("PassportAuthorize", R.string.PassportAuthorize));
    acceptTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    acceptTextView.setGravity(Gravity.CENTER);
    acceptTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomLayout.addView(acceptTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));

    progressViewButton = new ContextProgressView(context, 0);
    progressViewButton.setVisibility(View.INVISIBLE);
    bottomLayout.addView(progressViewButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    View shadow = new View(context);
    shadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    frameLayout.addView(shadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
}

From source file:com.vmware.identity.idm.server.IdentityManager.java

/**
 * UserName is could be UPN or userID+domain. UserID here is the ldap attribute value used to identity the user.
 * @param userName//from  w w  w  . ja  va2s .c  om
 *            user name for securID login
 * @return
 * @throws Exception
 */
private PrincipalId getPrincipalIDFromUserName(TenantInformation info, String userName,
        HashMap<String, String> userIDAttrMap) throws Exception {

    String[] userInfo = separateUserIDAndDomain(userName);
    if (userInfo == null) {
        throw new IDMLoginException(String.format(
                "User name %s does not contain the domain - expected in format of name@domain", userName));
    }

    if (userIDAttrMap == null || userIDAttrMap.isEmpty()) {
        return new PrincipalId(userInfo[0], userInfo[1]);
    }

    IIdentityProvider provider = info.findProviderADAsFallBack(userInfo[1]);
    String ldapAttrName = userIDAttrMap.get(provider.getName());

    if (ldapAttrName == null || ldapAttrName.equals("userPrincipalName")) {
        return new PrincipalId(userInfo[0], userInfo[1]);
    } else {
        // find the user with the ldap attribute
        PrincipalId pID = provider.findActiveUser(ldapAttrName, userInfo[0]);
        return pID;
    }
}

From source file:com.vmware.identity.idm.server.IdentityManager.java

private String extractRsaUserID(TenantInformation info, String userName, HashMap<String, String> userIDAttrMap)
        throws Exception {

    Validate.notNull(info, "info");

    String[] userInfo = separateUserIDAndDomain(userName);
    if (userInfo == null) {
        throw new IDMLoginException(String.format(
                "User name %s does not contain the domain - expected in format of name@domain", userName));
    }/*from   w  w w  .ja v  a 2s . co m*/

    String userID;
    if (userIDAttrMap == null || userIDAttrMap.isEmpty()) {
        userID = userName;
    } else {
        IIdentityProvider provider = info.findProviderADAsFallBack(userInfo[1]);
        String ldapAttr = userIDAttrMap.get(provider.getName());

        if (ldapAttr == null || ldapAttr.equals("userPrincipalName")) {
            userID = userName;
        } else {
            userID = userInfo[0];
        }
    }
    return userID;
}

From source file:kr.wdream.ui.ChatActivity.java

private void createChatAttachView() {
    if (getParentActivity() == null) {
        return;/*from   ww  w  .  j a v a  2  s . c  o  m*/
    }
    if (chatAttachAlert == null) {
        chatAttachAlert = new ChatAttachAlert(getParentActivity(), this);
        chatAttachAlert.setDelegate(new ChatAttachAlert.ChatAttachViewDelegate() {
            @Override
            public void didPressedButton(int button) {
                if (getParentActivity() == null) {
                    return;
                }
                if (button == 7) {
                    chatAttachAlert.dismiss();
                    HashMap<Integer, MediaController.PhotoEntry> selectedPhotos = chatAttachAlert
                            .getSelectedPhotos();
                    if (!selectedPhotos.isEmpty()) {
                        ArrayList<String> photos = new ArrayList<>();
                        ArrayList<String> captions = new ArrayList<>();
                        ArrayList<ArrayList<TLRPC.InputDocument>> masks = new ArrayList<>();
                        for (HashMap.Entry<Integer, MediaController.PhotoEntry> entry : selectedPhotos
                                .entrySet()) {
                            MediaController.PhotoEntry photoEntry = entry.getValue();
                            if (photoEntry.imagePath != null) {
                                photos.add(photoEntry.imagePath);
                                captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
                                masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers)
                                        : null);
                            } else if (photoEntry.path != null) {
                                photos.add(photoEntry.path);
                                captions.add(photoEntry.caption != null ? photoEntry.caption.toString() : null);
                                masks.add(!photoEntry.stickers.isEmpty() ? new ArrayList<>(photoEntry.stickers)
                                        : null);
                            }
                            photoEntry.imagePath = null;
                            photoEntry.thumbPath = null;
                            photoEntry.caption = null;
                            photoEntry.stickers.clear();
                        }
                        SendMessagesHelper.prepareSendingPhotos(photos, null, dialog_id, replyingMessageObject,
                                captions, masks);
                        showReplyPanel(false, null, null, null, false, true);
                        DraftQuery.cleanDraft(dialog_id, true);
                    }
                    return;
                } else if (chatAttachAlert != null) {
                    chatAttachAlert.dismissWithButtonClick(button);
                }
                processSelectedAttach(button);
            }

            @Override
            public View getRevealView() {
                return menuItem;
            }

            @Override
            public void didSelectBot(TLRPC.User user) {
                if (chatActivityEnterView == null || user.username == null || user.username.length() == 0) {
                    return;
                }
                chatActivityEnterView.setFieldText("@" + user.username + " ");
                chatActivityEnterView.openKeyboard();
            }
        });
    }
}

From source file:plptool.gui.ProjectDriver.java

/**
 * Open plp file specified by path.//from   w ww. ja  va  2  s  . c  o m
 *
 * @param path Path to project file to load.
 * @param assemble Attempt to assemble after opening (if dirty is not set)
 * @return PLP_OK on successful operation, error code otherwise
 */
public int open(String path, boolean assemble) {
    File plpFile = new File(path);
    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN, plpFile);

    if (!plpFile.exists())
        return Msg.E("open(" + path + "): File not found.", Constants.PLP_BACKEND_PLP_OPEN_ERROR, null);

    boolean metafileFound = false;
    dirty = true;

    Msg.I("Opening " + path, null);

    if (arch != null) {
        arch.cleanup();
        arch = null;
    }
    asm = null;
    asms = new ArrayList<PLPAsmSource>();
    smods = null;
    watcher = null;
    pAttrSet = new HashMap<String, Object>();
    HashMap<String, Integer> asmFileOrder = new HashMap<String, Integer>();

    try {

        TarArchiveInputStream tIn = new TarArchiveInputStream(new FileInputStream(plpFile));
        TarArchiveEntry entry;
        byte[] image;
        String metaStr;

        // Find meta file first
        while ((entry = tIn.getNextTarEntry()) != null) {
            if (entry.getName().equals("plp.metafile")) {
                image = new byte[(int) entry.getSize()];
                tIn.read(image, 0, (int) entry.getSize());
                metaStr = new String(image);

                metafileFound = true;
                meta = metaStr;
                Scanner metaScanner;

                String lines[] = meta.split("\\r?\\n");
                if (lines[0].equals(Text.projectFileVersionString)) {

                } else {
                    Msg.W("This is not a " + Text.projectFileVersionString + " project file. Opening anyways.",
                            this);
                }

                metaScanner = new Scanner(meta);
                metaScanner.findWithinHorizon("DIRTY=", 0);
                if (metaScanner.nextInt() == 0)
                    dirty = false;
                if (metaScanner.findWithinHorizon("ARCH=", 0) != null) {
                    String temp = metaScanner.nextLine();
                    if (Config.cfgOverrideISA >= 0) { // ISA ID override, ignore the metafile
                        arch = ArchRegistry.getArchitecture(this, Config.cfgOverrideISA);
                        arch.init();
                    } else if (temp.equals("plpmips")) {
                        Msg.W("This project file was created by PLPTool version 3 or earlier. "
                                + "Meta data for this project will be updated "
                                + "with the default ISA (plpmips) when the project " + "file is saved.", this);
                        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        arch.init();
                    } else {
                        arch = ArchRegistry.getArchitecture(this, Integer.parseInt(temp));
                        if (arch == null) {
                            Msg.W("Invalid ISA ID is specified in the project file: '" + temp
                                    + "'. Assuming PLPCPU.", this);
                            arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
                        }
                        arch.init();
                    }
                    arch.hook(this);
                }

                // get asm files order
                int asmOrder = 0;
                while (metaScanner.hasNext()) {
                    String asmName = metaScanner.nextLine();
                    if (asmName.endsWith(".asm")) {
                        asmFileOrder.put(asmName, new Integer(asmOrder));
                        asmOrder++;
                        asms.add(null);
                    }
                }
            }
        }

        if (!metafileFound)
            return Msg.E("No PLP metadata found.", Constants.PLP_BACKEND_INVALID_PLP_FILE, this);

        // reset the tar input stream
        tIn = new TarArchiveInputStream(new FileInputStream(plpFile));

        while ((entry = tIn.getNextTarEntry()) != null) {
            boolean handled = false;
            image = new byte[(int) entry.getSize()];
            tIn.read(image, 0, (int) entry.getSize());
            metaStr = new String(image);

            // Hook for project open for each entry
            Object[] eParams = { entry.getName(), image, plpFile };
            handled = CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_ENTRY, eParams) || handled;

            if (entry.getName().endsWith("asm") && !entry.getName().startsWith("plp.")) {
                Integer order = (Integer) asmFileOrder.get(entry.getName());
                if (order == null)
                    Msg.W("The file '" + entry.getName() + "' is not listed in "
                            + "the meta file. This file will be removed when the project " + "is saved.", this);
                else {
                    asms.set(order, new PLPAsmSource(metaStr, entry.getName(), order));
                }

            } else if (entry.getName().equals("plp.metafile")) {
                // we've done reading the metafile

            } else if (entry.getName().equals("plp.image")) {
                binimage = new byte[(int) entry.getSize()];
                binimage = image;

            } else if (entry.getName().equals("plp.hex")) {
                hexstring = new String(image);

                // Restore bus modules states
            } else if (entry.getName().equals("plp.simconfig")) {
                Msg.D("simconfig:\n" + metaStr + "\n", 4, this);
                String lines[] = metaStr.split("\\r?\\n");
                int i;

                for (i = 0; i < lines.length; i++) {
                    String tokens[] = lines[i].split("::");

                    if (lines[i].startsWith("simRunnerDelay")) {
                        Config.simRunnerDelay = Integer.parseInt(tokens[1]);
                    }

                    if (lines[i].equals("MODS")) {
                        i++;
                        this.smods = new Preset();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            if (tokens.length > 4 && tokens[4].equals("noframe"))
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), false, false);
                            else if (tokens.length > 4)
                                smods.addModuleDefinition(Integer.parseInt(tokens[0]),
                                        Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), true,
                                        Boolean.parseBoolean(tokens[5]));

                            i++;
                        }
                    }

                    if (lines[i].equals("WATCHER")) {
                        i++;
                        this.watcher = Watcher.getTableInitialModel();

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            Object row[] = { tokens[0], tokens[1], null, null };
                            watcher.addRow(row);
                            i++;
                        }
                    }

                    if (lines[i].equals("ISASPECIFIC")) {
                        i++;

                        while (i < lines.length && !lines[i].equals("END")) {
                            tokens = lines[i].split("::");
                            arch.restoreArchSpecificSimStates(tokens);
                            i++;
                        }
                    }
                }
            } else if (handled) {

            } else {
                Msg.W("open(" + path + "): unable to process entry: " + entry.getName()
                        + ". This file will be removed when" + " you save the project.", this);
            }
        }

        tIn.close();

        if (asmFileOrder.isEmpty()) {
            return Msg.E("open(" + path + "): no .asm files found.", Constants.PLP_BACKEND_INVALID_PLP_FILE,
                    null);
        }

    } catch (Exception e) {
        Msg.trace(e);
        return Msg.E("open(" + path + "): Invalid PLP archive.", Constants.PLP_BACKEND_INVALID_PLP_FILE, null);
    }

    if (arch == null) {
        Msg.W("No ISA information specified in the archive, assuming plpmips", this);
        arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS);
        arch.init();
    }

    plpfile = new File(path);
    modified = false;
    open_asm = 0;

    for (int i = 0; i < asms.size(); i++)
        Msg.I(i + ": " + asms.get(i).getAsmFilePath(), null);

    if (g)
        refreshProjectView(false);
    if (!dirty && assemble) {
        assemble();
        asm_req = false;
    } else
        asm_req = true;

    if (g) {
        g_opts.restoreSavedOpts();
        desimulate();

        if (asm != null && asm.isAssembled())
            g_dev.enableSimControls();
        else
            g_dev.disableSimControls();

        this.setUnModified();
        updateWindowTitle();
        g_dev.updateDevelopRecentProjectList(plpFile.getAbsolutePath());
        if (g_asmview != null)
            g_asmview.dispose();
    }

    CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_SUCCESSFUL, plpFile);
    return Constants.PLP_OK;
}

From source file:org.apache.hadoop.mapred.lib.CombineFileInputFormat.java

/**
 * Return all the splits in the specified set of paths
 *//*  www. j  ava2s.  c  o m*/
private void getMoreSplits(JobConf job, Collection<LocatedFileStatus> stats, long maxSize, long minSizeNode,
        long minSizeRack, long maxNumBlocksPerSplit, List<CombineFileSplit> splits) throws IOException {

    // all blocks for all the files in input set
    OneFileInfo[] files;

    // mapping from a rack name to the list of blocks it has
    HashMap<String, List<OneBlockInfo>> rackToBlocks = new HashMap<String, List<OneBlockInfo>>();

    // mapping from a block to the nodes on which it has replicas
    HashMap<OneBlockInfo, String[]> blockToNodes = new HashMap<OneBlockInfo, String[]>();

    // mapping from a node to the list of blocks that it contains
    HashMap<String, List<OneBlockInfo>> nodeToBlocks = new HashMap<String, List<OneBlockInfo>>();

    if (stats.isEmpty()) {
        return;
    }
    files = new OneFileInfo[stats.size()];

    // populate all the blocks for all files
    long totLength = 0;
    int fileIndex = 0;
    for (LocatedFileStatus oneStatus : stats) {
        files[fileIndex] = new OneFileInfo(oneStatus, job,
                isSplitable(FileSystem.get(job), oneStatus.getPath()), rackToBlocks, blockToNodes, nodeToBlocks,
                rackToNodes, maxSize);
        totLength += files[fileIndex].getLength();
        fileIndex++;
    }

    // Sort the blocks on each node from biggest to smallest by size to
    // encourage more node-local single block splits
    sortBlocksBySize(nodeToBlocks);

    ArrayList<OneBlockInfo> validBlocks = new ArrayList<OneBlockInfo>();
    Set<String> nodes = new HashSet<String>();
    long curSplitSize = 0;

    // process all nodes and create splits that are local
    // to a node.
    for (Iterator<Map.Entry<String, List<OneBlockInfo>>> iter = nodeToBlocks.entrySet().iterator(); iter
            .hasNext();) {

        Map.Entry<String, List<OneBlockInfo>> one = iter.next();
        nodes.add(one.getKey());
        List<OneBlockInfo> blocksInNode = one.getValue();

        // for each block, copy it into validBlocks. Delete it from
        // blockToNodes so that the same block does not appear in
        // two different splits.
        for (OneBlockInfo oneblock : blocksInNode) {
            if (blockToNodes.containsKey(oneblock)) {
                validBlocks.add(oneblock);
                blockToNodes.remove(oneblock);
                curSplitSize += oneblock.length;

                // if the accumulated split size exceeds the maximum, then
                // create this split.
                if ((maxSize != 0 && curSplitSize >= maxSize)
                        || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
                    // create an input split and add it to the splits array
                    // if only one block, add all the node replicas
                    if (validBlocks.size() == 1) {
                        Set<String> blockLocalNodes = new HashSet<String>(
                                Arrays.asList(validBlocks.get(0).hosts));
                        addCreatedSplit(job, splits, blockLocalNodes, validBlocks);
                        addStatsForSplitType(SplitType.SINGLE_BLOCK_LOCAL, curSplitSize, blockLocalNodes.size(),
                                validBlocks.size());
                    } else {
                        addCreatedSplit(job, splits, nodes, validBlocks);
                        addStatsForSplitType(SplitType.NODE_LOCAL, curSplitSize, nodes.size(),
                                validBlocks.size());
                    }
                    curSplitSize = 0;
                    validBlocks.clear();
                }
            }
        }
        // if there were any blocks left over and their combined size is
        // larger than minSplitNode, then combine them into one split.
        // Otherwise add them back to the unprocessed pool. It is likely
        // that they will be combined with other blocks from the same rack later on.
        if (minSizeNode != 0 && curSplitSize >= minSizeNode) {
            // create an input split and add it to the splits array
            addCreatedSplit(job, splits, nodes, validBlocks);
            addStatsForSplitType(SplitType.NODE_LOCAL_LEFTOVER, curSplitSize, nodes.size(), validBlocks.size());
        } else {
            for (OneBlockInfo oneblock : validBlocks) {
                blockToNodes.put(oneblock, oneblock.hosts);
            }
        }
        validBlocks.clear();
        nodes.clear();
        curSplitSize = 0;
    }

    // if blocks in a rack are below the specified minimum size, then keep them
    // in 'overflow'. After the processing of all racks is complete, these overflow
    // blocks will be combined into splits.
    ArrayList<OneBlockInfo> overflowBlocks = new ArrayList<OneBlockInfo>();
    Set<String> racks = new HashSet<String>();

    // Process all racks over and over again until there is no more work to do.
    boolean noRacksMadeSplit = false;
    while (blockToNodes.size() > 0) {

        // Create one split for this rack before moving over to the next rack.
        // Come back to this rack after creating a single split for each of the
        // remaining racks.
        // Process one rack location at a time, Combine all possible blocks that
        // reside on this rack as one split. (constrained by minimum and maximum
        // split size).

        // Iterate over all racks.  Add to the overflow blocks only if at least
        // one pass over all the racks was completed without adding any splits
        long splitsAddedOnAllRacks = 0;
        for (Iterator<Map.Entry<String, List<OneBlockInfo>>> iter = rackToBlocks.entrySet().iterator(); iter
                .hasNext();) {

            Map.Entry<String, List<OneBlockInfo>> one = iter.next();
            racks.add(one.getKey());
            List<OneBlockInfo> blocks = one.getValue();

            // for each block, copy it into validBlocks. Delete it from
            // blockToNodes so that the same block does not appear in
            // two different splits.
            boolean createdSplit = false;
            for (OneBlockInfo oneblock : blocks) {
                if (blockToNodes.containsKey(oneblock)) {
                    validBlocks.add(oneblock);
                    blockToNodes.remove(oneblock);
                    curSplitSize += oneblock.length;

                    // if the accumulated split size exceeds the maximum, then
                    // create this split.
                    if ((maxSize != 0 && curSplitSize >= maxSize)
                            || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
                        // create an input split and add it to the splits array
                        addCreatedSplit(job, splits, getHosts(racks), validBlocks);
                        addStatsForSplitType(SplitType.RACK_LOCAL, curSplitSize, getHosts(racks).size(),
                                validBlocks.size());
                        createdSplit = true;
                        ++splitsAddedOnAllRacks;
                        break;
                    }
                }
            }

            // if we created a split, then just go to the next rack
            if (createdSplit) {
                curSplitSize = 0;
                validBlocks.clear();
                racks.clear();
                continue;
            }

            if (!validBlocks.isEmpty()) {
                if (minSizeRack != 0 && curSplitSize >= minSizeRack) {
                    // if there is a mimimum size specified, then create a single split
                    // otherwise, store these blocks into overflow data structure
                    addCreatedSplit(job, splits, getHosts(racks), validBlocks);
                    addStatsForSplitType(SplitType.RACK_LOCAL_LEFTOVER, curSplitSize, getHosts(racks).size(),
                            validBlocks.size());
                    ++splitsAddedOnAllRacks;
                } else if (!noRacksMadeSplit) {
                    // Add the blocks back if a pass on all rack found at least one
                    // split or this is the first pass
                    for (OneBlockInfo oneblock : validBlocks) {
                        blockToNodes.put(oneblock, oneblock.hosts);
                    }
                } else {
                    // There were a few blocks in this rack that remained to be processed.
                    // Keep them in 'overflow' block list. These will be combined later.
                    overflowBlocks.addAll(validBlocks);
                }
            }
            curSplitSize = 0;
            validBlocks.clear();
            racks.clear();
        }

        if (splitsAddedOnAllRacks == 0) {
            noRacksMadeSplit = true;
        }
    }

    assert blockToNodes.isEmpty();
    assert curSplitSize == 0;
    assert validBlocks.isEmpty();
    assert racks.isEmpty();

    // Process all overflow blocks
    for (OneBlockInfo oneblock : overflowBlocks) {
        validBlocks.add(oneblock);
        curSplitSize += oneblock.length;

        // This might cause an exiting rack location to be re-added,
        // but it should be OK because racks is a Set.
        for (int i = 0; i < oneblock.racks.length; i++) {
            racks.add(oneblock.racks[i]);
        }

        // if the accumulated split size exceeds the maximum, then
        // create this split.
        if ((maxSize != 0 && curSplitSize >= maxSize)
                || (maxNumBlocksPerSplit > 0 && validBlocks.size() >= maxNumBlocksPerSplit)) {
            // create an input split and add it to the splits array
            addCreatedSplit(job, splits, getHosts(racks), validBlocks);
            addStatsForSplitType(SplitType.OVERFLOW, curSplitSize, getHosts(racks).size(), validBlocks.size());
            curSplitSize = 0;
            validBlocks.clear();
            racks.clear();
        }
    }

    // Process any remaining blocks, if any.
    if (!validBlocks.isEmpty()) {
        addCreatedSplit(job, splits, getHosts(racks), validBlocks);
        addStatsForSplitType(SplitType.OVERFLOW_LEFTOVER, curSplitSize, getHosts(racks).size(),
                validBlocks.size());
    }
}

From source file:net.emotivecloud.scheduler.drp4one.DRP4OVF.java

/**
 * *************************************************************************
 * Methods with a correspondence in the OCCI interface. *
 * ************************************************************************
 *///  w w  w .  j  a v a2s  . co  m
@POST
@Path("/compute")
@Consumes("application/xml")
@Produces("application/xml")
/**
 * Method that managers the post to http://host/ovf4one/compute. This
 * creates a vm instance
 *
 * @param ovfXml a <code>String</code> an OVF file with the informations
 * that drive the VM instance creation
 * @param request an <code>HttpServletRequest</code> with the full http
 * request
 * @return a <code>String</code> an OVF input with the VM instance ID
 * @exception DRPOneException If something goes wrong, what else ?
 */
public String createCompute(String ovfXml, @Context HttpServletRequest request)
        throws DRPOneException, ParserConfigurationException, SAXException { // (Map<String,
    // Object>);
    HashMap<String, String> hmap = new HashMap<String, String>();

    log.debug("entering create compute...");

    if (ovfXml == null) {
        throw new DRPOneException("\nFailed createCompute method!!\n." + "\nThe ovf xml is" + ovfXml
                + "\n.Please enter correct xml ovf and try again.\n", StatusCodes.BAD_OVF);
    }
    log.debug("ovfxml is not null...");
    OVFWrapper ovf;

    try {
        log.debug("parsing the ovfxml...");
        ovf = parse(ovfXml);
        log.debug("parsing successful");
    } catch (DRPOneException e) {
        // This one is expectet to be thrown, and should
        // pass unchanged
        throw e;
    } catch (Exception e) {
        throw new DRPOneException("\nFailed createCompute method!!\n"
                + "An error occured to parse ovfXml.\n The parse of ovfxml is " + e.getCause()
                + "\n.Please enter correct xml ovf anf try again.\n", StatusCodes.BAD_OVF);

    }
    log.debug("parsed ovf:\n" + ovf);

    EmotiveOVF emotiveOvf = new EmotiveOVF(ovf);
    List<SectionType> sections = OVFAux.findSections(emotiveOvf.getOVFEnvelope().getSection(),
            ProductSectionType.class);
    ProductSectionType ps = null;
    for (SectionType s : sections) {
        if (s instanceof ProductSectionType
                && ((ProductSectionType) s).getClazz().equals(OVFWrapper.class.getName())) {
            ps = (ProductSectionType) s;
            break;
        }
    }
    if (ps != null) {
        List cop = ps.getCategoryOrProperty();
        ProductSectionType.Property propertyToRemove = null;
        for (Object prop : cop) {
            if (prop instanceof ProductSectionType.Property) {
                ProductSectionType.Property p = (ProductSectionType.Property) prop;
                hmap.put(p.getKey(), p.getValueAttribute());
                log.debug(p.getKey() + " " + p.getValueAttribute());
            }
        }
    }
    Client ocaClient = getClient(request);

    log.debug("created ocaclient");

    //1) Create the Images that will be used at the VM template
    System.out.println("DRP4ONE - createVM> Voy a llamar a oneExtraFuncs.createAllImages()...");
    oneExtraFuncs.createAllImages(getClient(request), ONE_DATASTORE_ID, ovf.getDisks().values(),
            emotiveOvf.getBaseImage());

    //2) Start creating the VM Template
    String vmTemplate = "";

    try {
        System.out.println("DRP4ONE - createVM> emotiveOvf:" + emotiveOvf);
        //            vmTemplate = ovf2OneDescription(emotiveOvf, request);
        vmTemplate = oneExtraFuncs.VMTemplate(ocaClient, emotiveOvf);
        //Sergio is doing a replace for the adequate ONE Network
        //            vmTemplate = vmTemplate.replace("NETWORK = \"public\" ", "NETWORK = \"" + myOneNet + "\"");
        System.out.println("***************************************************************");
        System.out.println("DRP4ONE - createVM> vmTemplate2 (REPLACED):" + vmTemplate);
        System.out.println("***************************************************************");
    } catch (Exception e) {
        log.error("Exception occurred:" + e.getMessage());
        System.out.println("DRP4ONE - createVM> EXPCECION SALTADA CREANDO TEMPLATE");
    }

    log.debug("vmtemplate:\n" + vmTemplate);
    // Creates the VM, keeping it at PENDING state (necessary to call deploy())
    System.out.println("DRP4ONE - createVM> allocating the VM");

    OneResponse rc = VirtualMachine.allocate(ocaClient, vmTemplate);

    if (rc.isError()) {
        System.out.println("DRP4ONE - createVM> ERROR while allocating the VM");
        System.out.println("DRP4ONE - createVM> Message: " + rc.getErrorMessage());
        throw new DRPOneException(
                "\nFailed createCompute method!!\n" + "Failed to create VM " + rc.getErrorMessage() + Status,
                StatusCodes.ONE_FAILURE);
    }
    int newVMID = Integer.parseInt(rc.getMessage());

    System.out.println("DRP4ONE - createVM> the new VM has newVMID=" + newVMID);

    // After created the VM, it is necessary to deploy the VM
    VirtualMachine myvm = new VirtualMachine(newVMID, ocaClient);
    String strHostName = emotiveOvf.getProductProperty(EmotiveOVF.PROPERTYNAME_DESTINATION_HOST);

    System.out.println("DRP4ONE - createVM> the VM host (extracted from OVF, strHostID=" + strHostName);

    //TODO: call the image creation
    // get the path
    //        String imgName = emotiveOvf.getBaseImage();
    //        String imgPath = imgsHome + "/" + imgName;
    //        System.out.println("DRP4ONE - createVM> imgName:" + imgName);
    //        System.out.println("DRP4ONE - createVM> imgPath:" + imgPath);
    // get the name
    //        oneExtraFuncs.createImage(ocaClient, ONE_DATASTORE_ID, imgName, imgPath);

    // this function gets id from a host name from OpenStack
    int hid = oneExtraFuncs.getIdFromName(getClient(request), strHostName);

    System.out.println("DRP4ONE  - oneExtraFuncs.getIdFromName(c," + strHostName + ")> : " + hid);

    //        int hostID = Integer.parseInt(hid);
    OneResponse rc_info = myvm.info();

    System.out.println("DRP4ONE  - createVM> rc_info: " + rc_info);

    //TODO: Use the host got from the ovf (now static "2")
    //Initiates the instance of the VM on the target host.
    //        OneResponse rc_deploy = myvm.deploy(hostID);
    System.out.println("B========================================D DRP4ONE  - myvm.deploy(" + hid + ")> : ");
    OneResponse rc_deploy = myvm.deploy(hid);

    if (rc_deploy.isError()) {
        System.out.println("DRP4ONE - createVM> ERROR while deploying the VM");
        throw new DRPOneException("\nFailed createCompute method!!\n" + "Failed to create VM "
                + rc_deploy.getErrorMessage() + Status, StatusCodes.ONE_FAILURE);
    }

    System.out.println(
            "DRP4ONE - createVM> deploying VM at specific host, message from ONE: " + rc_deploy.getMessage());

    // The response message is the new VM's ID
    log.info("ok, ID " + newVMID + ".");

    OVFNetwork nets[] = this.getNetworks(request, newVMID);
    /*
     * notifyUsageTracker(newVMID, SecureSessionInfo.getUserDN(request));
     * log.info("UsageTracker notified for " + newVMID + ".");
     */
    // We can create a representation for the new VM, using the returned
    // VM-ID
    // Returning created domain.
    // get the disk section properties
    Collection<OVFDisk> tmpDisks = ovf.getDisks().values();
    OVFDisk disks[] = tmpDisks.toArray(new OVFDisk[tmpDisks.size()]);

    // get the network properties
    //        Collection<OVFNetwork> tmpNets = ovf.getNetworks().values();
    //        OVFNetwork nets[] = tmpNets.toArray(new OVFNetwork[tmpNets.size()]);
    // get the product properties
    // HashMap<String, String> hmap = new HashMap<String,String>();
    // SectionType product =
    // OVFAux.findSection(ovf.getOVFEnvelope().getSection(),
    // ProductSectionType.class);
    log.debug("RAM:" + ovf.getMemoryMB());

    String xx = OVFWrapperFactory.create(ovf.getId(), ovf.getCPUsNumber(), ovf.getMemoryMB(), disks, nets, hmap)
            .toCleanString();

    idVsOneId.put(ovf.getId(), newVMID);

    try {
        //Truco Josep pa guardar name 
        EmotiveOVF ovfDomEmo = new EmotiveOVF(xx);
        ovfDomEmo.setProductProperty(EmotiveOVF.PROPERTYNAME_VM_NAME, String.valueOf(newVMID));
    } catch (Exception e) {
        System.out.println("");
        e.printStackTrace();
    }

    if (!hmap.isEmpty()) {
        PRODUCT_PROPS.put(String.valueOf(newVMID), hmap);

        //            writeToFile(productPropsFolder + PROPS_FILE_NAME, String.valueOf(newVMID));
    }

    log.debug("ovf returned:" + xx);
    return xx;
}

From source file:org.apparatus_templi.web.handler.SettingsHandler.java

private byte[] getResponse() {
    byte[] returnBytes = null;
    byte[] templateBytes = HttpHelper.getFileBytes(webserver.getResourceFolder() + "inc/template.html");
    if (templateBytes != null) {
        String template = new String(templateBytes);

        StringBuilder html = new StringBuilder();
        HashMap<String, String> prefs = Coordinator.getPrefs().getPreferencesMap();
        // remove any preferences that should be hidden from the frontend
        prefs.remove(Prefs.Keys.userName);
        prefs.remove(Prefs.Keys.userPass);

        String configFile = prefs.get(Prefs.Keys.configFile);

        if (webserver instanceof EncryptedWebServer) {
            if (!Prefs.isCredentialsSet()) {
                html.append(//from  w  w  w. jav a  2  s  . c o  m
                        "<div class='info-box' style='width:600px; display: block; margin-right: auto; margin-left: auto; "
                                + "cursor: pointer; font-size: smaller; text-align: center; padding: 10px'><p>No password has been set. "
                                + "Access will be unrestricted until you <a onclick='window.open(\"/set_password\", \"password_change\", "
                                + "\"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=750,height=550\");'>"
                                + "set a password</a>.</p></div>");
            }
        }

        // TODO update to a form so that the settings can be sent back in a POST request
        html.append("<div id=\"prefs_form\">");

        // Buttons
        html.append("<div id='settings-buttons'>");
        // TODO what modules can be restarted?
        html.append("<span id=\"restart_all_button\" class=\"btn-group closed\" >"
                + "<a class=\"btn btn-danger\" href=\"/restart_module?module=all\" title='Restarting the service will re-read "
                + "preferences from config file, restart all driver, and re-initialize the web server and the serial connection.'>"
                + "<i class=\"fa fa-refresh fa-fw\"></i> &nbsp;&nbsp;Restart Service</a>"
                + "<a class=\"btn btn-danger dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">"
                + "<span class=\"fa fa-caret-down\"></span></a>" + "<ul class=\"dropdown-menu\">"
                + "<li><a href=\"/restart_module?module=drivers\" title='Ask all drivers to terminate, then re-initialize all "
                + "drivers.  Only drivers specified in the driver list will be started.'><i class=\"fa fa-refresh fa-fw\"></i> "
                + "Restart Drivers</a></li><li><a href=\"/restart_module?module=web\" title='Restart the web server. This will "
                + "bind the web server to a new address and port number if those settings have been changed.'><i class=\"fa "
                + "fa-refresh fa-fw\"></i> Restart Web Server</a></li><li><a href=\"/restart_module?module=serial\" "
                + "title='Re-initialize the serial connection, discarding all partial messages'><i class=\"fa fa-refresh "
                + "fa-fw\"></i> Serial Connection</a></li></ul> </span>");

        // Save preferences button
        // if the config file is the default then we want the save preferences button to be
        // disabled until updated via javascript
        html.append("<span id='form_submit' ");
        if (configFile.equals(Coordinator.getPrefs().getDefPreference(Prefs.Keys.configFile))) {
            html.append("class='btn btn-success disabled'>");
        } else {
            html.append("class ='btn btn-success' ");
            html.append("form=\"prefs\" ");
            html.append("onclick = \"document.getElementById('prefs').submit()\" >");
        }
        html.append("<i class=\"fa fa-save\"></i>&nbsp;&nbsp;" + "Save Preferences to <span id='btn_conf_file'>"
                + configFile + "</span></div>");

        // end submit span
        html.append("</span>");

        // end buttons div
        // html.append("</div>");

        // clear the elements
        // html.append("<div class=\"clear\"></div>");

        html.append("<form name='prefs' id='prefs' action=\"update_settings\" " + "method=\"POST\" >\n");

        // settings boxes div
        html.append("<div id='settings_boxes'>");

        // Preferences for the main section
        html.append("<div id='prefs_section_main' class='prefs_section info-box'><div class='title'>"
                + "<i  class=\"fa fa-code-fork\"></i>&nbsp;Main" + "</div>");
        html.append("<div class='content'>");
        html.append("<div class=\"pref_input\"><span class=\"pref_key\">"
                + "<i class=\"fa fa-question-circle\" " + "title=\""
                + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(Prefs.Keys.configFile))
                + "\"></i>&nbsp;" + Prefs.Keys.configFile + "</span><span "
                + "class=\"pref_value\"><input id='f_config_file' type=\"text\" name=\"" + Prefs.Keys.configFile
                + "\" value=\"" + prefs.get(Prefs.Keys.configFile)
                + "\" onChange='updateConfigFile()' onkeypress='updateConfigFile()' onkeyup='updateConfigFile()' "
                + "onBlur='updateConfigFile()' /></span></div><br />\n");
        prefs.remove(Prefs.Keys.configFile);
        for (String key : new String[] { Prefs.Keys.serialPort, Prefs.Keys.driverList, Prefs.Keys.logFile,
                Prefs.Keys.emailList, Prefs.Keys.debugLevel }) {
            String value = prefs.get(key);
            // the serial port name can be a null value, but writing a null string
            // + will print "null" (a non-existent serial port). Write "" instead.
            if (key.equals(Prefs.Keys.serialPort) && value == null) {
                value = "";
            }
            html.append("<div class=\"pref_input\"><span class=\"pref_key \">"
                    + "<i class=\"fa fa-question-circle\" " + "title=\""
                    + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(key))
                    + "\"></i>&nbsp;" + Coordinator.getPrefs().getPreferenceName(key) + "</span><span "
                    + "class=\"pref_value\"><input "
                    + ((key == Prefs.Keys.userPass) ? " type='password' " : " type='text'") + " name=\"" + key
                    + "\" value=\"" + value + "\" /></span></div><br />\n");
            prefs.remove(key);
        }
        if (Prefs.isCredentialsSet() && webserver instanceof EncryptedWebServer) {
            html.append(
                    "<div style='margin-right: auto; margin-left: auto; cursor: pointer; text-align: center'><p><a "
                            + "onclick='window.open(\"/set_password\", \"password_change\", \"toolbar=no,location=no,status=no,"
                            + "menubar=no,scrollbars=yes,resizable=yes,width=750,height=550\");'>Change password</a></p></div>");
        }
        html.append("</div></div>");

        // Preferences for web server
        html.append("<div id='prefs_section_webserver'  class='prefs_section info-box'><div class='title'>"
                + "<i class=\"fa fa-cloud\"></i>&nbsp;Web Server" + "</div>");
        html.append("<div class='content'>");
        for (String key : new String[] { Prefs.Keys.portNum, Prefs.Keys.serverBindLocalhost,
                Prefs.Keys.encryptServer, Prefs.Keys.webResourceFolder }) {
            String value = prefs.get(key);
            html.append("<div class=\"pref_input\"><span class=\"pref_key\">"
                    + "<i class=\"fa fa-question-circle \" " + "title=\""
                    + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(key))
                    + "\"></i>&nbsp;" + Coordinator.getPrefs().getPreferenceName(key) + "</span><span "
                    + "class=\"pref_value\"><input "
                    + (key.equals((Prefs.Keys.portNum)) ? " type='number' " : "") + " type=\"text\" name=\""
                    + key + "\" value=\"" + value + "\" /></span></div><br />\n");
            prefs.remove(key);
        }
        html.append("</div></div>");

        // Preferences for the Twitter service
        html.append("<div id='prefs_section_twitter' class='prefs_section info-box'><div class='title'>"
                + "<i  class=\"fa fa-twitter\"></i>&nbsp;Twitter Service" + "</div>");
        html.append("<div class='content'>");
        for (String key : new String[] { Prefs.Keys.twtrAccess, Prefs.Keys.twtrAccessKey }) {
            html.append("<div class=\"pref_input\"><span class=\"pref_key\">"
                    + "<i class=\"fa fa-question-circle \" " + "title=\""
                    + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(key))
                    + "\"></i>&nbsp;" + Coordinator.getPrefs().getPreferenceName(key) + "</span><span "
                    + "class=\"pref_value\"><input " + " type=\"password\" name=\"" + key + "\" value=\""
                    + prefs.get(key) + "\" /></span></div><br />\n");
            prefs.remove(key);
        }
        html.append("</div>");
        html.append("<div class='warning'><p class=''>" + ENC_WARNING
                + "All passwords are stored in plaintext.</div>");
        html.append("</div>");

        // Preferences for the email service
        html.append("<div id='prefs_section_email' class='info-box prefs_section'><div class='title'>"
                + "<i  class=\"fa fa-envelope\"></i>&nbsp;Email Service" + "</div>");
        html.append("<div class='content'>");
        for (String key : new String[] { Prefs.Keys.emailAddress, Prefs.Keys.emailUsername,
                Prefs.Keys.emailPassword, Prefs.Keys.emailServer, Prefs.Keys.emailPort }) {
            html.append("<div class=\"pref_input\"><span class=\"pref_key\">"
                    + "<i class=\"fa fa-question-circle \" " + "title=\""
                    + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(key))
                    + "\"></i>&nbsp;" + Coordinator.getPrefs().getPreferenceName(key) + "</span><span "
                    + "class=\"pref_value\"><input "
                    + ((key == Prefs.Keys.emailPassword) ? "type = 'password' " : " type=\"text\"") + " name=\""
                    + key + "\" value=\"" + prefs.get(key) + "\" /></span></div><br />\n");
            prefs.remove(key);
        }
        html.append("</div>");
        html.append("<div class='warning'><p class=''>" + ENC_WARNING
                + "All passwords are stored in plaintext.</div>");
        html.append("</div>");

        // Any remaining unclassified preferences
        if (!prefs.isEmpty()) {
            html.append("<div id='prefs_section_unknown' class='info-box prefs_section'><div class='title'>"
                    + "<i  class=\"fa fa-question\"></i>&nbsp;Uncategorized" + "</div>");
            html.append("<div class='content'>");
            for (String key : prefs.keySet()) {
                html.append("<div class=\"pref_input\"><span class=\"pref_key\">"
                        + "<i class=\"fa fa-question-circle \" " + "title=\""
                        + StringEscapeUtils.escapeHtml4(Coordinator.getPrefs().getPreferenceDesc(key))
                        + "\"></i>&nbsp;" + Coordinator.getPrefs().getPreferenceName(key) + "</span><span "
                        + "class=\"pref_value\"><input " + " type=\"text\" name=\"" + key + "\" value=\""
                        + prefs.get(key) + "\" /></span></div><br />\n");
            }
            html.append("</div></div>");
        }
        // end settings boxes div
        html.append("</div>");
        html.append("</form>");
        // clear the elements
        html.append("<div class=\"clear\"></div>");
        // html.append("<hr class=\"fancy-line\"></hr>");

        // buttons div
        html.append("<div id=\"settings_buttons_div\">");

        html.append("</div></div>");
        template = template.replace("!PROTOCOL!", webserver.getProtocol());
        template = template.replace("!MAIN_CONTENT!", html.toString());
        template = template.replace("!JAVASCRIPT!",
                "<script type='text/javascript' src='/resource?file=js/settings.js'></script>");
        returnBytes = template.getBytes();
    }
    return returnBytes;
}

From source file:org.opendatakit.aggregate.parser.FormParserForJavaRosa.java

private void guardedInitHelper(MultiPartFormData uploadedFormItems, MultiPartFormItem xformXmlData,
        String incomingFormXml, String persistenceStoreFormId, StringBuilder warnings, CallingContext cc)
        throws ODKDatastoreException, ODKFormAlreadyExistsException, ODKParseException,
        ODKIncompleteSubmissionData {//w  w  w  .j  av a2s. co  m
    // ///////////////
    // Step 1: create or fetch the Form (FormInfo) submission
    //
    // This allows us to delete the form if upload goes bad...
    // form downloads are immediately enabled unless the upload specifies
    // that they shouldn't be.
    String isIncompleteFlag = uploadedFormItems.getSimpleFormField(ServletConsts.TRANSFER_IS_INCOMPLETE);
    boolean isDownloadEnabled = (isIncompleteFlag == null || isIncompleteFlag.trim().length() == 0);

    /* true if newly created */
    boolean newlyCreatedXForm = false;
    /* true if we are modifying this form definition. */
    boolean updateForm;
    /* true if the form definition changes, but is compatible */
    @SuppressWarnings("unused")
    boolean differentForm = false;
    IForm formInfo = null;
    /*
     * originationGraceTime: if a previously loaded form was last updated prior
     * to the originationGraceTime, then require a version change if the new
     * form is not identical (is changed).
     */
    Date originationGraceTime = new Date(System.currentTimeMillis() - FIFTEEN_MINUTES_IN_MILLISECONDS);
    /*
     * originationTime: the time of the form's first upload to the system
     */
    Date originationTime;
    try {
        formInfo = FormFactory.retrieveFormByFormId(rootElementDefn.formId, cc);

        // formId matches...
        Boolean thisIsEncryptedForm = formInfo.isEncryptedForm();
        if (thisIsEncryptedForm == null) {
            thisIsEncryptedForm = false;
        }

        if (isFileEncryptedForm != thisIsEncryptedForm) {
            // they either both need to be encrypted, or both need to not be
            // encrypted...
            throw new ODKFormAlreadyExistsException(
                    "Form encryption status cannot be altered. Form Id must be changed.");
        }
        // isEncryptedForm matches...

        XFormParameters thisRootElementDefn = formInfo.getRootElementDefn();
        String thisTitle = formInfo.getViewableName();
        String thisMd5Hash = formInfo.getMd5HashFormXml(cc);
        String md5Hash = CommonFieldsBase.newMD5HashUri(incomingFormXml);

        boolean same = thisRootElementDefn.equals(rootElementDefn)
                && (thisMd5Hash == null || md5Hash.equals(thisMd5Hash));

        if (same) {
            // version matches
            if (thisMd5Hash == null) {
                // IForm record does not have any attached form definition XML
                // attach it, set the title, and flag the form as updating
                // NOTE: this is an error path and not a normal flow
                updateFormXmlVersion(formInfo, incomingFormXml, rootElementDefn.modelVersion, cc);
                formInfo.setViewableName(title);
                updateForm = true;
                originationTime = new Date();
            } else {
                // The md5Hash of the form file being uploaded matches that
                // of a fully populated IForm record.
                // Do not allow changing the title...
                if (!title.equals(thisTitle)) {
                    throw new ODKFormAlreadyExistsException(
                            "Form title cannot be changed without updating the form version");
                }
                updateForm = false;
                String existingFormXml = formInfo.getFormXml(cc);
                // get the upload time of the existing form definition
                originationTime = FormParserForJavaRosa.xmlTimestamp(existingFormXml);
            }
        } else {
            String existingFormXml = formInfo.getFormXml(cc);
            // get the upload time of the existing form definition
            originationTime = FormParserForJavaRosa.xmlTimestamp(existingFormXml);

            if (FormParserForJavaRosa.xmlWithoutTimestampComment(incomingFormXml)
                    .equals(FormParserForJavaRosa.xmlWithoutTimestampComment(existingFormXml))) {
                // (version and file match).
                // The text of the form file being uploaded matches that of a
                // fully-populated IForm record once the ODK Aggregate
                // TimestampComment is removed.

                // Do not allow changing the title...
                if (!title.equals(thisTitle)) {
                    throw new ODKFormAlreadyExistsException(
                            "Form title cannot be changed without updating the form version.");
                }
                updateForm = false;

            } else {
                // file is different...

                // determine if the form is storage-equivalent and if version is
                // increasing...
                DifferenceResult diffresult = FormParserForJavaRosa.compareXml(this, existingFormXml,
                        formInfo.getViewableName(), originationTime.after(originationGraceTime));
                if (diffresult == DifferenceResult.XFORMS_DIFFERENT) {
                    // form is not storage-compatible
                    throw new ODKFormAlreadyExistsException();
                }
                if (diffresult == DifferenceResult.XFORMS_MISSING_VERSION) {
                    throw new ODKFormAlreadyExistsException(
                            "Form definition file has changed but does not specify a form version.  Update the form version and resubmit.");
                }
                if (diffresult == DifferenceResult.XFORMS_EARLIER_VERSION) {
                    throw new ODKFormAlreadyExistsException(
                            "Form version is not lexically greater than existing form version.  Update the form version and resubmit.");
                }

                // update the title and form definition file as needed...
                if (!thisTitle.equals(title)) {
                    formInfo.setViewableName(title);
                }

                updateFormXmlVersion(formInfo, incomingFormXml, rootElementDefn.modelVersion, cc);

                // mark this as a different form...
                differentForm = true;
                updateForm = true;
                originationTime = new Date();
            }
        }
    } catch (ODKFormNotFoundException e) {
        // form is not found -- create it
        formInfo = FormFactory.createFormId(incomingFormXml, rootElementDefn, isFileEncryptedForm,
                isDownloadEnabled, title, cc);
        updateForm = false;
        newlyCreatedXForm = true;
        originationTime = new Date();
    }

    // and upload all the media files associated with the form.
    // Allow updates if the form version has changed (updateForm is true)
    // or if the originationTime is after the originationGraceTime
    // e.g., the form version was changed within the last 15 minutes.

    boolean allowUpdates = updateForm || originationTime.after(originationGraceTime);

    // If an update is attempted and we don't allow updates,
    // throw an ODKFormAlreadyExistsException
    // NOTE: we store new files during this process, in the
    // expectation that the user simply forgot to update the
    // version and will do so shortly and upload that revised
    // form.
    Set<Map.Entry<String, MultiPartFormItem>> fileSet = uploadedFormItems.getFileNameEntrySet();
    for (Map.Entry<String, MultiPartFormItem> itm : fileSet) {
        if (itm.getValue() == xformXmlData)
            continue;// ignore the xform -- stored above.

        // update the images if the form version changed, otherwise throw an
        // error.

        if (itm.getValue().getFilename().contains("settings")) {
            log.info("Adding settings: " + itm.getValue().getFilename());
            if (formInfo.setSettingsFile(itm.getValue(), allowUpdates, cc)) {
                // needed update
                if (!allowUpdates) {
                    // but we didn't update the form...
                    throw new ODKFormAlreadyExistsException(
                            "Form settings file(s) have changed.  Please update the form version and resubmit.");
                }
            }
            continue;
        }

        if (formInfo.setXFormMediaFile(itm.getValue(), allowUpdates, cc)) {
            // needed update
            if (!allowUpdates) {
                // but we didn't update the form...
                throw new ODKFormAlreadyExistsException(
                        "Form media file(s) have changed.  Please update the form version and resubmit.");
            }
        }
    }
    // NOTE: because of caching, we only update the form definition file at
    // intervals of no more than every 3 seconds. So if you upload a
    // media file, then immediately upload an altered version, we don't
    // necessarily increment the uiVersion.

    // Determine the information about the submission...
    formInfo.setIsComplete(true);
    formInfo.persist(cc);
    formInfo.setAccessEntry(cc);

    Datastore ds = cc.getDatastore();
    User user = cc.getCurrentUser();

    FormDefinition fdDefined = null;
    try {
        fdDefined = FormDefinition.getFormDefinition(submissionElementDefn.formId, cc);
    } catch (IllegalStateException e) {
        e.printStackTrace();
        throw new ODKFormAlreadyExistsException(
                "Internal error: the form already exists but has a bad form definition.  Delete it.");
    }
    if (fdDefined != null) {
        // get most recent form-deletion statuses
        if (newlyCreatedXForm) {
            throw new ODKFormAlreadyExistsException(
                    "Internal error: Completely new file has pre-existing form definition");
        }
        // we're done -- updated the file and media; form definition doesn't need
        // updating.
        return;
    }

    // we don't have an existing form definition
    // -- create a submission association table entry mapping to what will
    // be
    // the model.
    // -- then create the model and iterate on manifesting it in the
    // database.
    SubmissionAssociationTable sa = SubmissionAssociationTable
            .assertSubmissionAssociation(formInfo.getKey().getKey(), submissionElementDefn.formId, cc);
    fdmSubmissionUri = sa.getUriSubmissionDataModel();

    // so we have the formInfo record, but no data model backing it.
    // Find the submission associated with this form...

    final List<FormDataModel> fdmList = new ArrayList<FormDataModel>();

    // List of successfully asserted relations.
    // Use a HashMap<String,CommonFieldsBase>(). This allows us to
    // use the tableKey(CommonFieldsBase) (schema name + table name)
    // to identify the successfully asserted relations, rather than
    // the object identity of the CommonFieldsBase objects, which is
    // inappropriate for our use.
    final HashMap<String, CommonFieldsBase> assertedRelations = new HashMap<String, CommonFieldsBase>();

    try {
        // ////////////////////////////////////////////////
        // Step 2: Now build up the parse tree for the form...
        //
        final FormDataModel fdm = FormDataModel.assertRelation(cc);

        // we haven't actually constructed the fdm record yet, so use the
        // relation when creating the entity key...
        final EntityKey k = new EntityKey(fdm, fdmSubmissionUri);

        NamingSet opaque = new NamingSet();

        // construct the data model with table and column placeholders.
        // assumes that the root is a non-repeating group element.
        final String tableNamePlaceholder = opaque.getTableName(fdm.getSchemaName(), persistenceStoreFormId, "",
                "CORE");

        constructDataModel(opaque, k, fdmList, fdm, k.getKey(), 1, persistenceStoreFormId, "",
                tableNamePlaceholder, submissionElement, warnings, cc);

        // find a good set of names...
        // this also ensures that the table names don't overlap existing
        // tables
        // in the datastore.
        opaque.resolveNames(ds, user);

        // debug output
        // for ( FormDataModel m : fdmList ) {
        // m.print(System.out);
        // }

        // and revise the data model with those names...
        for (FormDataModel m : fdmList) {
            String tablePlaceholder = m.getPersistAsTable();
            if (tablePlaceholder == null)
                continue;

            String columnPlaceholder = m.getPersistAsColumn();

            String tableName = opaque.resolveTablePlaceholder(tablePlaceholder);
            String columnName = opaque.resolveColumnPlaceholder(tablePlaceholder, columnPlaceholder);

            m.setPersistAsColumn(columnName);
            m.setPersistAsTable(tableName);
        }

        // ///////////////////////////////////////////
        // Step 3: create the backing tables...
        //
        // OK. At this point, the construction gets a bit ugly.
        // We need to handle the possibility that the table
        // needs to be split into phantom tables.
        // That happens if the table exceeds the maximum row
        // size for the persistence layer.

        // we do this by constructing the form definition from the fdmList
        // and then testing for successful creation of each table it
        // defines.
        // If that table cannot be created, we subdivide it, rearranging
        // the structure of the fdmList. Repeat until no errors.
        // Very error prone!!!
        //
        FormDefinition fd = null;
        try {
            int nAttempts = 0;
            for (;;) {
                // place a limit on this process
                if (++nAttempts > MAX_FORM_CREATION_ATTEMPTS) {
                    log.error("Aborting form-creation due to fail-safe limit (" + MAX_FORM_CREATION_ATTEMPTS
                            + " attempts)!");
                    throw new ODKParseException("Unable to create form data tables after "
                            + MAX_FORM_CREATION_ATTEMPTS + " attempts.");
                }

                fd = new FormDefinition(sa, submissionElementDefn.formId, fdmList, cc);

                List<CommonFieldsBase> badTables = new ArrayList<CommonFieldsBase>();

                for (CommonFieldsBase tbl : fd.getBackingTableSet()) {
                    try {
                        // patch up tbl with desired lengths of string
                        // fields...
                        for (FormDataModel m : fdmList) {
                            if (m.getElementType().equals(ElementType.STRING)) {
                                DataField f = m.getBackingKey();
                                Integer i = fieldLengths.get(m);
                                if (f != null && i != null) {
                                    f.setMaxCharLen(new Long(i));
                                }
                            }
                        }

                        // CommonFieldsBase objects are re-constructed with each
                        // call to new FormDefinition(...). We need to ensure the
                        // datastore contains the table that each of these objects
                        // refers to.
                        //
                        // Optimization:
                        //
                        // If assertedRelations contains a hit for tableKey(tbl),
                        // then we can assume that the table exists in the datastore
                        // and just update the CommonFieldsBase object in the
                        // assertedRelations map.
                        //
                        // Otherwise, we need to see if we can create it.
                        //
                        // Later on, before we do any more work, we need to
                        // sweep through and call ds.assertRelation() to ensure
                        // that all the CommonFieldsBase objects are fully
                        // initialized (because we don't really know what is
                        // done in the persistence layers during the
                        // ds.assertRelation() call).
                        //
                        if (assertedRelations.containsKey(tableKey(tbl))) {
                            assertedRelations.put(tableKey(tbl), tbl);
                        } else {
                            ds.assertRelation(tbl, user);
                            assertedRelations.put(tableKey(tbl), tbl);
                        }
                    } catch (Exception e1) {
                        // assume it is because the table is too wide...
                        log.warn("Create failed -- assuming phantom table required " + tableKey(tbl)
                                + " Exception: " + e1.toString());
                        // we expect the following dropRelation to fail,
                        // as the most likely state of the system is
                        // that the table was unable to be created.
                        try {
                            ds.dropRelation(tbl, user);
                        } catch (Exception e2) {
                            // no-op
                        }
                        if ((tbl instanceof DynamicBase) || (tbl instanceof TopLevelDynamicBase)) {
                            /* we know how to subdivide these -- we can recover from this */
                            badTables.add(tbl);
                        } else {
                            /* there must be something amiss with the database... */
                            throw e1;
                        }
                    }
                }

                for (CommonFieldsBase tbl : badTables) {
                    // dang. We need to create phantom tables...
                    orderlyDivideTable(fdmList, FormDataModel.assertRelation(cc), tbl, opaque, cc);
                }

                if (badTables.isEmpty()) {
                    // OK. We created everything and have no re-work.
                    //
                    // Since this might be the N'th time through this
                    // loop, we may have incompletely initialized the
                    // CommonFieldsBase entries in the assertedRelations map.
                    //
                    // Go through that now, asserting each relation.
                    // This ensures that all those entries are
                    // properly initialized.
                    //
                    // Since this was once successful, it should still be.
                    // If it isn't then any database error thrown is
                    // not recoverable.
                    for (CommonFieldsBase tbl : assertedRelations.values()) {
                        ds.assertRelation(tbl, user);
                    }
                    break;
                }

                /*
                 * reset the derived fields so that the FormDefinition construction
                 * will work.
                 */
                for (FormDataModel m : fdmList) {
                    m.resetDerivedFields();
                }
            }
        } catch (Exception e) {
            /*
             * either something is amiss in the database or there was some sort of
             * internal error. Try to drop all the successfully created database
             * tables.
             */
            try {
                log.warn("Aborting form-creation do to exception: " + e.toString()
                        + ". Datastore exceptions are expected in the following stack trace; other exceptions may indicate a problem:");
                e.printStackTrace();

                /* if everything were OK, assertedRelations should be empty... */
                if (!assertedRelations.isEmpty()) {
                    log.error("assertedRelations not fully unwound!");
                    Iterator<Entry<String, CommonFieldsBase>> iter = assertedRelations.entrySet().iterator();
                    while (iter.hasNext()) {
                        Entry<String, CommonFieldsBase> entry = iter.next();
                        CommonFieldsBase tbl = entry.getValue();
                        try {
                            log.error("--dropping " + entry.getKey());
                            ds.dropRelation(tbl, user);
                        } catch (Exception e3) {
                            log.error("--Exception while dropping " + entry.getKey() + " exception: "
                                    + e3.toString());
                            // do nothing...
                            e3.printStackTrace();
                        }
                        // we tried our best... twice.
                        // Remove the definition whether
                        // or not we were successful.
                        // No point in ever trying again.
                        iter.remove();
                    }
                }

                // scorched earth -- get all the tables and try to drop them all...
                if (fd != null) {
                    for (CommonFieldsBase tbl : fd.getBackingTableSet()) {
                        try {
                            ds.dropRelation(tbl, user);
                            assertedRelations.remove(tableKey(tbl));
                        } catch (Exception e3) {
                            // the above may fail because the table was never created...
                            // do nothing...
                            log.warn(
                                    "If the following stack trace is not a complaint about a table not existing, it is likely a problem!");
                            e3.printStackTrace();
                        }
                    }
                }
            } catch (Exception e4) {
                // just log error... popping out to original exception
                log.error("dropping of relations unexpectedly failed with exception: " + e4.toString());
                e4.printStackTrace();
            }
            throw new ODKParseException("Error processing new form: " + e.toString());
        }
        // TODO: if the above gets killed, how do we clean up?
    } catch (ODKParseException e) {
        formInfo.deleteForm(cc);
        throw e;
    } catch (ODKDatastoreException e) {
        formInfo.deleteForm(cc);
        throw e;
    }

    // ////////////////////////////////////////////
    // Step 4: record the data model...
    //
    // if we get here, we were able to create the tables -- record the
    // form description....
    ds.putEntities(fdmList, user);

    // TODO: if above write fails, how do we clean this up?

    // and update the complete flag to indicate that upload was fully
    // successful.
    sa.setIsPersistenceModelComplete(true);
    ds.putEntity(sa, user);
    // And wait until the data is propagated across all server instances.
    //
    // Rather than relying on MemCache, we insert this delay here so that
    // any caller that is creating a form can know that the form definition
    // has been propagated across the front-ends (subject to fast/slow
    // clocks).
    // This assumes that server clock rates never cause drifts of more than
    // the
    // network transmission latency between the requester and the server
    // over
    // the PersistConsts.MAX_SETTLE_MILLISECONDS time period.
    //
    // After this delay interval, the caller can be confident that the form
    // is visible by whatever server receives the caller's next request
    // (and this is also true during unit tests).
    try {
        Thread.sleep(PersistConsts.MAX_SETTLE_MILLISECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.site.tool.SiteAction.java

/**
 * getFeatures gets features for a new site
 * /*from ww  w  .  j a  v  a 2s  .com*/
 */
private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) {
    List idsSelected = new Vector();

    List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null ? new Vector()
            : (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST);
    // to reset the state variable of the multiple tool instances
    Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null
            ? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET)
            : new HashSet();
    // get the map of titles of multiple tool instances
    Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null
            ? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP)
            : new HashMap();

    // related to LTI Tool selection
    Map<String, Map<String, Object>> existingLtiIds = state
            .getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null
                    ? (Map<String, Map<String, Object>>) state
                            .getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST)
                    : null;
    HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state
            .getAttribute(STATE_LTITOOL_LIST);
    HashMap<String, Map<String, Object>> ltiSelectedTools = new HashMap<String, Map<String, Object>>();

    boolean goToToolConfigPage = false;
    boolean homeSelected = false;
    // lti tool selection
    boolean ltiToolSelected = false;

    // Add new pages and tools, if any
    if (params.getStrings("selectedTools") == null && params.getStrings("selectedLtiTools") == null) {
        addAlert(state, rb.getString("atleastonetool"));
    } else {
        List l = new ArrayList(Arrays.asList(params.getStrings("selectedTools"))); // toolId's of chosen tools

        for (int i = 0; i < l.size(); i++) {
            String toolId = (String) l.get(i);

            if (toolId.equals(TOOL_ID_HOME)) {
                homeSelected = true;
                if (!idsSelected.contains(toolId))
                    idsSelected.add(toolId);
            } else if (toolId.startsWith(LTITOOL_ID_PREFIX)) {
                String ltiToolId = toolId.substring(LTITOOL_ID_PREFIX.length());
                // whether there is any lti tool been selected
                if (existingLtiIds == null) {
                    ltiToolSelected = true;
                } else {
                    if (!existingLtiIds.keySet().contains(ltiToolId)) {
                        // there are some new lti tool(s) selected
                        ltiToolSelected = true;
                    }
                }

                // add tool entry to list
                ltiSelectedTools.put(ltiToolId, ltiTools.get(ltiToolId));
            } else {
                String originId = findOriginalToolId(state, toolId);
                if (isMultipleInstancesAllowed(originId)) {
                    // if user is adding either EmailArchive tool, News tool
                    // or Web Content tool, go to the Customize page for the
                    // tool
                    if (!existTools.contains(toolId)) {
                        goToToolConfigPage = true;
                        if (!multipleToolIdSet.contains(toolId))
                            multipleToolIdSet.add(toolId);
                        if (!multipleToolIdTitleMap.containsKey(toolId)) {
                            // reset tool title if there is a different title config setting
                            String titleConfig = ServerConfigurationService
                                    .getString(CONFIG_TOOL_TITLE + originId);
                            if (titleConfig != null && titleConfig.length() > 0) {
                                multipleToolIdTitleMap.put(toolId, titleConfig);
                            } else {
                                multipleToolIdTitleMap.put(toolId, ToolManager.getTool(originId).getTitle());
                            }
                        }
                    }
                } else if ("sakai.mailbox".equals(toolId)) {
                    // get the email alias when an Email Archive tool
                    // has been selected
                    String alias = getSiteAlias(
                            mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID)));
                    if (alias != null) {
                        state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, alias);
                    }
                    // go to the config page
                    if (!existTools.contains(toolId)) {
                        goToToolConfigPage = true;
                    }

                }
                if (!idsSelected.contains(toolId))
                    idsSelected.add(toolId);
            }

        }

        state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(homeSelected));

        if (!ltiSelectedTools.isEmpty()) {
            state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiSelectedTools);
        } else {
            state.removeAttribute(STATE_LTITOOL_SELECTED_LIST);
        }
    }

    state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's

    // in case of import
    String importString = params.getString("import");
    if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) {
        state.setAttribute(STATE_IMPORT, Boolean.TRUE);

        List importSites = new Vector();
        if (params.getStrings("importSites") != null) {
            importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
        }
        if (importSites.size() == 0) {
            addAlert(state, rb.getString("java.toimport") + " ");
        } else {
            Hashtable sites = new Hashtable();
            for (int index = 0; index < importSites.size(); index++) {
                try {
                    Site s = SiteService.getSite((String) importSites.get(index));
                    if (!sites.containsKey(s)) {
                        sites.put(s, new Vector());
                    }
                } catch (IdUnusedException e) {
                }
            }
            state.setAttribute(STATE_IMPORT_SITES, sites);
        }
    } else {
        state.removeAttribute(STATE_IMPORT);
    }

    // of
    // ToolRegistration
    // toolId's
    if (state.getAttribute(STATE_MESSAGE) == null) {
        if (state.getAttribute(STATE_IMPORT) != null) {
            // go to import tool page
            state.setAttribute(STATE_TEMPLATE_INDEX, "27");
        } else if (goToToolConfigPage || ltiToolSelected) {
            state.setAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, Boolean.valueOf(goToToolConfigPage));
            // go to the configuration page for multiple instances of tools
            state.setAttribute(STATE_TEMPLATE_INDEX, "26");
        } else {
            // go to next page
            state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex);
        }
        state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet);
        state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap);
    }
}