Example usage for org.springframework.util MultiValueMap getFirst

List of usage examples for org.springframework.util MultiValueMap getFirst

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap getFirst.

Prototype

@Nullable
V getFirst(K key);

Source Link

Document

Return the first value for the given key.

Usage

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void invalidScopeErrorMessageIsNotShowingAllUserScopes() throws Exception {
    String clientId = "testclient" + generator.generate();
    String scopes = "openid,password.write,cloud_controller.read,scim.userids,password.write,something.else";
    setUpClients(clientId, scopes, scopes, "authorization_code", true);

    String username = "testuser" + generator.generate();
    ScimUser developer = setUpUser(username, "openid", OriginKeys.UAA, IdentityZoneHolder.getUaaZone().getId());
    MockHttpSession session = getAuthenticatedSession(developer);

    String basicDigestHeaderValue = "Basic " + new String(
            org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + SECRET).getBytes()));

    String state = generator.generate();
    MockHttpServletRequestBuilder authRequest = get("/oauth/authorize")
            .header("Authorization", basicDigestHeaderValue).session(session)
            .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.SCOPE, "something.else")
            .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
            .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI);

    MvcResult mvcResult = getMockMvc().perform(authRequest).andExpect(status().is3xxRedirection()).andReturn();

    UriComponents locationComponents = UriComponentsBuilder
            .fromUri(URI.create(mvcResult.getResponse().getHeader("Location"))).build();
    MultiValueMap<String, String> queryParams = locationComponents.getQueryParams();
    String errorMessage = URIUtil
            .encodeQuery("[something.else] is invalid. This user is not allowed any of the requested scopes");
    assertTrue(!queryParams.containsKey("scope"));
    assertEquals(errorMessage, queryParams.getFirst("error_description"));
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;/*from   w  w w  .ja  v  a2s.c  om*/
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        UaaUser uaaUser = userDatabase.retrieveUserByEmail(userWithSamlAttributes.getEmail(),
                samlPrincipal.getOrigin());
        if (uaaUser != null) {
            user = uaaUser.modifyUsername(samlPrincipal.getName());
        } else {
            if (!addNew) {
                throw new LoginSAMLException("SAML user does not exist. "
                        + "You can correct this by creating a shadow user for the SAML user.", e);
            }
            // Register new users automatically
            publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
            try {
                user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
            } catch (UsernameNotFoundException ex) {
                throw new BadCredentialsException(
                        "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
            }
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

From source file:org.cloudfoundry.identity.uaa.provider.saml.LoginSamlAuthenticationProvider.java

protected UaaUser getUser(UaaPrincipal principal, MultiValueMap<String, String> userAttributes) {
    String name = principal.getName();
    String email = userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME);
    String givenName = userAttributes.getFirst(GIVEN_NAME_ATTRIBUTE_NAME);
    String familyName = userAttributes.getFirst(FAMILY_NAME_ATTRIBUTE_NAME);
    String phoneNumber = userAttributes.getFirst(PHONE_NUMBER_ATTRIBUTE_NAME);
    String userId = OriginKeys.NotANumber;
    String origin = principal.getOrigin() != null ? principal.getOrigin() : OriginKeys.LOGIN_SERVER;
    String zoneId = principal.getZoneId();
    if (name == null && email != null) {
        name = email;/*from   w w  w.jav a 2  s .c  om*/
    }
    if (name == null && OriginKeys.NotANumber.equals(userId)) {
        throw new BadCredentialsException("Cannot determine username from credentials supplied");
    } else if (name == null) {
        //we have user_id, name is irrelevant
        name = "unknown";
    }
    if (email == null) {
        if (name.contains("@")) {
            if (name.split("@").length == 2 && !name.startsWith("@") && !name.endsWith("@")) {
                email = name;
            } else {
                email = name.replaceAll("@", "") + "@unknown.org";
            }
        } else {
            email = name + "@unknown.org";
        }
    }
    if (givenName == null) {
        givenName = email.split("@")[0];
    }
    if (familyName == null) {
        familyName = email.split("@")[1];
    }
    return new UaaUser(new UaaUserPrototype().withEmail(email).withGivenName(givenName)
            .withFamilyName(familyName).withPhoneNumber(phoneNumber).withModified(new Date()).withId(userId)
            .withUsername(name).withPassword("").withAuthorities(Collections.EMPTY_LIST).withCreated(new Date())
            .withOrigin(origin).withExternalId(name).withVerified(true).withZoneId(zoneId).withSalt(null)
            .withPasswordLastModified(null));
}

From source file:org.ednovo.gooru.domain.service.ScollectionServiceImpl.java

@Override
public Collection updateCollectionMetadata(final String collectionId, final String creatorUId, String ownerUId,
        final boolean hasUnrestrictedContentAccess, final MultiValueMap<String, String> data,
        final User apiCallerUser) {
    final Collection collection = this.getCollectionByGooruOid(collectionId, null);
    rejectIfNull(collection, GL0056, _COLLECTION);
    Boolean taxonomyByCode = false;
    final String taxonomyCode = data.getFirst(TAXONOMY_CODE);
    final String title = data.getFirst(TITLE);
    final String description = data.getFirst(DESCRIPTION);
    final String grade = data.getFirst(GRADE);
    final String sharing = data.getFirst(SHARING);
    final String narrationLink = data.getFirst(NARRATION_LINK);
    final String updateTaxonomyByCode = data.getFirst(UPDATE_TAXONOMY_BY_CODE);
    final String action = data.getFirst(ACTION);
    final String buildType = data.getFirst(BUILD_TYPE);

    if (isNotEmptyString(updateTaxonomyByCode) && updateTaxonomyByCode.equalsIgnoreCase(TRUE)) {
        taxonomyByCode = true;/*from  w w  w. j a  v a 2 s  . c  o m*/
    }

    if (isNotEmptyString(taxonomyCode)) {
        if (isNotEmptyString(action) && action.equalsIgnoreCase(DELETE)) {
            deleteCollectionTaxonomy(collection, taxonomyCode, taxonomyByCode);
        } else {
            addCollectionTaxonomy(collection, taxonomyCode, taxonomyByCode);
        }
        this.getCollectionRepository().save(collection);
    }
    /*
     * if (isNotEmptyString(buildType)) { if
     * (buildType.equalsIgnoreCase(WEB) || buildType.equalsIgnoreCase(IPAD))
     * { collection.setBuildType(this.getCustomTableRepository().
     * getCustomTableValue(CustomProperties.Table.BUILD_TYPE.getTable(),
     * buildType)); } }
     */
    if (isNotEmptyString(title)) {
        collection.setTitle(title);
    }

    collection.setLastUpdatedUserUid(apiCallerUser.getPartyUid());

    if (isNotEmptyString(sharing)) {
        collection.setSharing(sharing);
        this.getCollectionRepository().save(collection);
        resetFolderVisibility(collection.getGooruOid(), apiCallerUser.getPartyUid());
        updateResourceSharing(sharing, collection);
    }

    if (data.containsKey(GRADE)) {
        saveOrUpdateCollectionGrade(grade, collection, false);
    }
    if (isNotEmptyString(narrationLink)) {
        collection.setNarrationLink(narrationLink);
    }

    if (hasUnrestrictedContentAccess) {
        if (creatorUId != null) {
            User user = getUserService().findByGooruId(creatorUId);
            collection.setCreator(user);
        }
        if (ownerUId != null) {
            final User user = getUserService().findByGooruId(ownerUId);
            collection.setUser(user);
        }
    }
    this.setCollectionMetaData(collection, null, null, true, null, false, false, false);
    this.getCollectionRepository().save(collection);
    try {
        indexHandler.setReIndexRequest(collection.getGooruOid(), IndexProcessor.INDEX, SCOLLECTION, null, false,
                false);
    } catch (Exception e) {
        LOGGER.error(_ERROR, e);
    }
    getAsyncExecutor().deleteFromCache(V2_ORGANIZE_DATA + collection.getUser().getPartyUid() + "*");

    return collection;
}

From source file:org.ednovo.gooru.domain.service.ScollectionServiceImpl.java

@Override
public CollectionItem updateCollectionItemMetadata(final String collectionItemId,
        final MultiValueMap<String, String> data, final User apiCaller) {

    final CollectionItem collectionItem = this.getCollectionItemById(collectionItemId);

    rejectIfNull(collectionItem, GL0056, _COLLECTION_ITEM);

    ServerValidationUtils.rejectIfMaxLimitExceed(8, data.getFirst(NARRATION_TYPE), "GL0014", NARRATION_TYPE,
            "8");
    ServerValidationUtils.rejectIfMaxLimitExceed(8, data.getFirst(START), "GL0014", START, "8");
    ServerValidationUtils.rejectIfMaxLimitExceed(8, data.getFirst(STOP), "GL0014", STOP, "8");

    final String narration = data.getFirst(NARRATION);
    final String narrationType = data.getFirst(NARRATION_TYPE);
    final String start = data.getFirst(START);
    final String stop = data.getFirst(STOP);

    if (data.containsKey(NARRATION)) {
        collectionItem.setNarration(narration);
    }// www .j a  va2  s.  c o  m
    if (isNotEmptyString(narrationType)) {
        collectionItem.setNarrationType(narrationType);
    }
    if (data.containsKey(START)) {
        collectionItem.setStart(start);
    }
    if (data.containsKey(STOP)) {
        collectionItem.setStop(stop);
    }

    this.getCollectionRepository().save(collectionItem);
    try {
        indexHandler.setReIndexRequest(collectionItem.getContent().getGooruOid(), IndexProcessor.INDEX,
                RESOURCE, null, false, false);
        indexHandler.setReIndexRequest(collectionItem.getCollection().getGooruOid(), IndexProcessor.INDEX,
                SCOLLECTION, null, false, false);
    } catch (Exception e) {
        LOGGER.error(_ERROR, e);
    }
    getAsyncExecutor()
            .deleteFromCache(V2_ORGANIZE_DATA + collectionItem.getCollection().getUser().getPartyUid() + "*");
    return collectionItem;
}

From source file:org.ednovo.gooru.domain.service.user.impl.UserServiceImpl.java

@Override
public Profile updateUserInfo(String gooruUId, MultiValueMap<String, String> data, User apiCaller,
        Boolean isDisableUser) throws Exception {
    Boolean reIndexUserContent = false;
    if (gooruUId == null || gooruUId.equalsIgnoreCase("")) {
        throw new BadRequestException("User Id cannot be null or empty");
    }/*from w  w  w.  j  a va2 s .  c  o  m*/

    if (isDisableUser && ((!apiCaller.getGooruUId().equals(gooruUId)) || (!isContentAdmin(apiCaller)))) {
        throw new AccessDeniedException("You are not authorized to perform this action");
    }

    String firstName = data.getFirst(FIRST_NAME);
    String lastName = data.getFirst(LAST_NAME);
    String gender = data.getFirst(GENDER);
    String birthDate = data.getFirst(BIRTH_DATE);
    String birthMonth = data.getFirst(BIRTH_MONTH);
    String birthYear = data.getFirst(BIRTH_YEAR);
    String aboutMe = data.getFirst(ABOUT_ME);
    String highestDegree = data.getFirst(HIGHEST_DEGREE);
    String graduation = data.getFirst(GRADUATION);
    String postGraduation = data.getFirst(POST_GRADUATION);
    String highSchool = data.getFirst(HIGH__SCHOOL);
    String website = data.getFirst(WEBSITE);
    String facebook = data.getFirst(FACE_BOOK);
    String twitter = data.getFirst(TWITTER);
    String email = data.getFirst(EMAIL);
    String subject = data.getFirst(SUBJECT);
    String grade = data.getFirst(GRADE);
    String school = data.getFirst(SCHOOL);
    String username = data.getFirst(USER_NAME);
    String teachingExperience = data.getFirst(TEACHING_EXP);
    String teachingIn = data.getFirst(TEACHING_IN);
    String teachingMethodology = data.getFirst(TEACHING_METHODOLOGY);
    String dateOfBirth = data.getFirst(DATEOFBIRTH);
    String password = data.getFirst(PASSWORD);
    String userType = data.getFirst(USER_ROLE);

    Identity identity = this.getUserRepository().findUserByGooruId(gooruUId);

    Profile profile = this.getUserRepository().getProfile(getUser(gooruUId), false);

    User user = profile.getUser();
    if ((user != null) && (user.getConfirmStatus() == 0)) {
        user.setConfirmStatus(1);
    }

    if (isNotEmptyString(firstName)) {
        user.setFirstName(firstName);
        reIndexUserContent = true;
    }
    if (isNotEmptyString(lastName)) {
        user.setLastName(lastName);
        reIndexUserContent = true;
    }

    if (isNotEmptyString(gender)) {
        profile.setGender(this.getUserRepository().getGenderByGenderId(gender));
    }

    if (isNotEmptyString(dateOfBirth)) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date date = dateFormat.parse(dateOfBirth);
        profile.setDateOfBirth(date);

    }

    // if(isContentAdmin(apiCaller)){
    if (isNotEmptyString(birthDate)) {
        profile.setBirthDate(Integer.parseInt(birthDate));
    }

    if (isNotEmptyString(birthMonth)) {
        profile.setBirthMonth((Integer.parseInt(birthMonth)));
    }

    if (isNotEmptyString(birthYear)) {
        profile.setBirthYear(Integer.parseInt(birthYear));
    }

    if (isNotEmptyString(username)) {

        usernameValidation(username, user.getOrganization().getPartyUid());

        if (isNotEmptyString(password)) {
            validatePassword(password, username);
        }

        boolean usernameAvailability = this.getUserRepository().checkUserAvailability(username,
                CheckUser.BYUSERNAME, false);
        if (usernameAvailability) {
            throw new BadRequestException(
                    "Someone already has taken " + username + "!.Please pick another username.");
        } else {
            user.setUsername(username);
            reIndexUserContent = true;
        }
    }

    Boolean saveIdentity = false;

    if (isNotEmptyString(firstName)) {
        identity.setFirstName(firstName);
    }

    if (isNotEmptyString(lastName)) {
        identity.setLastName(lastName);
    }

    if (isNotEmptyString(email)) {

        boolean emailAvailability = this.getUserRepository().checkUserAvailability(email, CheckUser.BYEMAILID,
                false);

        if (emailAvailability) {
            throw new BadRequestException(
                    "Someone already has taken " + email + "!.Please pick another email.");
        }

        identity.setExternalId(email);
        reIndexUserContent = true;
        saveIdentity = true;

    }

    if (isDisableUser) {
        identity.setActive(Short.parseShort(ZERO));
        user.setConfirmStatus(0);
        saveIdentity = true;
    }

    if (saveIdentity) {
        this.getUserRepository().save(identity);
    }
    // }

    // set password for parent or non parent

    Credential creds = identity.getCredential();
    if (creds != null) {
        creds.setIdentity(identity);
    }
    if (password != null) {
        creds.setPassword(encryptPassword(password));
        this.getUserRepository().save(creds);
    }

    if (isNotEmptyString(aboutMe)) {
        profile.setAboutMe(aboutMe);
    }
    if (isNotEmptyString(highestDegree)) {
        profile.setHighestDegree(highestDegree);
    }
    if (isNotEmptyString(graduation)) {
        profile.setGraduation(graduation);
    }
    if (isNotEmptyString(postGraduation)) {
        profile.setPostGraduation(postGraduation);
    }
    if (isNotEmptyString(highSchool)) {
        profile.setHighSchool(highSchool);
    }
    if (isNotEmptyString(website)) {
        profile.setWebsite(website);
    }
    if (isNotEmptyString(facebook)) {
        profile.setFacebook(facebook);
    }
    if (isNotEmptyString(twitter)) {
        profile.setTwitter(twitter);
    }
    if (isNotEmptyString(subject)) {
        profile.setSubject(subject);
    }
    if (isNotEmptyString(grade)) {
        profile.setGrade(grade);
    }
    if (isNotEmptyString(school)) {
        profile.setSchool(school);
    }
    if (isNotEmptyString(teachingExperience)) {
        profile.setTeachingExperience(teachingExperience);
    }
    if (isNotEmptyString(teachingIn)) {
        profile.setTeachingIn(teachingIn);
    }
    if (isNotEmptyString(teachingMethodology)) {
        profile.setTeachingMethodology(teachingMethodology);
    }
    if (isNotEmptyString(userType)) {
        profile.setUserType(userType);
    }

    profile.setUser(user);

    this.getUserRepository().save(profile);

    PartyCustomField partyCustomField = this.getPartyService()
            .getPartyCustomeField(profile.getUser().getPartyUid(), "user_confirm_status", profile.getUser());

    if (partyCustomField == null) {
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put(GOORU_UID, profile.getUser().getPartyUid());
        dataMap.put(EVENT_TYPE, CustomProperties.EventMapping.WELCOME_MAIL.getEvent());
        if (profile.getUser().getAccountTypeId() != null
                && profile.getUser().getAccountTypeId().equals(UserAccountType.ACCOUNT_CHILD)) {
            if (profile.getUser().getParentUser().getIdentities() != null) {
                dataMap.put("recipient",
                        profile.getUser().getParentUser().getIdentities().iterator().next().getExternalId());
            }
        } else {
            if (profile.getUser().getIdentities() != null) {
                dataMap.put("recipient", profile.getUser().getIdentities().iterator().next().getExternalId());
            }
        }
        this.getUserRepository().save(
                new PartyCustomField(profile.getUser().getPartyUid(), USER_META, USER_CONFIRM_STATUS, TRUE));
        this.getMailHandler().handleMailEvent(dataMap);
    }

    if (user != null && identity.getAccountCreatedType() != null
            && identity.getAccountCreatedType()
                    .equalsIgnoreCase(UserAccountType.accountCreatedType.SSO.getType())
            && user.getViewFlag() == 0) {
        password = BaseUtil.generateBase48Encode(7);
        creds.setPassword(encryptPassword(password));
        this.getUserRepository().save(creds);
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put(EVENT_TYPE, CustomProperties.EventMapping.SSO_CONFIRMATION_MAIL.getEvent());
        dataMap.put(GOORU_UID, user.getGooruUId());
        dataMap.put(PASSWORD, password);
        this.getMailHandler().handleMailEvent(dataMap);
    }
    indexHandler.setReIndexRequest(user.getPartyUid(), IndexProcessor.INDEX, USER, null, reIndexUserContent,
            false);
    return profile;

}

From source file:org.flowable.app.rest.api.ApiModelResource.java

/**
 * POST /editor/models/{modelId}/editor/json -> save the JSON model
 *///from ww  w . j a  v  a 2  s.c o m
@RequestMapping(value = "/editor/models/{modelId}/editor/json", method = RequestMethod.POST)
public ModelRepresentation saveModel(@PathVariable String modelId,
        @RequestBody MultiValueMap<String, String> values) {

    // Validation: see if there was another update in the meantime
    long lastUpdated = -1L;
    String lastUpdatedString = values.getFirst("lastUpdated");
    if (lastUpdatedString == null) {
        throw new BadRequestException("Missing lastUpdated date");
    }
    try {
        Date readValue = objectMapper.getDeserializationConfig().getDateFormat().parse(lastUpdatedString);
        lastUpdated = readValue.getTime();
    } catch (ParseException e) {
        throw new BadRequestException("Invalid lastUpdated date: '" + lastUpdatedString + "'");
    }

    Model model = modelService.getModel(modelId);
    User currentUser = SecurityUtils.getCurrentUserObject();
    boolean currentUserIsOwner = model.getLastUpdatedBy().equals(currentUser.getId());
    String resolveAction = values.getFirst("conflictResolveAction");

    // If timestamps differ, there is a conflict or a conflict has been resolved by the user
    if (model.getLastUpdated().getTime() != lastUpdated) {

        if (RESOLVE_ACTION_SAVE_AS.equals(resolveAction)) {

            String saveAs = values.getFirst("saveAs");
            String json = values.getFirst("json_xml");
            return createNewModel(saveAs, model.getDescription(), model.getModelType(), json);

        } else if (RESOLVE_ACTION_OVERWRITE.equals(resolveAction)) {
            return updateModel(model, values, false);
        } else if (RESOLVE_ACTION_NEW_VERSION.equals(resolveAction)) {
            return updateModel(model, values, true);
        } else {

            // Exception case: the user is the owner and selected to create a new version
            String isNewVersionString = values.getFirst("newversion");
            if (currentUserIsOwner && "true".equals(isNewVersionString)) {
                return updateModel(model, values, true);
            } else {
                // Tried everything, this is really a conflict, return 409
                ConflictingRequestException exception = new ConflictingRequestException(
                        "Process model was updated in the meantime");
                exception.addCustomData("userFullName", model.getLastUpdatedBy());
                exception.addCustomData("newVersionAllowed", currentUserIsOwner);
                throw exception;
            }
        }

    } else {

        // Actual, regular, update
        return updateModel(model, values, false);

    }
}

From source file:org.flowable.app.rest.api.ApiModelResource.java

protected ModelRepresentation updateModel(Model model, MultiValueMap<String, String> values,
        boolean forceNewVersion) {

    String name = values.getFirst("name");
    String key = values.getFirst("key");
    String description = values.getFirst("description");
    String isNewVersionString = values.getFirst("newversion");
    String newVersionComment = null;

    ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(), key);
    if (modelKeyInfo.isKeyAlreadyExists()) {
        throw new BadRequestException("Model with provided key already exists " + key);
    }/*from w  w  w .j a v  a 2  s  . c  o  m*/

    boolean newVersion = false;
    if (forceNewVersion) {
        newVersion = true;
        newVersionComment = values.getFirst("comment");
    } else {
        if (isNewVersionString != null) {
            newVersion = "true".equals(isNewVersionString);
            newVersionComment = values.getFirst("comment");
        }
    }

    String json = values.getFirst("json_xml");

    try {
        model = modelService.saveModel(model.getId(), name, key, description, json, newVersion,
                newVersionComment, SecurityUtils.getCurrentUserObject());
        return new ModelRepresentation(model);

    } catch (Exception e) {
        LOGGER.error("Error saving model {}", model.getId(), e);
        throw new BadRequestException("Process model could not be saved " + model.getId());
    }
}

From source file:org.flowable.ui.modeler.rest.app.ModelResource.java

protected ModelRepresentation updateModel(Model model, MultiValueMap<String, String> values,
        boolean forceNewVersion) {

    String name = values.getFirst("name");
    String key = values.getFirst("key").replaceAll(" ", "");
    String description = values.getFirst("description");
    String isNewVersionString = values.getFirst("newversion");
    String newVersionComment = null;

    ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(), key);
    if (modelKeyInfo.isKeyAlreadyExists()) {
        throw new BadRequestException("Model with provided key already exists " + key);
    }/*from ww  w  . j  av a  2 s.c  o  m*/

    boolean newVersion = false;
    if (forceNewVersion) {
        newVersion = true;
        newVersionComment = values.getFirst("comment");
    } else {
        if (isNewVersionString != null) {
            newVersion = "true".equals(isNewVersionString);
            newVersionComment = values.getFirst("comment");
        }
    }

    String json = values.getFirst("json_xml");

    try {
        ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(json);

        ObjectNode propertiesNode = (ObjectNode) editorJsonNode.get("properties");
        String processId = key;
        propertiesNode.put("process_id", processId);
        propertiesNode.put("name", name);
        if (StringUtils.isNotEmpty(description)) {
            propertiesNode.put("documentation", description);
        }
        editorJsonNode.set("properties", propertiesNode);
        model = modelService.saveModel(model.getId(), name, key, description, editorJsonNode.toString(),
                newVersion, newVersionComment, SecurityUtils.getCurrentUserObject());
        return new ModelRepresentation(model);

    } catch (Exception e) {
        LOGGER.error("Error saving model {}", model.getId(), e);
        throw new BadRequestException("Process model could not be saved " + model.getId());
    }
}

From source file:org.jasig.cas.support.rest.TicketsResource.java

/**
 * Create new service ticket./*  ww w .ja  v  a  2  s  .  c  o m*/
 *
 * @param requestBody service application/x-www-form-urlencoded value
 * @param tgtId ticket granting ticket id URI path param
 * @return @return ResponseEntity representing RESTful response
 */
@RequestMapping(value = "/tickets/{tgtId:.+}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public final ResponseEntity<String> createServiceTicket(
        @RequestBody final MultiValueMap<String, String> requestBody,
        @PathVariable("tgtId") final String tgtId) {
    try {
        final String serviceTicketId = this.cas.grantServiceTicket(tgtId,
                new SimpleWebApplicationServiceImpl(requestBody.getFirst("service")));
        return new ResponseEntity<String>(serviceTicketId, HttpStatus.OK);
    } catch (final InvalidTicketException e) {
        return new ResponseEntity<String>("TicketGrantingTicket could not be found", HttpStatus.NOT_FOUND);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}